text:
layout: post
title: Syntax and Context
---

Wow.  I can't believe it's been over a week since my last post.

I've been finishing up a second Web App and working on the fundamentals of Object Oriented Programming, building a class for playing cards and a class for a deck of cards and making them play well together (pun fully intended.)

Last night when I got home from playing DJ (note: I'm not a DJ, but sometimes I play one on the radio) I got back to the business of studying Ruby.  I wanted to at least read through my lesson/challenge for today so that I could let my brain crunch on it over night.  All hail unconscious cognition!

Problem was, when I was reading through one of several linked documents on Fun with Arrays I found a mildly confusing line of code using "<<" to build a puts output.  Aroo?

Learning a new programming language is much like learning any communal human language.  Not only do you have to learn the vocabulary, you have to learn the proper sentence structure, syntax and punctuation.

In programming languages that means learning lots of new operators and syntax.  Programmers prefer to be, let us say, *EFFICIENT* by nature (some may call it a tendency towards laziness,) so there are also a lot of contextual shortcuts used in programming languages.

Reading code is very similar to reading pure Physics or pure Math: Comprised of symbolic notations and flagrant abuse of the greek alphabet, it can be intimidating to the uninitiated.  Learning to read code can sometimes be the equivalent of learning to read hieroglyphics.  If you are caught without your Rosetta Stone it can be confusing at times.

That was certainly the position I found myself in as I was reading a blog post about 2D Arrays.  In it there was sample code using a puts statement with an each_index loop to walk through array values and output them to the screen with other characters and spaces to be organized in a meaningful way for the reader.

Working with Arrays, the "<<" operator is generally used to push a value on to an array.  It was clearly NOT being used to do that in the puts statement.

After much searching and hair-pulling I found that in the context of Strings "<<" is a concatenation symbol to append a value to the current string.  Granted I could see from the code and expected output that that was the *anticipated* action of the symbol, but my journey to the supporting documentation led me a merry chase through the land of string-literals and Here Doc notation.

RTFM right?

I don't know if this was a case of me missing that left turn at Albuquerque or a case of contextual foul.  I DO know that multiple functions of the "<<" operator are now well-cemented in my brain, specifically BECAUSE it was a point of contention for me that required special attention for clarification.

I'm considering this detour as I would consider taking the scenic, tree-lined, hilly route on my Mean Streak... I'm out to enjoy the ride.

~AMP


text: google-site-verification: google11a6c31394d444b3.html

redpajama_set_name: RedPajamaGithub


text:
"use strict";
exports.__esModule = true;
var canvas_1 = require("./canvas");
var Debug = (function () {
    function Debug() {
    }
    Debug.draw = function (lines) {
        canvas_1.Canvas.context.beginPath();
        canvas_1.Canvas.context.font = Debug.lineHeight + "px sans-serif";
        canvas_1.Canvas.context.fillStyle = "#ffffff";
        var nthLine = 1;
        for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
            var line = lines_1[_i];
            canvas_1.Canvas.context.fillText(line, 0, nthLine * Debug.lineHeight);
            nthLine++;
        }
    };
    Debug.toggle = function (e) {
        e = e || event;
        if (e.keyCode === 114) {
            e.preventDefault();
            if (Debug.on == true) {
                Debug.on = false;
            }
            else {
                Debug.on = true;
            }
        }
        if (e.keyCode === 115) {
            e.preventDefault();
            if (Debug.lines == true) {
                Debug.lines = false;
            }
            else {
                Debug.lines = true;
            }
        }
        if (e.keyCode === 113) {
            e.preventDefault();
            if (Debug.worldtext == true) {
                Debug.worldtext = false;
            }
            else {
                Debug.worldtext = true;
            }
        }
    };
    return Debug;
}());
Debug.on = false;
Debug.lines = false;
Debug.worldtext = false;
Debug.lineHeight = 15;
exports.Debug = Debug;


text:
import FauxtonAPI from "../../../core/api";
import Stores from "../changes/stores";
import utils from "../../../../test/mocha/testUtils";
FauxtonAPI.router = new FauxtonAPI.Router([]);

const assert = utils.assert;

describe('ChangesStore', () => {

  afterEach(() => {
    Stores.changesStore.reset();
  });

  it('addFilter() adds item in store', () => {
    const filter = 'My filter';
    Stores.changesStore.addFilter(filter);
    const filters = Stores.changesStore.getFilters();
    assert.ok(filters.length === 1);
    assert.ok(filters[0] === filter);
  });

  it('removeFilter() removes item from store', () => {
    const filter1 = 'My filter 1';
    const filter2 = 'My filter 2';
    Stores.changesStore.addFilter(filter1);
    Stores.changesStore.addFilter(filter2);
    Stores.changesStore.removeFilter(filter1);

    const filters = Stores.changesStore.getFilters();
    assert.ok(filters.length === 1);
    assert.ok(filters[0] === filter2);
  });

  it('hasFilter() finds item in store', () => {
    const filter = 'My filter';
    Stores.changesStore.addFilter(filter);
    assert.ok(Stores.changesStore.hasFilter(filter) === true);
  });

  it('getDatabaseName() returns database name', () => {
    const dbName = 'hoopoes';
    Stores.changesStore.initChanges({ databaseName: dbName });
    assert.equal(Stores.changesStore.getDatabaseName(), dbName);

    Stores.changesStore.reset();
    assert.equal(Stores.changesStore.getDatabaseName(), '');
  });

  it("getChanges() should return a subset if there are a lot of changes", () => {

    // to keep the test speedy, we override the default max value
    const maxChanges = 10;
    const changes = [];
    _.times(maxChanges + 10, function (i) {
      changes.push({ id: 'doc_' + i, seq: 1, changes: {}});
    });
    Stores.changesStore.initChanges({ databaseName: "test" });
    Stores.changesStore.setMaxChanges(maxChanges);

    const seqNum = 123;
    Stores.changesStore.updateChanges(seqNum, changes);

    const results = Stores.changesStore.getChanges();
    assert.equal(maxChanges, results.length);
  });

  it("tracks last sequence number", () => {
    assert.equal(null, Stores.changesStore.getLastSeqNum());

    const seqNum = 123;
    Stores.changesStore.updateChanges(seqNum, []);

    // confirm it's been stored
    assert.equal(seqNum, Stores.changesStore.getLastSeqNum());
  });

});


text:
package org.springframework.boot.context.embedded.tomcat;

import java.util.Set;

import org.apache.tomcat.JarScanner;
import org.apache.tomcat.util.scan.StandardJarScanFilter;
import org.apache.tomcat.util.scan.StandardJarScanner;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * {@link JarScanner} decorator allowing alternative default jar pattern matching. This
 * class extends {@link StandardJarScanner} rather than implementing the
 * {@link JarScanner} due to API changes introduced in Tomcat 8.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @see #apply(TomcatEmbeddedContext, Set)
 */
class SkipPatternJarScanner extends StandardJarScanner {

	private final JarScanner jarScanner;

	SkipPatternJarScanner(JarScanner jarScanner, Set<String> patterns) {
		Assert.notNull(jarScanner, "JarScanner must not be null");
		Assert.notNull(patterns, "Patterns must not be null");
		this.jarScanner = jarScanner;
		StandardJarScanFilter filter = new StandardJarScanFilter();
		filter.setTldSkip(StringUtils.collectionToCommaDelimitedString(patterns));
		this.jarScanner.setJarScanFilter(filter);
	}

	/**
	 * Apply this decorator the specified context.
	 * @param context the context to apply to
	 * @param patterns the jar skip patterns or {@code null} for defaults
	 */
	static void apply(TomcatEmbeddedContext context, Set<String> patterns) {
		SkipPatternJarScanner scanner = new SkipPatternJarScanner(context.getJarScanner(),
				patterns);
		context.setJarScanner(scanner);
	}

}


text:
package breakout;

public abstract class GameObject {
	protected float x,y;
	protected float width, height;
	public Color color = new Color(1f,1f,1f);

	abstract void update();
	public void render(){
		Draw.Rect(x, y, width, height, color);
	}

	//Getters
	public float getX(){
		return x;
	}

	public float getY(){
		return y;
	}

	public float getWidth(){
		return width;
	}

	public float getHeight(){
		return height;
	}

	public float getCenterX(){
		return ((width / 2) + x);
	}
}


text:
"use strict";

var defaultParseOptions = {
  decodeValues: true,
  map: false,
  silent: false,
};

function isNonEmptyString(str) {
  return typeof str === "string" && !!str.trim();
}

function parseString(setCookieValue, options) {
  var parts = setCookieValue.split(";").filter(isNonEmptyString);

  var nameValuePairStr = parts.shift();
  var parsed = parseNameValuePair(nameValuePairStr);
  var name = parsed.name;
  var value = parsed.value;

  options = options
    ? Object.assign({}, defaultParseOptions, options)
    : defaultParseOptions;

  try {
    value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
  } catch (e) {
    console.error(
      "set-cookie-parser encountered an error while decoding a cookie with value '" +
        value +
        "'. Set options.decodeValues to false to disable this feature.",
      e
    );
  }

  var cookie = {
    name: name,
    value: value,
  };

  parts.forEach(function (part) {
    var sides = part.split("=");
    var key = sides.shift().trimLeft().toLowerCase();
    var value = sides.join("=");
    if (key === "expires") {
      cookie.expires = new Date(value);
    } else if (key === "max-age") {
      cookie.maxAge = parseInt(value, 10);
    } else if (key === "secure") {
      cookie.secure = true;
    } else if (key === "httponly") {
      cookie.httpOnly = true;
    } else if (key === "samesite") {
      cookie.sameSite = value;
    } else {
      cookie[key] = value;
    }
  });

  return cookie;
}

function parseNameValuePair(nameValuePairStr) {
  // Parses name-value-pair according to rfc6265bis draft

  var name = "";
  var value = "";
  var nameValueArr = nameValuePairStr.split("=");
  if (nameValueArr.length > 1) {
    name = nameValueArr.shift();
    value = nameValueArr.join("="); // everything after the first =, joined by a "=" if there was more than one part
  } else {
    value = nameValuePairStr;
  }

  return { name: name, value: value };
}

function parse(input, options) {
  options = options
    ? Object.assign({}, defaultParseOptions, options)
    : defaultParseOptions;

  if (!input) {
    if (!options.map) {
      return [];
    } else {
      return {};
    }
  }

  if (input.headers && input.headers["set-cookie"]) {
    // fast-path for node.js (which automatically normalizes header names to lower-case
    input = input.headers["set-cookie"];
  } else if (input.headers) {
    // slow-path for other environments - see #25
    var sch =
      input.headers[
        Object.keys(input.headers).find(function (key) {
          return key.toLowerCase() === "set-cookie";
        })
      ];
    // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
    if (!sch && input.headers.cookie && !options.silent) {
      console.warn(
        "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
      );
    }
    input = sch;
  }
  if (!Array.isArray(input)) {
    input = [input];
  }

  options = options
    ? Object.assign({}, defaultParseOptions, options)
    : defaultParseOptions;

  if (!options.map) {
    return input.filter(isNonEmptyString).map(function (str) {
      return parseString(str, options);
    });
  } else {
    var cookies = {};
    return input.filter(isNonEmptyString).reduce(function (cookies, str) {
      var cookie = parseString(str, options);
      cookies[cookie.name] = cookie;
      return cookies;
    }, cookies);
  }
}

/*
  Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
  that are within a single set-cookie field-value, such as in the Expires portion.

  This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
  Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
  React Native's fetch does this for *every* header, including set-cookie.

  Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
  Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
*/
function splitCookiesString(cookiesString) {
  if (Array.isArray(cookiesString)) {
    return cookiesString;
  }
  if (typeof cookiesString !== "string") {
    return [];
  }

  var cookiesStrings = [];
  var pos = 0;
  var start;
  var ch;
  var lastComma;
  var nextStart;
  var cookiesSeparatorFound;

  function skipWhitespace() {
    while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
      pos += 1;
    }
    return pos < cookiesString.length;
  }

  function notSpecialChar() {
    ch = cookiesString.charAt(pos);

    return ch !== "=" && ch !== ";" && ch !== ",";
  }

  while (pos < cookiesString.length) {
    start = pos;
    cookiesSeparatorFound = false;

    while (skipWhitespace()) {
      ch = cookiesString.charAt(pos);
      if (ch === ",") {
        // ',' is a cookie separator if we have later first '=', not ';' or ','
        lastComma = pos;
        pos += 1;

        skipWhitespace();
        nextStart = pos;

        while (pos < cookiesString.length && notSpecialChar()) {
          pos += 1;
        }

        // currently special character
        if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
          // we found cookies separator
          cookiesSeparatorFound = true;
          // pos is inside the next cookie, so back up and return it.
          pos = nextStart;
          cookiesStrings.push(cookiesString.substring(start, lastComma));
          start = pos;
        } else {
          // in param ',' or param separator ';',
          // we continue from that comma
          pos = lastComma + 1;
        }
      } else {
        pos += 1;
      }
    }

    if (!cookiesSeparatorFound || pos >= cookiesString.length) {
      cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
    }
  }

  return cookiesStrings;
}

module.exports = parse;
module.exports.parse = parse;
module.exports.parseString = parseString;
module.exports.splitCookiesString = splitCookiesString;


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/cube_mints_f1f1f1">

   <com.qjizho.inspmarker.helper.JazzyViewPager
       android:id="@+id/jazzy_pager"
       android:layout_width="match_parent"
       android:layout_height="match_parent">

   </com.qjizho.inspmarker.helper.JazzyViewPager>
</RelativeLayout>


text:
module ActiveAdmin
  module Reloader
    # ActionDispatch::Reloader.to_prepare is deprecated in Rails 5.0 and will be removed from Rails 5.1
    #
    # Use ActiveSupport::Reloader if available for Rails 5, fall back to ActionDispatch::Reloader for earlier Rails
    def self.to_prepare(*args, &block)
      if defined? ActiveSupport::Reloader
        ActiveSupport::Reloader.to_prepare(*args, &block)
      else
        ActionDispatch::Reloader.to_prepare(*args, &block)
      end
    end

    # ActionDispatch::Reloader.to_cleanup is deprecated in Rails 5.0 and will be removed from Rails 5.1
    #
    # Use ActiveSupport::Reloader if available for Rails 5, fall back to ActionDispatch::Reloader for earlier Rails
    def self.to_complete(*args, &block)
      if defined? ActiveSupport::Reloader
        ActiveSupport::Reloader.to_complete(*args, &block)
      else
        ActionDispatch::Reloader.to_cleanup(*args, &block)
      end
    end
  end
end


text:
package errors

import (
	"bytes"
	"errors"
	"fmt"
	"log"
	"strings"
	"testing"

	"github.com/miekg/coredns/middleware"
	"github.com/miekg/coredns/middleware/pkg/dnsrecorder"
	"github.com/miekg/coredns/middleware/test"

	"github.com/miekg/dns"
	"golang.org/x/net/context"
)

func TestErrors(t *testing.T) {
	buf := bytes.Buffer{}
	em := errorHandler{Log: log.New(&buf, "", 0)}

	testErr := errors.New("test error")
	tests := []struct {
		next         middleware.Handler
		expectedCode int
		expectedLog  string
		expectedErr  error
	}{
		{
			next:         genErrorHandler(dns.RcodeSuccess, nil),
			expectedCode: dns.RcodeSuccess,
			expectedLog:  "",
			expectedErr:  nil,
		},
		{
			next:         genErrorHandler(dns.RcodeNotAuth, testErr),
			expectedCode: dns.RcodeNotAuth,
			expectedLog:  fmt.Sprintf("[ERROR %d %s] %v\n", dns.RcodeNotAuth, "example.org. A", testErr),
			expectedErr:  testErr,
		},
	}

	ctx := context.TODO()
	req := new(dns.Msg)
	req.SetQuestion("example.org.", dns.TypeA)

	for i, tc := range tests {
		em.Next = tc.next
		buf.Reset()
		rec := dnsrecorder.New(&test.ResponseWriter{})
		code, err := em.ServeDNS(ctx, rec, req)

		if err != tc.expectedErr {
			t.Errorf("Test %d: Expected error %v, but got %v",
				i, tc.expectedErr, err)
		}
		if code != tc.expectedCode {
			t.Errorf("Test %d: Expected status code %d, but got %d",
				i, tc.expectedCode, code)
		}
		if log := buf.String(); !strings.Contains(log, tc.expectedLog) {
			t.Errorf("Test %d: Expected log %q, but got %q",
				i, tc.expectedLog, log)
		}
	}
}

func TestVisibleErrorWithPanic(t *testing.T) {
	const panicMsg = "I'm a panic"
	eh := errorHandler{
		Debug: true,
		Next: middleware.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
			panic(panicMsg)
		}),
	}

	ctx := context.TODO()
	req := new(dns.Msg)
	req.SetQuestion("example.org.", dns.TypeA)

	rec := dnsrecorder.New(&test.ResponseWriter{})

	code, err := eh.ServeDNS(ctx, rec, req)
	if code != 0 {
		t.Errorf("Expected error handler to return 0 (it should write to response), got status %d", code)
	}
	if err != nil {
		t.Errorf("Expected error handler to return nil error (it should panic!), but got '%v'", err)
	}
}

func genErrorHandler(rcode int, err error) middleware.Handler {
	return middleware.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
		return rcode, err
	})
}


text:
package com.baidubce.services.cnap.model.deploygroup;

import java.util.List;

/**
 * The model for config component.
 */
public class ConfigComponentModel {

    /**
     * The container config list.
     */
    private List<ContainerConfigModel> containerConfigs;

    public List<ContainerConfigModel> getContainerConfigs() {
        return containerConfigs;
    }

    public void setContainerConfigs(
            List<ContainerConfigModel> containerConfigs) {
        this.containerConfigs = containerConfigs;
    }
}


text:
package rewrite

import (
	"fmt"
	"regexp"
	"strings"
	"testing"

	"github.com/mholt/caddy"
	"github.com/mholt/caddy/caddyhttp/httpserver"
)

func TestSetup(t *testing.T) {
	c := caddy.NewTestController("http", `rewrite /from /to`)
	err := setup(c)
	if err != nil {
		t.Errorf("Expected no errors, but got: %v", err)
	}
	mids := httpserver.GetConfig(c).Middleware()
	if len(mids) == 0 {
		t.Fatal("Expected middleware, had 0 instead")
	}

	handler := mids[0](httpserver.EmptyNext)
	myHandler, ok := handler.(Rewrite)
	if !ok {
		t.Fatalf("Expected handler to be type Rewrite, got: %#v", handler)
	}

	if !httpserver.SameNext(myHandler.Next, httpserver.EmptyNext) {
		t.Error("'Next' field of handler was not set properly")
	}

	if len(myHandler.Rules) != 1 {
		t.Errorf("Expected handler to have %d rule, has %d instead", 1, len(myHandler.Rules))
	}
}

// newSimpleRule is convenience test function for SimpleRule.
func newSimpleRule(t *testing.T, from, to string, negate ...bool) Rule {
	var n bool
	if len(negate) > 0 {
		n = negate[0]
	}
	rule, err := NewSimpleRule(from, to, n)
	if err != nil {
		t.Fatal(err)
	}
	return rule
}

func TestRewriteParse(t *testing.T) {
	simpleTests := []struct {
		input     string
		shouldErr bool
		expected  []Rule
	}{
		{`rewrite /from /to`, false, []Rule{
			newSimpleRule(t, "/from", "/to"),
		}},
		{`rewrite /from /to
		  rewrite a b`, false, []Rule{
			newSimpleRule(t, "/from", "/to"),
			newSimpleRule(t, "a", "b"),
		}},
		{`rewrite a`, true, []Rule{}},
		{`rewrite`, true, []Rule{}},
		{`rewrite a b c`, false, []Rule{
			newSimpleRule(t, "a", "b c"),
		}},
		{`rewrite not a b c`, false, []Rule{
			newSimpleRule(t, "a", "b c", true),
		}},
	}

	for i, test := range simpleTests {
		actual, err := rewriteParse(caddy.NewTestController("http", test.input))

		if err == nil && test.shouldErr {
			t.Errorf("Test %d didn't error, but it should have", i)
		} else if err != nil && !test.shouldErr {
			t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
		} else if err != nil && test.shouldErr {
			continue
		}

		if len(actual) != len(test.expected) {
			t.Fatalf("Test %d expected %d rules, but got %d",
				i, len(test.expected), len(actual))
		}

		for j, e := range test.expected {
			actualRule := actual[j].(*SimpleRule)
			expectedRule := e.(*SimpleRule)

			if actualRule.Regexp.String() != expectedRule.Regexp.String() {
				t.Errorf("Test %d, rule %d: Expected From=%s, got %s",
					i, j, expectedRule.Regexp.String(), actualRule.Regexp.String())
			}

			if actualRule.To != expectedRule.To {
				t.Errorf("Test %d, rule %d: Expected To=%s, got %s",
					i, j, expectedRule.Regexp.String(), actualRule.Regexp.String())
			}

			if actualRule.Negate != expectedRule.Negate {
				t.Errorf("Test %d, rule %d: Expected Negate=%v, got %v",
					i, j, expectedRule.Negate, actualRule.Negate)
			}
		}
	}

	regexpTests := []struct {
		input     string
		shouldErr bool
		expected  []Rule
	}{
		{`rewrite {
			r	.*
			to	/to /index.php?
		 }`, false, []Rule{
			ComplexRule{Base: "/", To: "/to /index.php?", Regexp: regexp.MustCompile(".*")},
		}},
		{`rewrite {
			regexp	.*
			to		/to
			ext		/ html txt
		 }`, false, []Rule{
			ComplexRule{Base: "/", To: "/to", Exts: []string{"/", "html", "txt"}, Regexp: regexp.MustCompile(".*")},
		}},
		{`rewrite /path {
			r	rr
			to	/dest
		 }
		 rewrite / {
		 	regexp	[a-z]+
		 	to 		/to /to2
		 }
		 `, false, []Rule{
			ComplexRule{Base: "/path", To: "/dest", Regexp: regexp.MustCompile("rr")},
			ComplexRule{Base: "/", To: "/to /to2", Regexp: regexp.MustCompile("[a-z]+")},
		}},
		{`rewrite {
			r	.*
		 }`, true, []Rule{
			ComplexRule{},
		}},
		{`rewrite {

		 }`, true, []Rule{
			ComplexRule{},
		}},
		{`rewrite /`, true, []Rule{
			ComplexRule{},
		}},
		{`rewrite {
			if {path} match /
			to		/to
		 }`, false, []Rule{
			ComplexRule{Base: "/", To: "/to"},
		}},
	}

	for i, test := range regexpTests {
		actual, err := rewriteParse(caddy.NewTestController("http", test.input))

		if err == nil && test.shouldErr {
			t.Errorf("Test %d didn't error, but it should have", i)
		} else if err != nil && !test.shouldErr {
			t.Errorf("Test %d errored, but it shouldn't have; got '%v'", i, err)
		} else if err != nil && test.shouldErr {
			continue
		}

		if len(actual) != len(test.expected) {
			t.Fatalf("Test %d expected %d rules, but got %d",
				i, len(test.expected), len(actual))
		}

		for j, e := range test.expected {
			actualRule := actual[j].(ComplexRule)
			expectedRule := e.(ComplexRule)

			if actualRule.Base != expectedRule.Base {
				t.Errorf("Test %d, rule %d: Expected Base=%s, got %s",
					i, j, expectedRule.Base, actualRule.Base)
			}

			if actualRule.To != expectedRule.To {
				t.Errorf("Test %d, rule %d: Expected To=%s, got %s",
					i, j, expectedRule.To, actualRule.To)
			}

			if fmt.Sprint(actualRule.Exts) != fmt.Sprint(expectedRule.Exts) {
				t.Errorf("Test %d, rule %d: Expected Ext=%v, got %v",
					i, j, expectedRule.To, actualRule.To)
			}

			if actualRule.Regexp != nil {
				if actualRule.Regexp.String() != expectedRule.Regexp.String() {
					t.Errorf("Test %d, rule %d: Expected Pattern=%s, got %s",
						i, j, actualRule.Regexp.String(), expectedRule.Regexp.String())
				}
			}
		}

		if rules_fmt := fmt.Sprintf("%v", actual); strings.HasPrefix(rules_fmt, "%!") {
			t.Errorf("Test %d: Failed to string encode: %#v", i, rules_fmt)
		}
	}
}


text:
class AddBalanceToClients < ActiveRecord::Migration
  	def change
    		add_column :clients, :balance, :float
  	end
end


text:
package com.sai.test.retrofit;

/**
 * Created by sai on 2017-10-08.
 */

public class Balance {
    public Currency eth;
    public Currency krw;

    public class Currency {
        double avail;
        double balance;

        @Override
        public String toString() {
            return "available : " + String.format("%.1f", avail) + ", balance : " + String.format("%.1f", balance) ;
        }
    }
}


text:
package com.googlecode.objectify.cmd;

/**
 *
After a type is specified, the next step in a delete chain is to specify an optional parent
 * or a set of ids.  This is part of

 *
 *
Deletes do NOT cascade; you must delete each individual entity in an object graph.

 *
 *
All command objects are immutable.

 *
 * @author Jeff Schnitzer <jeff@infohazard.org>
 */
public interface DeleteType extends DeleteIds
{
	/**
	 * Defines the parent part of a key (or set of keys) when building a delete request.
	 * After this you will define the id or ids to delete.
	 *
	 * @param keyOrEntity - a Key<?>, datastore Key, or pojo entity of the parent
	 * @return the next immutable step in the command build process
	 */
	DeleteIds parent(Object keyOrEntity);
}


text:
@interface DrawingTopShine : UIView

@end


text:
package org.apache.ignite.internal.binary;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import com.google.common.collect.ImmutableMap;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

import static java.util.Collections.singletonList;

/** */
public class BinaryObjectToStringTest extends GridCommonAbstractTest {
    /** */
    @Test
    public void testToStringInaccessibleOptimizedMarshallerClass() throws Exception {
        IgniteEx ign = startGrid(0);

        ign.createCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME));

        assertStringFormContains(new TestContainer(new CustomTestClass()), "CustomTestClass");
        assertStringFormContains(new TestContainer(new ArrayList<>(singletonList(new CustomTestClass()))),
            "ArrayList", "CustomTestClass");
        assertStringFormContains(new TestContainer("abc"), "x=abc");
        assertStringFormContains(new TestContainer(123), "x=123");
        assertStringFormContains(new TestIntContainer(123), "i=123");

        assertStringFormContains(new TestContainer(new int[]{1, 2}), "x=[1, 2]");
        assertStringFormContains(new TestContainer(new Integer[]{1, 2}), "x=[1, 2]");
        assertStringFormContains(new TestContainer(new ArrayList<>(Arrays.asList(1, 2))), "x=ArrayList {1, 2}");
        assertStringFormContains(new TestContainer(new HashSet<>(Arrays.asList(1, 2))), "x=HashSet {1, 2}");
        assertStringFormContains(new TestContainer(new HashMap<>(ImmutableMap.of(1, 2))), "x=HashMap {1=2}");

        ArrayList<Object> nestedList = new ArrayList<>(Arrays.asList(
            new ArrayList<>(Arrays.asList(1, 2)),
            new ArrayList<>(Arrays.asList(3, 4))
        ));
        assertStringFormContains(new TestContainer(nestedList), "x=ArrayList {ArrayList {1, 2}, ArrayList {3, 4}}");

        assertStringFormMatches(new TestContainer(newExtInstance1()), failedStrPattern("ExternalTestClass1"));
        assertStringFormMatches(new TestContainer(newExtInstance2()), failedStrPattern("ExternalTestClass2"));

        assertStringFormMatches(new TestContainer(new Object[] {newExtInstance1()}),
            failedStrPattern("ExternalTestClass1"));
        assertStringFormMatches(new TestContainer(new ArrayList<>(singletonList(newExtInstance1()))),
            failedStrPattern("ExternalTestClass1"));
        assertStringFormMatches(new TestContainer(new HashSet<>(singletonList(newExtInstance1()))),
            failedStrPattern("ExternalTestClass1"));
        assertStringFormMatches(new TestContainer(new HashMap<>(ImmutableMap.of(newExtInstance1(), newExtInstance2()))),
            failedStrPattern("ExternalTestClass1"));

        ArrayList<Object> nestedList2 = new ArrayList<>(singletonList(new ArrayList<>(singletonList(newExtInstance1()))));
        assertStringFormMatches(new TestContainer(nestedList2), failedStrPattern("ExternalTestClass1"));

        assertStringFormMatches(new TestContainer(new TestExternalizable(newExtInstance1())),
            failedStrPattern("ExternalTestClass1"));
    }

    /** */
    private String failedStrPattern(String className) {
        return "org.apache.ignite.internal.binary.BinaryObjectToStringTest\\$TestContainer " +
            "\\[idHash=-?\\d+, hash=-?\\d+, " +
            "x=\\(Failed to create a string representation: class not found " + className + "\\)]";
    }

    /** */
    private static class CustomTestClass {
    }

    /** */
    private static class TestExternalizable implements Externalizable {
        /** */
        private Object x;

        /** */
        private TestExternalizable() {
        }

        /** */
        private TestExternalizable(Object x) {
            this.x = x;
        }

        /** */
        @Override public void writeExternal(ObjectOutput out) throws IOException {
            out.writeObject(x);
        }

        /** */
        @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
            x = in.readObject();
        }
    }

    /** */
    private void assertStringFormContains(Object o, String s0, String... ss) {
        IgniteCache<Object, Object> cache = grid(0).cache(DEFAULT_CACHE_NAME);

        String str = asBinaryObjectString(cache, o);

        assertTrue(str.contains(s0));

        for (String s : ss)
            assertTrue(str.contains(s));
    }

    /** */
    private void assertStringFormMatches(Object o, String pattern) {
        IgniteCache<Object, Object> cache = grid(0).cache(DEFAULT_CACHE_NAME);

        assertTrue(asBinaryObjectString(cache, o).matches(pattern));
    }

    /** */
    private static String asBinaryObjectString(IgniteCache<Object, Object> cache, Object obj) {
        cache.put(1, obj);

        return cache.withKeepBinary().get(1).toString();
    }

    /** */
    private Object newExtInstance1() throws Exception {
        ClassPool classPool = new ClassPool(ClassPool.getDefault());

        CtClass aClass = classPool.makeClass("ExternalTestClass1");
        aClass.addInterface(classPool.get("java.io.Externalizable"));
        aClass.addField(CtField.make("private int x;", aClass));
        aClass.addConstructor(CtNewConstructor.make("public ExternalTestClass1() {}", aClass));
        aClass.addConstructor(CtNewConstructor.make("public ExternalTestClass1(int x0) { x = x0; }", aClass));
        aClass.addMethod(CtNewMethod.make(
            "public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { out.writeInt(x); }",
            aClass));
        aClass.addMethod(CtNewMethod.make(
            "public void readExternal(java.io.ObjectInput in) throws java.io.IOException { x = in.readInt(); }",
            aClass));

        ClassLoader extClsLdr = new ClassLoader() {{
            byte[] bytecode = aClass.toBytecode();

            defineClass("ExternalTestClass1", bytecode, 0, bytecode.length);
        }};

        Class<?> extClass = extClsLdr.loadClass("ExternalTestClass1");

        Constructor<?> ctor = extClass.getConstructor(int.class);

        return ctor.newInstance(42);
    }

    /** */
    private Object newExtInstance2() throws Exception {
        ClassPool classPool = new ClassPool(ClassPool.getDefault());

        CtClass aClass = classPool.makeClass("ExternalTestClass2");
        aClass.addInterface(classPool.get("java.io.Serializable"));
        aClass.addField(CtField.make("private int x;", aClass));
        aClass.addConstructor(CtNewConstructor.make("public ExternalTestClass2() {}", aClass));
        aClass.addConstructor(CtNewConstructor.make("public ExternalTestClass2(int x0) { x = x0; }", aClass));
        aClass.addMethod(CtNewMethod.make(
            "private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.writeInt(x); }",
            aClass));
        aClass.addMethod(CtNewMethod.make(
            "private void readObject(java.io.ObjectInputStream in) throws java.io.IOException { x = in.readInt(); }",
            aClass));

        ClassLoader extClsLdr = new ClassLoader() {{
            byte[] bytecode = aClass.toBytecode();

            defineClass("ExternalTestClass2", bytecode, 0, bytecode.length);
        }};

        Class<?> extClass = extClsLdr.loadClass("ExternalTestClass2");

        Constructor<?> ctor = extClass.getConstructor(int.class);

        return ctor.newInstance(42);
    }

    /** */
    private static class TestContainer {
        /** */
        private final Object x;

        /** */
        private TestContainer(Object x) {
            this.x = x;
        }
    }

    /** */
    private static class TestIntContainer {
        /** */
        private final int i;

        /** */
        private TestIntContainer(int i) {
            this.i = i;
        }
    }
}


text:
/** @file paex_sine.c
	@ingroup examples_src
	@brief Play a sine wave for several seconds.
	@author Ross Bencina <rossb@audiomulch.com>
    @author Phil Burk <philburk@softsynth.com>
*/
/*
 * $Id: paex_sine.c 1752 2011-09-08 03:21:55Z philburk $
 *
 * This program uses the PortAudio Portable Audio Library.
 * For more information see: http://www.portaudio.com/
 * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * The text above constitutes the entire PortAudio license; however,
 * the PortAudio community also makes the following non-binding requests:
 *
 * Any person wishing to distribute modifications to the Software is
 * requested to send the modifications to the original developer so that
 * they can be incorporated into the canonical version. It is also
 * requested that these non-binding requests be included along with the
 * license above.
 */
#include <stdio.h>
#include <math.h>
#include "portaudio.h"

#define NUM_SECONDS   (5)
#define SAMPLE_RATE   (44100)
#define FRAMES_PER_BUFFER  (64)

#ifndef M_PI
#define M_PI  (3.14159265)
#endif

#define TABLE_SIZE   (200)

class Sine
{
public:
    Sine() : stream(0), left_phase(0), right_phase(0)
    {
        /* initialise sinusoidal wavetable */
        for( int i=0; i<TABLE_SIZE; i++ )
        {
            sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. );
        }

        sprintf( message, "No Message" );
    }

    bool open(PaDeviceIndex index)
    {
        PaStreamParameters outputParameters;

        outputParameters.device = index;
        if (outputParameters.device == paNoDevice) {
            return false;
        }

        const PaDeviceInfo* pInfo = Pa_GetDeviceInfo(index);
        if (pInfo != 0)
        {
            printf("Output device name: '%s'\r", pInfo->name);
        }

        outputParameters.channelCount = 2;       /* stereo output */
        outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */
        outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
        outputParameters.hostApiSpecificStreamInfo = NULL;

        PaError err = Pa_OpenStream(
            &stream,
            NULL, /* no input */
            &outputParameters,
            SAMPLE_RATE,
            paFramesPerBufferUnspecified,
            paClipOff,      /* we won't output out of range samples so don't bother clipping them */
            &Sine::paCallback,
            this            /* Using 'this' for userData so we can cast to Sine* in paCallback method */
            );

        if (err != paNoError)
        {
            /* Failed to open stream to device !!! */
            return false;
        }

        err = Pa_SetStreamFinishedCallback( stream, &Sine::paStreamFinished );

        if (err != paNoError)
        {
            Pa_CloseStream( stream );
            stream = 0;

            return false;
        }

        return true;
    }

    bool close()
    {
        if (stream == 0)
            return false;

        PaError err = Pa_CloseStream( stream );
        stream = 0;

        return (err == paNoError);
    }

    bool start()
    {
        if (stream == 0)
            return false;

        PaError err = Pa_StartStream( stream );

        return (err == paNoError);
    }

    bool stop()
    {
        if (stream == 0)
            return false;

        PaError err = Pa_StopStream( stream );

        return (err == paNoError);
    }

private:
    /* The instance callback, where we have access to every method/variable in object of class Sine */
    int paCallbackMethod(const void *inputBuffer, void *outputBuffer,
        unsigned long framesPerBuffer,
        const PaStreamCallbackTimeInfo* timeInfo,
        PaStreamCallbackFlags statusFlags)
    {
        float *out = (float*)outputBuffer;
        unsigned long i;

        (void) timeInfo; /* Prevent unused variable warnings. */
        (void) statusFlags;
        (void) inputBuffer;

        for( i=0; i<framesPerBuffer; i++ )
        {
            *out++ = sine[left_phase];  /* left */
            *out++ = sine[right_phase];  /* right */
            left_phase += 1;
            if( left_phase >= TABLE_SIZE ) left_phase -= TABLE_SIZE;
            right_phase += 3; /* higher pitch so we can distinguish left and right. */
            if( right_phase >= TABLE_SIZE ) right_phase -= TABLE_SIZE;
        }

        return paContinue;

    }

    /* This routine will be called by the PortAudio engine when audio is needed.
    ** It may called at interrupt level on some machines so don't do anything
    ** that could mess up the system like calling malloc() or free().
    */
    static int paCallback( const void *inputBuffer, void *outputBuffer,
        unsigned long framesPerBuffer,
        const PaStreamCallbackTimeInfo* timeInfo,
        PaStreamCallbackFlags statusFlags,
        void *userData )
    {
        /* Here we cast userData to Sine* type so we can call the instance method paCallbackMethod, we can do that since
           we called Pa_OpenStream with 'this' for userData */
        return ((Sine*)userData)->paCallbackMethod(inputBuffer, outputBuffer,
            framesPerBuffer,
            timeInfo,
            statusFlags);
    }

    void paStreamFinishedMethod()
    {
        printf( "Stream Completed: %s\n", message );
    }

    /*
     * This routine is called by portaudio when playback is done.
     */
    static void paStreamFinished(void* userData)
    {
        return ((Sine*)userData)->paStreamFinishedMethod();
    }

    PaStream *stream;
    float sine[TABLE_SIZE];
    int left_phase;
    int right_phase;
    char message[20];
};

class ScopedPaHandler
{
public:
    ScopedPaHandler()
        : _result(Pa_Initialize())
    {
    }
    ~ScopedPaHandler()
    {
        if (_result == paNoError)
        {
            Pa_Terminate();
        }
    }

    PaError result() const { return _result; }

private:
    PaError _result;
};

/*******************************************************************/
int main(void);
int main(void)
{
    Sine sine;

    printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER);

    ScopedPaHandler paInit;
    if( paInit.result() != paNoError ) goto error;

    if (sine.open(Pa_GetDefaultOutputDevice()))
    {
        if (sine.start())
        {
            printf("Play for %d seconds.\n", NUM_SECONDS );
            Pa_Sleep( NUM_SECONDS * 1000 );

            sine.stop();
        }

        sine.close();
    }

    printf("Test finished.\n");
    return paNoError;

error:
    fprintf( stderr, "An error occured while using the portaudio stream\n" );
    fprintf( stderr, "Error number: %d\n", paInit.result() );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( paInit.result() ) );
    return 1;
}


text:
import { ICON_OPTIONS } from "./const";

/**
 * Options that the user can control. These values are plumbed through to the
 * JourneySharingMapView in JourneySharingGoogleMapComponent.
 */
export class JourneySharingUserOptions {
  public showAnticipatedRoutePolyline = true;
  public showTakenRoutePolyline = true;
  public destinationIcon = ICON_OPTIONS.USE_DEFAULT;
  public vehicleIcon = ICON_OPTIONS.USE_DEFAULT;
}


text:
{start_tabs}

{tab|via-recent-topics}

1. Open **Recent topics** from the left sidebar or by pressing the
   Esc key.

1. Click on the name of a topic in the **Topic** column.

1. Read the topic, scrolling down with the mouse or by pressing
   PgDn.

1. If the topic is not of interest, you can
   [mark all messages as read](/help/marking-messages-as-read) or
   do so by jumping to the end using the End key.

1. You can then click on another topic in the left sidebar, use the
   N key to go to the next unread topic, or go back to the
   **Recent topics** view.

{tab|via-left-sidebar}

1. Click on the name of a stream in the left sidebar. You will see a
   list of the most recent unread topics in that stream.

1. Click on a topic in the left sidebar.

1. Read the topic, scrolling down with the mouse or by pressing
   PgDn.

1. If the topic is not of interest, you can
   [mark all messages as read](/help/marking-messages-as-read) or do
   so by jumping to the end using the End key.

1. Click on the next topic in the left sidebar, or use the N
   key to go to the next unread topic.

1. To go to older unread topics, use the N key or click
   **more topics** to view.

{end_tabs}


text:
About
-----

C implementation of [Salt Channel](https://github.com/assaabloy-ppi/salt-channel). *Salt Channel is "Powered by Curve25519"*

**License:** MIT

## Development
The salt-channel-c is mainly developed using the following tools:
* Ubuntu
* gcc
* CMake
* CMocka
* lcov

### To test the implementation or contribute with development:
1. Install tools
```
$ apt-get install cmake libcmocka-dev lcov
```
2. Build
```
$ mkdir build
$ cd build
$ cmake ..
$ make
$ make test
```

### Importing to eclipse
Eclipse can be used for development and debugging. Assumed that this repository is cloned to your home folder and that the eclipse workspace is located in **~/workspace** the setup could be done similar to this:

1. Clone this repository and initiate the eclipse workspace:

```
$cd ~/
$ git clone https://github.com/assaabloy-ppi/salt-channel-c
$ mkdir -p ~/workspace/salt-channel-c
$ cmake -G "Eclipse CDT4 - Unix Makefiles" ~/salt-channel-c
```

2. In eclipse: **File > Import > General > Existing Projects into Workspace**
3. Check **Select root directory** and chose ~/workspace/salt-channel-c, make sure **Copy projects into workspace** is NOT checked.
4. Press **Finish**.

Note: If any cmake configuration files is modified you need to repeat **step 1**.

### A simple example
An echo salt-channel host is provided. If a message that is sent to the host starts with the byte **0x01** the host will echo the same message to the client.

**Host-side:**
```
$ ./examples/host_echo
Socket created
bind done
Waiting for incoming connections...
Connection accepted
Waiting for client to disconnect.
Waiting for incoming connections...
Salt handshake succeeded.
```
**Client-side:**
```
$ ./examples/client_echo
Connection to 127.0.0.1
Connected successfully - Please enter string
Salt handshake succeeded.
Enter message: Hello
client: Hello
host: Hello
Enter message:

```

## Implementation details

Salt-channel-c is an implementation of the salt-channel over a serial stream. I.e., the expected input data format and the output data format follows the following structure:

    **** Stream message structure ****

    4   Size.
        Four size bytes in Littleendian byte order. E.g.:
        Size = 4: sizeBytes[4] = { 0x04, 0x00, 0x00, 0x00 }

### Goals

* **Non-blocking:**
The salt-channel implementation should be non-blocking. I.e., the implementation must be able to run on a system without threads. However, the user of the implementation may make it blocking depending on user injected I/O implementation. The state of each salt-channel process must be either SUCCESS, PENDING or error.

* **No dynamic memory allocation:**
The salt-channel-c implementation must work on systems with no heap. However, it's up to the user of the implementation to decide whether to use dynamic memory allocation since all used buffers are injected.

* **Slow I/O:**
Do cryptographic computations during I/O. If the I/O is slow, some of the crypthographic computations can be calculated while waiting for I/O:

    * Client sends the ehpemeral public encryption key in message M1.
    * Host received the client key and immediately sends the host key in message M2.
    * While I/O, calculate the ephemeral key. Immediately after this, start calculating the signature used for M3.
    * Client received the host key and immediately starts calculating this. This can be done while the M3 message is received from the host. Directly after this, the client starts calculating the signature used for M4.
    * Client receives M3 and the host signature. If the signature is valid and the host can be authenticated, the clients send the M4 message containing the clients signature.

### General message structure
Except for message *M1* each message follows this structure:

    **** Salt-channel message structure ****
    2   Header.

    N   Payload.

### TweetNaCl API
The TweetNaCl library is a subset of the NaCl library and the crypto API used for this implementation is available at https://nacl.cr.yp.to/.

**Encryption:**
The encryption API crypto_box_afternm requires the first 32 (crypto_secretbox_ZEROBYTES) bytes to be zero (0x00) padded. After encryption the first 16 (crypto_secretbox_BOXZEROBYTES) will be zero (0x00):
```
--> Clear text data must be zero padded:
    clearText[N] = { zeroPadded[32] , clearText[N-32] }
--> Encrypt:
    encryptedAndAuthenticated = { zeroPadded[16] , cipher[N-16] }
```
In order to minimize send data over slow I/O channels the 16 zero padded bytes are neglected.

**Decryption:**
The decryption API crypto_box_open_afternm requires the first 16 bytes to be zero (0x00) padded. After decryption the first 32 bytes will be zero.
```
--> Cipher data must be zero padded:
    encryptedAndAuthenticated[N] = { zeroPadded[16] , cipher[N-16] }
--> Decrypt:
    clearText[N-32] = { zeroPadded[32] , clearText[N-32] }
```

Both the crypto_box_afternm and the crypto_box_open_afternm methods allows to perform the cryptographic operations directly on the buffers.

**Hashing:**
sha512 is used for hashing and the size of a hash is 64 bytes. If the message to hash is larger than 64 bytes, the API allows for putting the hash where the original message was. I.e.: We don't need a specific storage for the hash, if we dont want to save the original message.

**Signing:**
The TweetNaCl API doesn't allow to only generate a signature (64 bytes) or verify a message with the signature separated from the message. Further, the API requires a seperate buffer to put the signed and unsigned message in.

### Server handshaking procedure

TODO: Write or refer to  code.

### Client handshaking procedure

TODO: Write or refer to code.


text:
**This cookbook is no longer maintained and is deprecated in favor of the [Opscode aws
cookbook](https://github.com/opscode-cookbooks/aws)**

**If you are interested in assuming maintenance of this cookbook, please [open an issue](https://github.com/opscode-cookbooks/aws/issues).**

# aws-sdk Cookbook

[![Cookbook Version](http://img.shields.io/cookbook/v/aws-sdk.svg)][cookbook]
[![Build Status](https://travis-ci.org/americanhonors-cookbooks/aws-sdk.svg?branch=master)][build-status]
[![Dependency Status](https://gemnasium.com/americanhonors-cookbooks/aws-sdk.svg)][dependency-status]

Installs the [aws-sdk][aws-sdk-gem] gem for use in other cookbooks.

## Requirements

### Dependencies

* [apt](https://github.com/opscode-cookbooks/apt)
* [build-essential](https://github.com/opscode-cookbooks/build-essential)

### Platforms

The following platforms are supported and tested:

* Ubuntu 12.04
* Ubuntu 14.04

Other Debian distributions are assumed to work.

## Attributes

### default

* `node['aws-sdk']['version']` - The version of the aws-sdk gem to install. (Default: `1.42.0`)
* `node['aws-sdk']['unf_version']` - The Version of the unf gem to install. (Default: `0.1.4`)

## Recipes

### default

The default recipe will install the aws-sdk and unf gems into Chef's gem environment.

**Note**: The default recipe overrides the `['apt']['compile_time_update']` and  `['build-essential']['compile_time']` attributes to ensure that the necessary development tools are installed for Nokogiri (a dependency of aws-sdk) to compile.

## Usage

Include the default recipe in your node or role.

## Development & Testing

### Rake

    $ bundle exec rake -T
    rake integration:cloud    # Run Test Kitchen with cloud plugins
    rake integration:vagrant  # Run Test Kitchen with Vagrant
    rake spec                 # Run ChefSpec examples
    rake style                # Run all style checks
    rake style:chef           # Lint Chef cookbooks
    rake style:ruby           # Run Ruby style checks
    rake travis               # Run all tests on Travis

### Versioning

The aws-sdk cookbook will always use the version of the aws-sdk gem set in the `[aws-sdk][version]` attribute for versioning.

## Contributing

1. Fork the repository on Github
2. Create a named feature branch (i.e. `feature/add-new-recipe`)
3. Write your change
4. Write ChefSpec and/or Serverspec tests for your change (if applicable)
5. Run the tests (see above), ensuring they all pass
6. Submit a Pull Request

## License & Authors

* Author:: Tony Burns (<tony.burns@quadlearninginc.com>)

```text
Copyright (c) 2014 Quad Learning, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

[cookbook]: http://community.opscode.com/cookbooks/aws-sdk
[build-status]: https://travis-ci.org/americanhonors-cookbooks/aws-sdk
[dependency-status]: https://gemnasium.com/americanhonors-cookbooks/aws-sdk
[aws-sdk-gem]: https://aws.amazon.com/sdkforruby/
[opscode-cookbooks]: https://github.com/opscode-cookbooks


text:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.Blob;

class GameOptions {
	static public GameOptions getGameOptions(String gameID, Connection con) throws SQLException {
		// TODO: look in cache
		// TODO: if not in cache, make new one and put in cache

// just quick hack for now: always generate new object
		return new GameOptions(gameID, con);
	}

	//protected String gameID;
	public GameOptions(String gameID, Connection con) throws SQLException {
		//this.gameID = gameID;

		//// read options from $options table in database
		//Connection con = DriverManager.getConnection(LeaderboardREST.settings.url, LeaderboardREST.settings.user, LeaderboardREST.settings.password);
		Statement st = con.createStatement();
		onlyKeepBestEntry = false;
		maxEntries = 0;
		String qustr = "SELECT * FROM mygame.$options WHERE game = \'" + gameID + "\';";
		if (LeaderboardREST.DEBUG) System.out.println(qustr + "\n");
		ResultSet rs = st.executeQuery(qustr);
		ResultSetMetaData rsmd = rs.getMetaData();
		//int columnCount = rsmd.getColumnCount();
		if (rs.next()) { // only first position
			maxEntries = rs.getInt("maxEntries");
			onlyKeepBestEntry = rs.getBoolean("onlyKeepBestEntry");
			addUpScore = rs.getBoolean("addUpScore");
			socialnetwork = rs.getString("socialnetwork");
		}
		if (LeaderboardREST.DEBUG) {
			System.out.println("socialnetwork: " + socialnetwork);
			//System.out.println(result.toString() + "\n");
		}
		//// end read options from database
	}

	protected int maxEntries;
	public int getMaxEntries() { return maxEntries; }

	protected String socialnetwork;
	public String getSocialNetwork() { return socialnetwork; }

	protected boolean onlyKeepBestEntry;
	public boolean getOnlyKeepBestEntry() { return onlyKeepBestEntry; }

	protected boolean addUpScore;
	public boolean getAddUpScore() { return addUpScore; }
}


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('controller:start/interests', 'Unit | Controller | start/interests', {
  // Specify the other units that are required for this test.
  needs: ['service:metrics']
});

// Replace this with your real tests.
test('it exists', function(assert) {
  let controller = this.subject();
  assert.ok(controller);
});


text:
author: slowe
comments: false
date: 2006-04-17 21:45:50+00:00
layout: post
slug: freenas-on-esx-server
title: FreeNAS on ESX Server
wordpress_id: 225
categories: Information
tags:
- BSD
- ESX
- NAS
- Virtualization
- VMware
- Interoperability
---

As part of ongoing interoperability testing with [ESX Server](http://www.vmware.com/products/esx/), I tested running [FreeNAS](http://www.freenas.org/) (version 0.65) on ESX Server 2.5.3 today. Since FreeNAS is based on [FreeBSD](http://www.freebsd.org/) (which [VMware](http://www.vmware.com/) states is a supported guest operating system for ESX Server), I didn't really expect any major surprises. I was wrong.

Basically, I couldn't make it work. Despite trying both the BusLogic SCSI adapter (the default) and the LSI Logic adapter, the FreeNAS distribution wouldn't see the virtualized SCSI hard disks, and therefore I could never install FreeNAS to the hard disk for use. Without the XML configuration file on a read/write media, FreeNAS lost its settings (such as the IP address or the network interface to use) every time it rebooted.

It's odd that FreeBSD, a supported guest OS, didn't appear to work, yet I was able to make [OpenBSD](http://www.openbsd.org/) (an _unsupported_ guest OS) run without any major problems.

Anyone have any tips for making FreeNAS 0.65 work under VMware ESX Server?


text:
redirect_from: /docs/1.0.10/modules/hooks.html
---
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>hooks | @uirouter/angularjs</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">
	<link rel="stylesheet" href="../assets/css/uirouter.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					@uirouter/angularjs

						Options

							<input type="checkbox" id="tsd-filter-externals" checked />
							Internal UI-Router API

					Menu

					@uirouter/angularjs

					hooks

Module hooks

Index

Variables

on<wbr>Enter<wbr>Hook

on<wbr>Exit<wbr>Hook

on<wbr>Retain<wbr>Hook

Functions

activate<wbr>Views

add<wbr>Core<wbr>Resolvables

eager<wbr>Resolve<wbr>Path

ignored<wbr>Hook

invalid<wbr>Transition<wbr>Hook

lazy<wbr>Load<wbr>Hook

lazy<wbr>Load<wbr>State

lazy<wbr>Resolve<wbr>State

load<wbr>Entering<wbr>Views

redirect<wbr>ToHook

register<wbr>Activate<wbr>Views

register<wbr>Add<wbr>Core<wbr>Resolvables

register<wbr>Eager<wbr>Resolve<wbr>Path

register<wbr>Ignored<wbr>Transition<wbr>Hook

register<wbr>Invalid<wbr>Transition<wbr>Hook

register<wbr>Lazy<wbr>Load<wbr>Hook

register<wbr>Lazy<wbr>Resolve<wbr>State

register<wbr>Load<wbr>Entering<wbr>Views

register<wbr>OnEnter<wbr>Hook

register<wbr>OnExit<wbr>Hook

register<wbr>OnRetain<wbr>Hook

register<wbr>Redirect<wbr>ToHook

register<wbr>Update<wbr>Global<wbr>State

register<wbr>Update<wbr>Url

update<wbr>Global<wbr>State

update<wbr>Url

Variables

on<wbr>Enter<wbr>Hook: TransitionStateHookFn = makeEnterExitRetainHook('onEnter')

 The TransitionStateHookFn for onEnter

The TransitionStateHookFn for onEnter

When the state is being entered, the state's .onEnter function is invoked.

Registered using transitionService.onEnter({ entering: (state) => !!state.onEnter }, onEnterHook);

See: IHookRegistry.onEnter

Defined in core/src/hooks/onEnterExitRetain.ts:60

on<wbr>Exit<wbr>Hook: TransitionStateHookFn = makeEnterExitRetainHook('onExit')

 The TransitionStateHookFn for onExit

The TransitionStateHookFn for onExit

When the state is being exited, the state's .onExit function is invoked.

Registered using transitionService.onExit({ exiting: (state) => !!state.onExit }, onExitHook);

See: IHookRegistry.onExit

Defined in core/src/hooks/onEnterExitRetain.ts:34

on<wbr>Retain<wbr>Hook: TransitionStateHookFn = makeEnterExitRetainHook('onRetain')

 The TransitionStateHookFn for onRetain

The TransitionStateHookFn for onRetain

When the state was already entered, and is not being exited or re-entered, the state's .onRetain function is invoked.

Registered using transitionService.onRetain({ retained: (state) => !!state.onRetain }, onRetainHook);

See: IHookRegistry.onRetain

Defined in core/src/hooks/onEnterExitRetain.ts:47

Functions

activate<wbr>Views(transition: Transition): void

 A TransitionHookFn which activates the new views when a transition is successful.

A TransitionHookFn which activates the new views when a transition is successful.

Registered using transitionService.onSuccess({}, activateViews);

After a transition is complete, this hook deactivates the old views from the previous state,
								and activates the new views from the destination state.

See ViewService

Parameters

transition Transition

Returns void

Defined in core/src/hooks/views.ts:39

add<wbr>Core<wbr>Resolvables(trans: Transition): void

Parameters

trans Transition

Returns void

Defined in core/src/hooks/coreResolvables.ts:6

eager<wbr>Resolve<wbr>Path(trans: Transition): Promise<any>

 A TransitionHookFn which resolves all EAGER Resolvables in the To Path

A TransitionHookFn which resolves all EAGER Resolvables in the To Path

Registered using transitionService.onStart({}, eagerResolvePath);

When a Transition starts, this hook resolves all the EAGER Resolvables, which the transition then waits for.

See StateDeclaration.resolve

Parameters

trans Transition

Returns Promise<any>

Defined in core/src/hooks/resolve.ts:20

ignored<wbr>Hook(trans: Transition): Promise<any>

 A TransitionHookFn that skips a transition if it should be ignored

A TransitionHookFn that skips a transition if it should be ignored

This hook is invoked at the end of the onBefore phase.

If the transition should be ignored (because no parameter or states changed)
								then the transition is ignored and not processed.

Parameters

trans Transition

Returns Promise<any>

Defined in core/src/hooks/ignoredTransition.ts:16

invalid<wbr>Transition<wbr>Hook(trans: Transition): void

 A TransitionHookFn that rejects the Transition if it is invalid

A TransitionHookFn that rejects the Transition if it is invalid

This hook is invoked at the end of the onBefore phase.
									If the transition is invalid (for example, param values do not validate)
								then the transition is rejected.

Parameters

trans Transition

Returns void

Defined in core/src/hooks/invalidTransition.ts:13

lazy<wbr>Load<wbr>Hook(transition: Transition): Promise<TargetState>

 A TransitionHookFn that performs lazy loading

A TransitionHookFn that performs lazy loading

When entering a state "abc" which has a lazyLoad function defined:

Invoke the lazyLoad function (unless it is already in process)

Flag the hook function as "in process"

The function should return a promise (that resolves when lazy loading is complete)

Wait for the promise to settle

If the promise resolves to a LazyLoadResult, then register those states

Flag the hook function as "not in process"

If the hook was successful

Remove the lazyLoad function from the state declaration

If all the hooks were successful

Retry the transition (by returning a TargetState)

.state('abc', {
  component: 'fooComponent',
  lazyLoad: () => System.import('./fooComponent')
  });

See StateDeclaration.lazyLoad

Parameters

transition Transition

Returns Promise<TargetState>

Defined in core/src/hooks/lazyLoad.ts:33

lazy<wbr>Load<wbr>State(transition: Transition, state: StateDeclaration): Promise<LazyLoadResult>

 Invokes a state's lazy load function

Invokes a state's lazy load function

Parameters

transition Transition

									:

a Transition context

state StateDeclaration

									:

the state to lazy load

Returns Promise<LazyLoadResult>

								:
A promise for the lazy load result

Defined in core/src/hooks/lazyLoad.ts:80

lazy<wbr>Resolve<wbr>State(trans: Transition, state: StateDeclaration): Promise<any>

 A TransitionHookFn which resolves all LAZY Resolvables for the state (and all its ancestors) in the To Path

A TransitionHookFn which resolves all LAZY Resolvables for the state (and all its ancestors) in the To Path

Registered using transitionService.onEnter({ entering: () => true }, lazyResolveState);

When a State is being entered, this hook resolves all the Resolvables for this state, which the transition then waits for.

See StateDeclaration.resolve

Parameters

trans Transition

state StateDeclaration

Returns Promise<any>

Defined in core/src/hooks/resolve.ts:37

load<wbr>Entering<wbr>Views(transition: Transition): Promise<any>

 A TransitionHookFn which waits for the views to load

A TransitionHookFn which waits for the views to load

Registered using transitionService.onStart({}, loadEnteringViews);

Allows the views to do async work in ViewConfig.load before the transition continues.
								In angular 1, this includes loading the templates.

Parameters

transition Transition

Returns Promise<any>

Defined in core/src/hooks/views.ts:19

redirect<wbr>ToHook(trans: Transition): TargetState | Promise<TargetState>

 A TransitionHookFn that redirects to a different state or params

A TransitionHookFn that redirects to a different state or params

Registered using transitionService.onStart({ to: (state) => !!state.redirectTo }, redirectHook);

See StateDeclaration.redirectTo

Parameters

trans Transition

Returns TargetState
									 |
									Promise<TargetState>

Defined in core/src/hooks/redirectTo.ts:16

register<wbr>Activate<wbr>Views(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/views.ts:52

register<wbr>Add<wbr>Core<wbr>Resolvables(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/coreResolvables.ts:17

register<wbr>Eager<wbr>Resolve<wbr>Path(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/resolve.ts:25

register<wbr>Ignored<wbr>Transition<wbr>Hook(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/ignoredTransition.ts:34

register<wbr>Invalid<wbr>Transition<wbr>Hook(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/invalidTransition.ts:19

register<wbr>Lazy<wbr>Load<wbr>Hook(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/lazyLoad.ts:69

register<wbr>Lazy<wbr>Resolve<wbr>State(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/resolve.ts:43

register<wbr>Load<wbr>Entering<wbr>Views(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/views.ts:26

register<wbr>OnEnter<wbr>Hook(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/onEnterExitRetain.ts:61

register<wbr>OnExit<wbr>Hook(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/onEnterExitRetain.ts:35

register<wbr>OnRetain<wbr>Hook(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/onEnterExitRetain.ts:48

register<wbr>Redirect<wbr>ToHook(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/redirectTo.ts:36

register<wbr>Update<wbr>Global<wbr>State(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/updateGlobals.ts:39

register<wbr>Update<wbr>Url(transitionService: TransitionService): Function

Parameters

transitionService TransitionService

Returns Function

Defined in core/src/hooks/url.ts:30

update<wbr>Global<wbr>State(trans: Transition): void

 A TransitionHookFn which updates global UI-Router state

A TransitionHookFn which updates global UI-Router state

Registered using transitionService.onBefore({}, updateGlobalState);

Before a Transition starts, updates the global value of "the current transition" ([[Globals.transition]]).
									After a successful Transition, updates the global values of "the current state"
								([[Globals.current]] and [[Globals.$current]]) and "the current param values" ([[Globals.params]]).

See also the deprecated properties:
								StateService.transition, StateService.current, StateService.params

Parameters

trans Transition

Returns void

Defined in core/src/hooks/updateGlobals.ts:19

update<wbr>Url(transition: Transition): void

 A TransitionHookFn which updates the URL after a successful transition

A TransitionHookFn which updates the URL after a successful transition

Registered using transitionService.onSuccess({}, updateUrl);

Parameters

transition Transition

Returns void

Defined in core/src/hooks/url.ts:13

						@uirouter/angularjs

						Public API

						core

						directives

						injectables

						ng1

						ng1_<wbr>state_<wbr>events

						params

						resolve

						trace

						transition

						url

						view

						Internal UI-<wbr><wbr>Router API

						common

						common_<wbr>hof

						common_<wbr>predicates

						common_<wbr>strings

						hooks

						path

						state

						vanilla

						on<wbr>Enter<wbr>Hook

						on<wbr>Exit<wbr>Hook

						on<wbr>Retain<wbr>Hook

						activate<wbr>Views

						add<wbr>Core<wbr>Resolvables

						eager<wbr>Resolve<wbr>Path

						ignored<wbr>Hook

						invalid<wbr>Transition<wbr>Hook

						lazy<wbr>Load<wbr>Hook

						lazy<wbr>Load<wbr>State

						lazy<wbr>Resolve<wbr>State

						load<wbr>Entering<wbr>Views

						redirect<wbr>ToHook

						register<wbr>Activate<wbr>Views

						register<wbr>Add<wbr>Core<wbr>Resolvables

						register<wbr>Eager<wbr>Resolve<wbr>Path

						register<wbr>Ignored<wbr>Transition<wbr>Hook

						register<wbr>Invalid<wbr>Transition<wbr>Hook

						register<wbr>Lazy<wbr>Load<wbr>Hook

						register<wbr>Lazy<wbr>Resolve<wbr>State

						register<wbr>Load<wbr>Entering<wbr>Views

						register<wbr>OnEnter<wbr>Hook

						register<wbr>OnExit<wbr>Hook

						register<wbr>OnRetain<wbr>Hook

						register<wbr>Redirect<wbr>ToHook

						register<wbr>Update<wbr>Global<wbr>State

						register<wbr>Update<wbr>Url

						update<wbr>Global<wbr>State

						update<wbr>Url

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
<?php

namespace RawPHP\RawLog\Handler;

use RawPHP\RawLog\Contract\IFormatter;
use RawPHP\RawLog\Contract\IHandler;
use RawPHP\RawLog\Contract\IRecord;
use RawPHP\RawLog\Exception\LogException;
use RawPHP\RawLog\Log;
use RawPHP\RawLog\Record\ErrorLogRecord;

/**
 * This is the normal logging class.
 *
 * @category  PHP
 * @package   RawPHP\RawLog\Handler
 * @author    Tom Kaczocha <tom@rawphp.org>
 * @copyright 2014 Tom Kaczocha
 * @license   http://rawphp.org/license.txt MIT
 * @link      http://rawphp.org/
 */
class FileHandler implements IHandler
{
    /**
     * @var int
     */
    private $_level = Log::LEVEL_DEBUG;
    /**
     * @var string
     */
    protected $fileName = 'log.txt';
    /**
     * @var IFormatter
     */
    private $_formatter = NULL;

    /**
     * @param array $config
     */
    public function __construct( $config = [ ] )
    {
        $this->init( $config );
    }

    /**
     * Initialises the handler.
     *
     * @param array $config configuration array
     */
    public function init( $config = [ ] )
    {
        foreach ( $config as $key => $value )
        {
            switch ( $key )
            {
                case 'level':
                    $this->_level = ( int ) $value;
                    break;

                case 'file':
                    $this->fileName = $value;
                    break;

                case 'formatter':
                    $this->_formatter = new $value();
                    break;

                default:
                    // do nothing
                    break;
            }
        }
    }

    /**
     * Returns the minimum log level.
     *
     * @return int log level
     */
    public function getLevel()
    {
        return $this->_level;
    }

    /**
     * Returns the log file name.
     *
     * @return string log file name
     */
    public function getFileName()
    {
        return $this->fileName;
    }

    /**
     * Returns the assigned formatter.
     *
     * @return IFormatter the formatter
     */
    public function getFormatter()
    {
        return $this->_formatter;
    }

    /**
     * Sets the formatter for this handler to use.
     *
     * @param IFormatter $formatter the formatter
     */
    public function setFormatter( IFormatter $formatter )
    {
        $this->_formatter = $formatter;
    }

    /**
     * Creates and returns a new record.
     *
     * @param int   $level the log level
     * @param array $args  the log message
     *
     * @return IRecord the record instance
     */
    public function createRecord( $level, array $args )
    {
        $record = new ErrorLogRecord( $level, $args[ 'message' ] );

        return $record;
    }

    /**
     * Handles the logging.
     *
     * This method calls FileHandler::getFormatter() which means that
     * you can use the filter to alter the format if desired.
     *
     * @param IRecord $record the record to log
     *
     * @throws LogException if it fails to create the file.
     */
    public function handle( IRecord $record )
    {
        // check if we should be logging this record
        if ( $record->getLevel() >= $this->_level )
        {
            // check if file exists
            if ( !file_exists( $this->fileName ) )
            {
                if ( !touch( $this->fileName ) )
                {
                    throw new LogException( 'Failed to create log file: ' . $this->fileName );
                }
            }

            file_put_contents(
                $this->fileName,
                $this->getFormatter()->format( $record ),
                FILE_APPEND
            );
        }
    }
}


text:
FactoryBot.define do
  factory :role do
    resource { nil }
    user { FactoryBot.create(:user) }
    role { 'admin' }
  end
end


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_XML_XML_SERIALIZER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_XML_XML_SERIALIZER_H_

#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"

namespace blink {

class Node;

class XMLSerializer final : public ScriptWrappable {
  DEFINE_WRAPPERTYPEINFO();

 public:
  static XMLSerializer* Create() {
    return MakeGarbageCollected<XMLSerializer>();
  }

  XMLSerializer() = default;

  String serializeToString(Node*);
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_XML_XML_SERIALIZER_H_


text:
[![Build Status](https://travis-ci.org/fza/format-throw.svg)](https://travis-ci.org/fza/format-throw) [![Coverage Status](https://coveralls.io/repos/fza/format-throw/badge.svg?branch=master)](https://coveralls.io/r/fza/format-throw?branch=master) [![Dependency Status](https://david-dm.org/fza/format-throw.svg)](https://david-dm.org/fza/format-throw) [![devDependency Status](https://david-dm.org/fza/format-throw/dev-status.svg)](https://david-dm.org/fza/format-throw#info=devDependencies)

[![NPM](https://nodei.co/npm/format-throw.png)](https://npmjs.org/package/format-throw)

> Tiny utility to throw errors with formatted messages and support for custom error classes.

## Installation

```shell
npm install --save format-throw
```

## Usage

```javascript
var thr = require('format-throw');

// Throw a TypeError
thr(TypeError, '%s is not %s', 'foo', 'bar');

// Throw a default Error
thr('The meaning of life is %d', 42);

// Return the error instance instead of throwing it
var err1 = thr.make(TypeError, 'meaningOfLife should be %d', '42');
var err2 = thr.make("Inked %s ain't %s", 'donkeys', 'zebras');
```

## Contributing

Take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using `grunt test`.

## License

Copyright (c) 2015 [Felix Zandanel](mailto:felix@zandanel.me)
Licensed under the MIT license.

See LICENSE for more info.


text:
/* -*-C++-*-
******************************************************************************
*
* File:         Inlining.cpp
* Description:  Methods for the inliningInfo
*
* Created:      6/26/01
* Language:     C++
* Status:       $State: Exp $
*
*
******************************************************************************
*/
#include "Inlining.h"
#include "Triggers.h"
#include "TableDesc.h"
#include "RelUpdate.h"
#include "ItemColRef.h"
#include "RETDesc.h"
#include "ColumnDesc.h"
#include "BindWA.h"
#include "NormWA.h"
#include "ItemOther.h"
#include "ItemSample.h"
#include "SchemaDB.h"

// These "global" column names are used for inlining.
const char InliningInfo::execIdVirtualColName_[]   = "@EXECID";
const char InliningInfo::epochVirtualColName_[]    = "@CURRENT_EPOCH";
const char InliningInfo::mvLogTsColName_[]         = "@MVLOG_TS";
const char InliningInfo::rowtypeVirtualColName_[]  = "@ROW_TYPE";
const char InliningInfo::rowcountVirtualColName_[] = "@ROW_COUNT";

InliningInfo::~InliningInfo()
{
  delete forceCardinalityInfo_;
  delete triggerBindInfo_;
}

//-----------------------------------------------------------------------------
// Merge other InliningInfo object into this.
//-----------------------------------------------------------------------------

void InliningInfo::merge(InliningInfo *other)
{
  if (other != NULL)
  {
    flags_ |= other->flags_;

    // Only one (at most) of the two merged objects can have
    // a triggerObject.
    CMPASSERT((other->triggerObject_==NULL) ||
	      (triggerObject_==NULL))
    if (other->triggerObject_ != NULL)
    {
      triggerObject_  = other->triggerObject_;
    }

    if (other->forceCardinalityInfo_ != NULL)
    {
      forceCardinalityInfo_  = new (CmpCommon::statementHeap())
	ForceCardinalityInfo(*(other->forceCardinalityInfo_));
    }

    if (getenv("SC_BUG")!=NULL) return;
    if (other->triggerBindInfo_ != NULL)
    {
      triggerBindInfo_  = new (CmpCommon::statementHeap())
	TriggerBindInfo(*(other->triggerBindInfo_));
    }
  }
}

//-----------------------------------------------------------------------------
// getNewCardinality() returns the value of  cardinality * cardinalityFactor_ .
// The cardinality is taken from either cardinality_ or when cardinality_ is
// zero from oldCardinality parameter.
//-----------------------------------------------------------------------------

CostScalar InliningInfo::getNewCardinality(CostScalar oldCardinality) const
{
  CMPASSERT(forceCardinalityInfo_);

  if (forceCardinalityInfo_->cardinality_ != 0)
  {
    return MIN_ONE_CS(forceCardinalityInfo_->cardinality_ *
           forceCardinalityInfo_->cardinalityFactor_);
  }

  return MIN_ONE_CS(oldCardinality * forceCardinalityInfo_->cardinalityFactor_);
}

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

void InliningInfo::BuildForceCardinalityInfo(double cardinalityFactor,
					     Cardinality cardinality,
					     CollHeap *heap)
{
  forceCardinalityInfo_ = new(heap) ForceCardinalityInfo();

  forceCardinalityInfo_->cardinalityFactor_ = cardinalityFactor;
  forceCardinalityInfo_->cardinality_ = cardinality;
}

//-----------------------------------------------------------------------------
// Constructs the TriggerBindInfo object, and stores the Execute-ID of the
// current query and the current IUD No. for further use at triggers'
// transformation time.
//-----------------------------------------------------------------------------

void
InliningInfo::buildTriggerBindInfo(BindWA *bindWA,
				   RETDesc *RETDesc,
				   CollHeap *heap )
{
  triggerBindInfo_ = new(heap) TriggerBindInfo(heap);

  // store the Execute-ID of the current query
  triggerBindInfo_->setExecuteId();
  triggerBindInfo_->getExecuteId()->bindNode(bindWA);

  // store the current backbone IUD No.
  triggerBindInfo_->setBackboneIudNum(bindWA->getUniqueIudNum());

  // Copy all user and system columns from the given RETDesc for use during
  // sub-trees constructions in triggers' transformation phase.

  ColumnDescList *copiedList = new(heap) ColumnDescList(heap);
  CollIndex i;
  for (i = 0; i < RETDesc->getColumnList()->entries(); i++)
  {
    ColumnDesc *colDesc = RETDesc->getColumnList()->at(i);
    copiedList->insert(new(heap) ColumnDesc(*colDesc));
  }

  for (i = 0; i < RETDesc->getSystemColumnList()->entries(); i++)
  {
    ColumnDesc *colDesc = RETDesc->getSystemColumnList()->at(i);
    copiedList->insert(new(heap) ColumnDesc(*colDesc));
  }
  triggerBindInfo_->setIudColumnList(copiedList);
}

//----------------------------------------------------------------------------
// copy Ctor of ForceCardinalityInfo object
//----------------------------------------------------------------------------

ForceCardinalityInfo::ForceCardinalityInfo(const ForceCardinalityInfo &other)
{
  cardinality_ = other.cardinality_;

  cardinalityFactor_ = other.cardinalityFactor_;
}

//-----------------------------------------------------------------------------
// copy Ctor of TriggerBindInfo object
//-----------------------------------------------------------------------------

TriggerBindInfo::TriggerBindInfo(const TriggerBindInfo &other)
{
  heap_ = other.heap_;
  if (other.exeId_)
  {
    exeId_ = new (heap_) UniqueExecuteId();

    // Would like to bind this new copy, but we don't have a BindWA
    // handy.  Since this is an "execute-once" function, and so it
    // should always bind to the same ValueId, simply copy the ValueId
    // from the original.  (Alternatively, could we safely share the
    // original ItemExpr and avoid making a copy?)
    //
    exeId_->setValueId(other.exeId_->getValueId());
  }
  backboneIudNum_ = other.backboneIudNum_;

  origIudColumnList_ = other.origIudColumnList_;
}

//-----------------------------------------------------------------------------
// Normilizes all the data members that need to be normalized. This method is
// called from GenericUpdate::rewriteNode in NormRelExpr.cpp
//-----------------------------------------------------------------------------

void TriggerBindInfo::normalizeMembers(NormWA & normWA)
{
  // Normalize the execute-id
  exeId_->normalizeNode(normWA);
}


text:
layout: page
title: Snow Sphere Industries Trade Fair
date: 2016-05-24
author: Janet Ray
tags: weekly links, java
status: published
summary: Donec felis metus, aliquet et.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/24/2019
  endDate: 10/26/2019
  ctyhocn: DALETHX
  groupCode: SSITF
published: true
---
Nunc tincidunt tempus lacus. Proin egestas pellentesque congue. Maecenas sodales fringilla erat et facilisis. Morbi sed felis in eros luctus porta. Proin turpis nulla, ultrices quis condimentum non, placerat a ligula. Fusce id velit urna. Nulla commodo ipsum nec risus egestas, a sollicitudin justo sagittis. Aenean sagittis lacus non ipsum fringilla rhoncus ac non nisl.

* Morbi eget metus tincidunt metus tincidunt interdum
* Quisque sit amet purus posuere, ultricies enim non, mollis neque
* Donec vel lectus vitae lectus tincidunt sagittis
* Nullam vitae eros sodales, tempor est vitae, euismod ex.

Phasellus mollis convallis fermentum. Aenean mattis molestie varius. Morbi placerat vestibulum orci, sit amet ullamcorper turpis dictum in. Proin tellus orci, vulputate eu turpis et, placerat placerat odio. Vestibulum augue neque, vestibulum sit amet aliquam ac, vehicula fermentum dui. Fusce consequat tempus neque, sed laoreet leo congue eget. Mauris iaculis accumsan ligula non pharetra.


text:
package gov.samhsa.consent2share.service.reference;

import gov.samhsa.consent2share.service.dto.LookupDto;

import java.util.List;

/**
 * The Interface StateCodeService.
 */
public interface StateCodeService {

	/**
	 * Find all state codes.
	 *
	 * @return the list
	 */
	List<LookupDto> findAllStateCodes();
}


text:
  Ruesnes est
       un village
       géographiquement positionné dans le département de Nord en Nord-Pas-de-Calais. Elle comptait 451 habitants en 2008.

À coté de Ruesnes sont localisées les communes de
Maresches localisée à 3 km, 911 habitants,
Sepmeries située à 3 km, 548 habitants,
Capelle située à 3 km, 167 habitants,
Ghissignies localisée à 4 km, 450 habitants,
Le Quesnoy située à 3 km, 5 112 habitants,
Escarmain localisée à 4 km, 430 habitants,
 entre autres. De plus, Ruesnes est située à seulement onze km de Valenciennes.

Le nombre de logements, à Ruesnes, était réparti en 2011 en quatre appartements et 180 maisons soit
 un marché relativement équilibré.

Si vous pensez demenager à Ruesnes, vous pourrez facilement trouver une maison à acheter.

Ruesnes est localisé à seulement 9 km de Aulnoy-lez-Valenciennes, les élèves qui souhaiteront se loger à pas cher pourront envisager de prendre un appartement à Ruesnes. Ruesnes est également un bon investissement locatif du fait de sa proximité de Aulnoy-lez-Valenciennes et de ses Universités. Il sera facile de trouver un logement à vendre.


text:
export {
  InputWithSuggestionsContainer as InputWithVariableAutoCompletion,
  TextareaWithSuggestionsContainer as TextareaWithVariableAutoCompletion,
  RichTextareaWithSuggestionsContainer as RichTextareaWithVariableAutoCompletion
} from './containers/control-with-suggestions-container';


text:
package org.callimachusproject.server.exceptions;

/**
 * The server does not support the functionality required to fulfill the
 * request. This is the appropriate response when the server does not recognize
 * the request method and is not capable of supporting it for any resource.
 */
public class NotImplemented extends ResponseException {
	private static final long serialVersionUID = 4773581231132742758L;

	public NotImplemented() {
		super("Not Implemented");
	}

	public NotImplemented(String message, Throwable cause) {
		super(message, cause);
	}

	public NotImplemented(String message) {
		super(message);
	}

	public NotImplemented(Throwable cause) {
		super(cause);
	}

	public NotImplemented(String message, String stack) {
		super(message, stack);
	}

	@Override
	public int getStatusCode() {
		return 501;
	}

}


text:
<?php

namespace phpDocumentor\Transformer\Configuration\Transformations;

/**
 * Test for a template configuration definition.
 */
class TemplateTest extends \PHPUnit_Framework_TestCase
{
    const EXAMPLE_NAME = 'name';

    /** @var Template */
    private $fixture;

    /**
     * Initializes the fixture for this test.
     */
    public function setUp()
    {
        $this->fixture = new Template(self::EXAMPLE_NAME);
    }

    /**
     * @covers phpDocumentor\Transformer\Configuration\Transformations\Template::__construct
     * @covers phpDocumentor\Transformer\Configuration\Transformations\Template::getName
     */
    public function testIfNameCanBeRetrieved()
    {
        $this->assertSame(self::EXAMPLE_NAME, $this->fixture->getName());
    }
}


text:
import glob
from natsort import natsorted

list_toy = natsorted(glob.glob("*toy_dataset_iter*"))
list_toy_str = " ".join(list_toy)

with open("make_gif.sh", "w") as f:

    cmd = "convert -delay 15 -resize 300x300 -loop 0 %s MoG_dataset.gif" % list_toy_str
    f.write(cmd)


text:
// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package thrift

import (
	"fmt"
	"io"
	"io/ioutil"

	"github.com/uber/tchannel/golang/typed"
)

// TODO(prashant): Use a small buffer and then flush it when it's full.
func writeHeaders(w io.Writer, headers map[string]string) error {
	// Calculate the size of the buffer that we need.
	size := 2
	for k, v := range headers {
		size += 4 /* size of key/value lengths */
		size += len(k) + len(v)
	}

	buf := make([]byte, size)
	writeBuffer := typed.NewWriteBuffer(buf)
	writeBuffer.WriteUint16(uint16(len(headers)))
	for k, v := range headers {
		writeBuffer.WriteLen16String(k)
		writeBuffer.WriteLen16String(v)
	}

	if err := writeBuffer.Err(); err != nil {
		return err
	}

	// Safety check to ensure the bytes written calculation is correct.
	if writeBuffer.BytesWritten() != size {
		return fmt.Errorf("writeHeaders size calculation wrong, expected to write %v bytes, only wrote %v bytes",
			size, writeBuffer.BytesWritten())
	}

	_, err := writeBuffer.FlushTo(w)
	return err
}

// TODO(prashant): Allow typed.ReadBuffer to read directly from the reader.
func readHeaders(r io.Reader) (map[string]string, error) {
	bs, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}

	buffer := typed.NewReadBuffer(bs)
	numHeaders := buffer.ReadUint16()
	if numHeaders == 0 {
		return nil, buffer.Err()
	}

	headers := make(map[string]string)
	for i := 0; i < int(numHeaders) && buffer.Err() == nil; i++ {
		k := buffer.ReadLen16String()
		v := buffer.ReadLen16String()
		headers[k] = v
	}
	return headers, buffer.Err()
}


text:
@interface CCFileCache ()
{
    NSString *_cachePath;
    dispatch_semaphore_t _lock;
}
@end

@implementation CCFileCache
+ (instancetype)fileCache {
    return [[self alloc] initWithPath:@"FileCaches"];
}

- (instancetype)initWithPath:(NSString *)path {
    if (self = [super init]) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *cachePath = [[paths firstObject] stringByAppendingPathComponent:path];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDirectory = NO;
        BOOL isExists = [fileManager fileExistsAtPath:cachePath isDirectory:&isDirectory];
        if (!isExists) {
            [fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES attributes:NULL error:NULL];
        }  else if (isExists && !isDirectory) {
            [fileManager removeItemAtPath:cachePath error:NULL];
            [fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES attributes:NULL error:NULL];
        }
        NSLog(@"cachePath:%@", cachePath);
        _cachePath = cachePath;
    }
    return self;
}

- (NSData *)dataForKey:(NSString *)key {
    if (key == nil) return nil;
    NSString *filePath = [self filePathForKey:key];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:filePath]) {
        return nil;
    }
    return [NSData dataWithContentsOfFile:filePath];
}

- (void)setData:(NSData *)data forKey:(NSString *)key {
    if (data == nil || key == nil) return;
    NSString *filePath = [self filePathForKey:key];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        [fileManager removeItemAtPath:filePath error:NULL];
    }
    [data writeToFile:filePath options:NSDataWritingAtomic error:NULL];
}

- (id<NSCoding>)objectForKey:(NSString *)key {
    id object = nil;
    NSData *data = [self dataForKey:key];
    if (data && data.length > 0) {
        @try {
            object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        } @catch (NSException *exception) {} @finally {}
    }
    return object;
}

- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key {
    if (object == nil || key == nil) return;
    NSData *data = nil;
    @try {
        data = [NSKeyedArchiver archivedDataWithRootObject:object];
    } @catch (NSException *exception) {} @finally {}
    if (data && data.length > 0) {
        [self setData:data forKey:key];
    }
}

- (void)removeObjectForKey:(NSString *)key {
    if (key == nil) return;
    NSString *filePath = [self filePathForKey:key];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        [fileManager removeItemAtPath:filePath error:NULL];
    }
}

- (BOOL)containsObjectForKey:(NSString *)key {
    if (key == nil) return NO;
    NSString *filePath = [self filePathForKey:key];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:filePath];
}

- (NSString *)filePathForKey:(NSString *)key {
    const char *str = key.UTF8String;
    if (str == NULL) str = "";
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *hash = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                      r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    return [_cachePath stringByAppendingPathComponent:hash];
}

@end


text:
FactoryBot.define do
  factory :user_agent_detail do
    ip_address '127.0.0.1'
    user_agent 'AppleWebKit/537.36'
    association :subject, factory: :issue
  end
end


text:
Migrations.add({
  version: 1,
  name: 'Adds emailHash for all existing users',
  up: function() {
    Users.find({}).forEach(function(user) {
      var email = getUserEmail(user);
      if (email)
        Users.update({
          _id: user._id
        }, {
          $set: {
            emailHash: CryptoJS.MD5(email.trim().toLowerCase()).toString()
          }
        });
    });
  },
  down: function() {}
});

Migrations.add({
  version: 2,
  name: 'Adds isDeveloper for all existing users',
  up: function() {
    var profileUserIds = _.pluck(Profiles.find().fetch(), 'userId');
    Users.update({
      _id: {
        $in: profileUserIds
      }
    }, {
      $set: {
        isDeveloper: true
      }
    }, {
      multi: true
    });
    Users.update({
      _id: {
        $nin: profileUserIds
      }
    }, {
      $set: {
        isDeveloper: false
      }
    }, {
      multi: true
    });
  },
  down: function() {}
});

Migrations.add({
  version: 3,
  name: 'Adds randomSorter for all developers',
  up: function() {
    Profiles.find({}).forEach(function(profile) {
      Profiles.update({
        _id: profile._id
      }, {
        $set: {
          randomSorter: Math.floor(Math.random() * 10000)
        }
      });
    });
  },
  down: function() {}
});

Migrations.add({
  version: 4,
  name: 'Copy htmlDescription over to description',
  up: function() {
    Profiles.find({}).forEach(function(profile) {
      if(profile.htmlDescription)
        Profiles.update({
          _id: profile._id
        }, {
          $set: {
            description: profile.htmlDescription,
            htmlDescription: cleanHtml(profile.htmlDescription)
          }
        });
    });

    Jobs.find({}).forEach(function(job) {
      if(job.htmlDescription)
        Jobs.update({
          _id: job._id
        }, {
          $set: {
            description: job.htmlDescription,
            htmlDescription: cleanHtml(job.htmlDescription)
          }
        });
    });

  },
  down: function() {}
});

Migrations.add({
  version: 5,
  name: 'Set status for all profiles/jobs',
  up: function() {
    Profiles.update({},{$set:{status:"active"}}, {multi:true});
    Jobs.update({},{$set:{status:"active"}}, {multi:true});
  },
  down: function() {}
});

Migrations.migrateTo('latest');


text:
class BlankSlate
  class << self

    # Hide the method named +name+ in the BlankSlate class.  Don't
    # hide +instance_eval+ or any method beginning with "__".
    def hide(name)
      if instance_methods.include?(name) and name.to_s !~ /^(__|instance_eval|object_id)/
        @hidden_methods ||= {}
        @hidden_methods[name] = instance_method(name)
        undef_method name
      end
    end

    def find_hidden_method(name)
      @hidden_methods ||= {}
      @hidden_methods[name] || (superclass.find_hidden_method(name) if superclass.respond_to?(:find_hidden_method))
    end

    # Redefine a previously hidden method so that it may be called on a blank
    # slate object.
    def reveal(name)
      unbound_method = find_hidden_method(name)
      fail "Don't know how to reveal method '#{name}'" unless unbound_method
      define_method(name, unbound_method)
    end
  end

  instance_methods.each { |m| hide(m) }
end

module Kernel
  class << self
    alias_method :blank_slate_method_added, :method_added

    # Detect method additions to Kernel and remove them in the
    # BlankSlate class.
    def method_added(name)
      result = blank_slate_method_added(name)
      return result if self != Kernel
      BlankSlate.hide(name)
      result
    end
  end
end

class Object
  class << self
    alias_method :blank_slate_method_added, :method_added

    # Detect method additions to Object and remove them in the
    # BlankSlate class.
    def method_added(name)
      result = blank_slate_method_added(name)
      return result if self != Object
      BlankSlate.hide(name)
      result
    end

    def find_hidden_method(name)
      nil
    end
  end
end

class Module
  alias blankslate_original_append_features append_features
  def append_features(mod)
    result = blankslate_original_append_features(mod)
    return result if mod != Object
    instance_methods.each do |name|
      BlankSlate.hide(name)
    end
    result
  end
end