text:
var Name = require('./Name.js').Name;
var Selectors = require('./Selectors.js').Selectors;
var Block = require('./Block.js').Block;
var NdnType = require('./NdnType.js').NdnType;

var LOG = 0;

var Interest = function Interest (name)
{
    this.name = name;
    this.selectors = null;
    this.nonce = null;
    this.scope = null;
    this.interestLifetime = null; // in ms
};

exports.Interest = Interest;

Interest.prototype.from_tlv = function (block)
{
    if (LOG > 4)
	console.log('Interest.from_tlv: begin');

    var type = block.read_var_num ();  // read type
    if (type != NdnType.Interest)
	throw new Error ('Interest.from_tlv: wrong type');

    var len = block.read_var_num ();  // read length
    var end = block.head + len;  // end of Interest

    // read Name (mandatory)
    this.name = new Name ();
    this.name.from_tlv (block);

    // read optional fields
    while (block.head < end) {
	var t = block.peek_var_num ();  // peek type
	if (t == NdnType.Selectors) {
	    this.selectors = new Selectors ();
	    this.selectors.from_tlv (block);
	} else if (t == NdnType.Nonce) {  //XXX: should Nonce be mandatoray?
	    var t = block.read_var_num ();  // read type
	    var l = block.read_var_num ();  // read length
	    if (l != 4)
		throw new Error ('Interest.from_tlv: wrong length for Nonce');

	    this.nonce = block.read_nonneg_int (4);  // read Nonce as integer
	} else if (t == NdnType.Scope) {
	    var t = block.read_var_num ();  // read type
	    var l = block.read_var_num ();  // read length
	    this.scope = block.read_nonneg_int (l);
	} else if (t == NdnType.InterestLifetime) {
	    var t = block.read_var_num ();  // read type
	    var l = block.read_var_num ();  // read length
	    this.interestLifetime = block.read_nonneg_int (l);
	}
    }

    if (block.head != end)
	throw new Error ('Interest.from_tlv: wrong length');

    if (LOG > 4)
	console.log ('Interest.from_tlv: finish');
};

Interest.parse = function (buf)
{
    var block = new Block (buf);
    var inst = new Interest ();
    inst.from_tlv (block);
    return inst;
};

Interest.prototype.to_tlv = function (block)
{
    if (LOG > 4)
	console.log ('Interest.to_tlv: begin');

    if (this.name == null)
	throw new Error ('Interest.to_tlv: name cannot be empty');

    var val_len = 0;

    // Encode backward
    if (this.interestLifetime != null) {
	var l = block.push_nonneg_int (this.interestLifetime);  // encode value
	val_len += l;
	val_len += block.push_var_num (l);  // encode length
	val_len += block.push_var_num (NdnType.InterestLifetime);  // encode type
    }

    if (this.scope != null) {
	var l = block.push_nonneg_int (this.scope);  // encode value
	val_len += l;
	val_len += block.push_var_num (l);  // encode length
	val_len += block.push_var_num (NdnType.Scope);  // encode type
    }

    if (this.nonce != null) {
	// encode Nonce as 4 byte array
	block.push_byte (this.nonce);
	block.push_byte (this.nonce >> 8);
	block.push_byte (this.nonce >> 16);
	block.push_byte (this.nonce >> 24);
	val_len += 4;
	val_len += block.push_var_num (4);  // encode length
	val_len += block.push_var_num (NdnType.Nonce);  // encode type
    }

    if (this.selectors != null)
	val_len += this.selectors.to_tlv (block);

    val_len += this.name.to_tlv (block);

    var total_len = val_len;
    total_len += block.push_var_num (val_len);
    total_len += block.push_var_num (NdnType.Interest);

    if (LOG > 4)
	console.log ('Interest.to_tlv: finish');

    return total_len;
};

Interest.prototype.encodeToBinary = function ()
{
    var block = new Block ();
    this.to_tlv (block);
    return block.finalize ();
};

/*
 * Return true if this.name.match(name) and the name conforms to the interest selectors.
 */
Interest.prototype.matches_name = function (/*Name*/ name)
{
    if (!this.name.isPrefixOf (name))
        return false;

    if (this.selectors != null) {
	if (this.selectors.minSuffix != null &&
            !(name.components.length - this.name.components.length >= this.selectors.minSuffix))
            return false;

	if (this.selectors.maxSuffix != null &&
            !(name.components.length - this.name.components.length <= this.selectors.maxSuffix))
            return false;

	if (this.selectors.exclude != null && name.components.length > this.name.components.length &&
	    this.selectors.exclude.matches (name.components[this.name.components.length]))
	    return false;
    }

    return true;
};


text:
package pl.rodia.jopama.stats;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.Test;

public class OperationCounterUnitTests
{
	@Before
	public void initialize()
	{
		this.TIME_UNIT_SEC = new Double(0.1);
		this.STATS_BASE_NAME = new String(
				"TestCounters"
		);
		this.counter = new OperationCounter(
				STATS_BASE_NAME
		);
	}

	public void assertStatValueEqual(StatsResult statsResult, String name, Double expectedValue, Long tolerancePercent)
	{
		StatsUnitTestsHelpers.assertStatValueEqual("stat" + name, this.getStatValue(statsResult, name), expectedValue, tolerancePercent);
	}

	public void assertStatValueEqual(StatsResult statsResult, String name, Double value)
	{
		this.assertStatValueEqual(statsResult, name, value, new Long(10));
	}

	public Double getStatValue(StatsResult statsResult, String statName)
	{
		return statsResult.samples.get(
				STATS_BASE_NAME + "::" + statName
		);
	}

	@Test
	public void shouldHandleZeroRequests() throws InterruptedException
	{
		Thread.sleep(
				new Long(Math.round(1000 * this.TIME_UNIT_SEC))
		);
		StatsResult statsResult = counter.getStats();
		this.assertStatValueEqual(statsResult, "total", new Double(0));
		this.assertStatValueEqual(statsResult, "diff", new Double(0));
	}

	@Test
	public void shouldHandleOneRequest() throws InterruptedException
	{
		Thread.sleep(
				new Long(Math.round(1000 * this.TIME_UNIT_SEC))
		);
		counter.increase();
		Thread.sleep(
				new Long(Math.round(1000 * this.TIME_UNIT_SEC))
		);
		StatsResult statsResult = counter.getStats();
		this.assertStatValueEqual(statsResult, "total", new Double(1));
		this.assertStatValueEqual(statsResult, "diff", new Double(1) / (2 * this.TIME_UNIT_SEC));
	}

	@Test
	public void shouldHandleTwoRequests() throws InterruptedException
	{
		counter.increase(new Long(5));
		Thread.sleep(
				new Long(Math.round(1000 * this.TIME_UNIT_SEC))
		);
		counter.increase(new Long(10));
		Thread.sleep(
				new Long(Math.round(1000 * this.TIME_UNIT_SEC))
		);
		StatsResult statsResult = counter.getStats();
		this.assertStatValueEqual(statsResult, "total", new Double(15));
		this.assertStatValueEqual(statsResult, "diff", new Double(15) / (2 * this.TIME_UNIT_SEC));
	}

	@Test
	public void shouldHandleDoubleCollection() throws InterruptedException
	{
		counter.increase(new Long(5));
		Thread.sleep(
				new Long(Math.round(1000 * this.TIME_UNIT_SEC))
		);
		StatsResult statsResult = counter.getStats();
		this.assertStatValueEqual(statsResult, "total", new Double(5));
		this.assertStatValueEqual(statsResult, "diff", new Double(5) / this.TIME_UNIT_SEC);
		counter.increase(new Long(10));
		Thread.sleep(
				new Long(Math.round(1000 * this.TIME_UNIT_SEC))
		);
		statsResult = counter.getStats();
		this.assertStatValueEqual(statsResult, "total", new Double(15));
		this.assertStatValueEqual(statsResult, "diff", new Double(10) / (this.TIME_UNIT_SEC));
	}

	Double TIME_UNIT_SEC;
	String STATS_BASE_NAME;
	OperationCounter counter;
	static final Logger logger = LogManager.getLogger();

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Okta\Resource;

/**
 * Implementation of the Okta Apps resource, access via $okta->app
 *
 * http://developer.okta.com/docs/api/resources/apps.html
 */
class App extends Base
{
    /**
     * Adds a new application to your Okta organization.
     *
     * @param  string $name       Application name
     * @param  string $label      Application label
     * @param  string $signOnMode Application sign on mode
     * @param  array  $settings   Associative array of application settings
     * @param  bool   $activate   If true, executes activation lifecycle
     *                            operation when creating the application
     *
     * @return object             Application object
     */
    public function add($name, $label, $signOnMode, array $settings = null, $activate = null)
    {
        $request = $this->request->post('apps');

        $request->data([
            'name'       => $name,
            'label'      => $label,
            'signOnMode' => $signOnMode,
        ]);

        if (isset($settings)) $request->data(['settings' => ['app' => $settings]]);
        if (isset($activate)) $request->query(['activate' => $activate]);

        return $request->send();
    }

    /**
     * Fetches an application from your Okta organization by id.
     *
     * @param  string $aid Application ID
     *
     * @return object      Application object
     */
    public function get($aid)
    {
        $request = $this->request->get('apps/' . $aid);

        return $request->send();
    }

    /**
     * Enumerates apps added to your organization with pagination. A subset of
     * apps can be returned that match a supported filter expression or query.
     *
     * @param  array $query Array of query parameters/values
     *
     * @return array        Array of Application objects
     */
    public function listApps(array $query = null)
    {
        $request = $this->request->get('apps');

        if (isset($query)) $request->query($query);

        return $request->send();
    }

    /**
     * Updates an application in your organization.
     *
     * @param  string $aid ID of application to update
     * @param  array  $app Associative array of updated application data
     *
     * @return object      Application object
     */
    public function update($aid, array $app)
    {
        $request = $this->request->put('apps/' . $aid);

        $request->data($app);

        return $request->send();
    }

    /**
     * Removes an inactive application. Applications must be deactivated before
     * they can be deleted.
     *
     * @param  string $aid ID of application to delete
     *
     * @return object      An empty JSON object {}
     */
    public function delete($aid)
    {
        $request = $this->request->delete('apps/' . $aid);

        return $request->send();
    }

    /**
     * Activates an inactive application.
     *
     * @param  string $aid ID of application to activate
     *
     * @return object      An empty JSON object {}
     */
    public function activate($aid)
    {
        $request = $this->request->post('apps/' . $aid . '/lifecycle/activate');

        return $request->send();
    }

    /**
     * Deactivates an inactive application.
     *
     * @param  string $aid ID of application to deactivate
     *
     * @return object      An empty JSON object {}
     */
    public function deactivate($aid)
    {
        $request = $this->request->post('apps/' . $aid . '/lifecycle/deactivate');

        return $request->send();
    }

    /**
     * Assigns an user to an application.
     *
     * @param  string $aid     Unique key of Application
     * @param  array  $appuser Array of user credentials and (optional) profile
     *                         for the app
     *
     * @return object          Application User object
     */
    public function assignUser($aid, array $appuser)
    {
        $request = $this->request->post('apps/' . $aid . '/users');

        $request->data($appuser);

        return $request->send();
    }

    /**
     * Fetches a specific user assignment for application by ID.
     *
     * @param  string $aid Unique key of Application
     * @param  string $uid Unique key of assigned User
     *
     * @return object      Application User
     */
    public function getUser($aid, $uid)
    {
        $request = $this->request->get('apps/' . $aid . '/users/' . $uid);

        return $request->send();
    }

    /**
     * Enumerates all assigned application users for an application.
     *
     * @param  string $aid   Unique key of Application
     * @param  int    $limit Specifies the number of results for a page
     * @param  string $after Specifies the pagination cursor for the next page
     *                       of assignments
     *
     * @return array        Array of Application Users
     */
    public function listUsers($aid, $limit = null, $after = null)
    {
        $request = $this->request->get('apps/' . $aid . '/users');

        if (isset($limit)) $request->query(['limit' => $limit]);
        if (isset($after)) $request->query(['after' => $after]);

        return $request->send();
    }

    /**
     * Updates a user's credentials and/or profile for an assigned application
     *
     * @param  string $aid     Unique key of Application
     * @param  string $uid     Unique key of assigned User
     * @param  array  $appuser Array of user credentials and (optional) profile
     *                         for the app
     *
     * @return object          Application User
     */
    public function updateUser($aid, $uid, array $appuser)
    {
        $request = $this->request->post('apps/' . $aid . '/users/' . $uid);

        $request->data($appuser);

        return $request->send();
    }

    /**
     * Removes an assignment for a user from an application.
     *
     * This is a destructive operation and the user's app profile will not be
     * recoverable. If the app is enabled for provisioning and configured to
     * deactivate users, the user will also be deactivated in the target
     * application.
     *
     * @param  string $aid Unique key of Application
     * @param  string $uid Unique key of assigned User
     *
     * @return object      An empty object
     */
    public function removeUser($aid, $uid)
    {
        $request = $this->request->delete('apps/' . $aid . '/users/' . $uid);

        return $request->send();
    }

    /**
     * Assigns a group to an application
     *
     * @param  string $aid      Unique key of Application
     * @param  string $gid      Unique key of a valid Group
     * @param  array  $appgroup App group
     *
     * @return object           The assigned Application Group
     */
    public function assignGroup($aid, $gid, array $appgroup)
    {
        $request = $this->request->put('apps/' . $aid . '/groups/' . $gid);

        $request->data($appgroup);

        return $request->send();
    }

    /**
     * Fetches an application group assignment
     *
     * @param  string $aid Unique key of Application
     * @param  string $gid Unique key of a valid Group
     *
     * @return object      Application Group
     */
    public function getGroup($aid, $gid)
    {
        $request = $this->request->get('apps/' . $aid . '/groups/' . $gid);

        return $request->send();
    }

    /**
     * Enumerates group assignments for an application.
     *
     * @param  string $aid Unique key of Application
     *
     * @return array       Array of Application Groups
     */
    public function listGroups($aid)
    {
        $request = $this->request->get('apps/' . $aid . '/groups');

        return $request->send();
    }

    /**
     * Removes a group assignment from an application.
     *
     * @param  string $aid Unique key of Application
     * @param  string $gid Unique key of a valid Group
     *
     * @return object      An empty JSON object {}
     */
    public function removeGroup($aid, $gid)
    {
        $request = $this->request->delete('apps/' . $aid . '/groups/' . $gid);

        return $request->send();
    }

    /**
     * Generates a new X.509 certificate for an application key credential
     *
     * @param  string $aid           Unique key of Application
     * @param  int    $validityYears Expiry of the Application Key Credential
     *
     * @return object                The generated Application Key Credential
     */
    public function generateKey($aid, $validityYears)
    {
        $request = $this->request->post('apps/' . $aid . '/credentials/keys/generate');

        $request->query(['validityYears' => $validityYears]);

        return $request->send();
    }

    /**
     * Enumerates key credentials for an application
     *
     * @param  string $aid Unique key of Application
     *
     * @return array       Array of Application Key Credentials
     */
    public function listKeys($aid)
    {
        $request = $this->request->get('apps/' . $aid . '/credentials/keys');

        return $request->send();
    }

    /**
     * Gets a specific application key credential by kid
     *
     * @param  string $aid Unique key of Application
     * @param  string $kid Unique key of Application Key Credential
     *
     * @return object      Application Key Credential
     */
    public function getKey($aid, $kid)
    {
        $request = $this->request->get('apps/' . $aid . '/credentials/keys/' . $kid);

        return $request->send();
    }

    /**
     * Preview SAML metadata based on a specific key credential for an
     * application
     *
     * @param  string $aid Unique key of Application
     * @param  string $kid Unique key of Application Key Credential
     *
     * @return string      SAML metadata in XML
     */
    public function getSaml($aid, $kid)
    {
        $request = $this->request->get('apps/' . $aid . '/sso/saml/metadata');

        $request->query(['kid' => $kid]);

        return $request->send();
    }
}


text:
package com.oracle.ptsdemo.healthcare.business.datasync.load;

import com.oracle.ptsdemo.healthcare.ws.HealthCare;

/**
 */
public class DataLoadHealthCareLoad {

    static org.apache.log4j.Logger logger =
        org.apache.log4j.Logger.getLogger(DataLoadHealthCareLoad.class);

    /**
     */
    public DataLoadHealthCareLoad() {
        super();
        if (logger.isDebugEnabled()) {
            logger.debug(this.getClass().getName() + " : constructor");
        }
    }

    /**
     * @param prescriptionId
     * @return
     */
    public String loadPrescriptionLocal(String prescriptionId){
        if (logger.isDebugEnabled()) {
            logger.debug(this.getClass().getName() + ".loadPrescription(String prescriptionId)");
        }

        HealthCare healthCareClient = new HealthCare();
        String orderId = healthCareClient.loadPrescription(prescriptionId);
      //  logger.info("orderId " + orderId);
        return orderId;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using GTA;
using GTA.Native;
using NativeUI;
using Font = GTA.Font;

namespace NOOSE
{
    public delegate void EmptyArgs();

    public class MissionPassedScreen
    {
        public event EmptyArgs OnContinueHit;
        public string Title { get; set; }

        private List<Tuple<string, string, TickboxState>> _items = new List<Tuple<string, string, TickboxState>>();
        private int _completionRate;
        private Medal _medal;

        public bool Visible { get; set; }

        public MissionPassedScreen(string title, int completionRate, Medal medal)
        {
            Title = title;
            _completionRate = completionRate;
            _medal = medal;

            Visible = false;
        }

        public void AddItem(string label, string status, TickboxState state)
        {
            _items.Add(new Tuple<string, string, TickboxState>(label, status, state));
        }

        public void Show()
        {
            Visible = true;
        }

        public void Draw()
        {
            if (!Visible) return;

            SizeF res = UIMenu.GetScreenResolutionMantainRatio();
            int middle = Convert.ToInt32(res.Width/2);

            new Sprite("mpentry", "mp_modenotselected_gradient", new Point(0, 10), new Size(Convert.ToInt32(res.Width), 450 + (_items.Count*40)),
                0f, Color.FromArgb(200, 255, 255, 255)).Draw();

            new UIResText("mission passed", new Point(middle, 100), 2.5f, Color.FromArgb(255, 199, 168, 87), Font.Pricedown, UIResText.Alignment.Centered).Draw();

            new UIResText(Title, new Point(middle, 230), 0.5f, Color.White, Font.ChaletLondon, UIResText.Alignment.Centered).Draw();

            new UIResRectangle(new Point(middle - 300, 290), new Size(600, 2), Color.White).Draw();

            for (int i = 0; i < _items.Count; i++)
            {
                new UIResText(_items[i].Item1, new Point(middle - 230, 300 + (40*i)), 0.35f, Color.White, Font.ChaletLondon, UIResText.Alignment.Left).Draw();
                new UIResText(_items[i].Item2, new Point(_items[i].Item3 == TickboxState.None ? middle + 265 : middle + 230, 300 + (40*i)), 0.35f, Color.White, Font.ChaletLondon, UIResText.Alignment.Right).Draw();
                if (_items[i].Item3 == TickboxState.None) continue;
                string spriteName = "shop_box_blank";
                switch (_items[i].Item3)
                {
                    case TickboxState.Tick:
                        spriteName = "shop_box_tick";
                        break;
                    case TickboxState.Cross:
                        spriteName = "shop_box_cross";
                        break;
                }
                new Sprite("commonmenu", spriteName, new Point(middle + 230, 290 + (40*i)), new Size(48, 48)).Draw();
            }
            new UIResRectangle(new Point(middle - 300, 300 + (40 * _items.Count)), new Size(600, 2), Color.White).Draw();

            new UIResText("Completion", new Point(middle - 150, 320 + (40 * _items.Count)), 0.4f).Draw();
            new UIResText(_completionRate + "%", new Point(middle + 150, 320 + (40 * _items.Count)), 0.4f, Color.White, Font.ChaletLondon, UIResText.Alignment.Right).Draw();

            string medalSprite = "bronzemedal";
            switch (_medal)
            {
                case Medal.Silver:
                    medalSprite = "silvermedal";
                    break;
                case Medal.Gold:
                    medalSprite = "goldmedal";
                    break;
            }

            new Sprite("mpmissionend", medalSprite, new Point(middle + 150, 320 + (40 * _items.Count)), new Size(32, 32)).Draw();

            var scaleform = new Scaleform(0);
            scaleform.Load("instructional_buttons");
            scaleform.CallFunction("CLEAR_ALL");
            scaleform.CallFunction("TOGGLE_MOUSE_BUTTONS", 0);
            scaleform.CallFunction("CREATE_CONTAINER");

            scaleform.CallFunction("SET_DATA_SLOT", 0, Function.Call<string>(Hash._0x0499D7B09FC9B407, 2, (int)Control.FrontendAccept, 0), "Continue");
            scaleform.CallFunction("DRAW_INSTRUCTIONAL_BUTTONS", -1);
            scaleform.Render2D();
            if (Game.IsControlJustPressed(0, Control.FrontendAccept))
            {
                Game.PlaySound("SELECT", "HUD_FRONTEND_DEFAULT_SOUNDSET");
                ContinueHit();
            }
        }

        public enum Medal
        {
            Bronze,
            Silver,
            Gold
        }

        public enum TickboxState
        {
            None,
            Empty,
            Tick,
            Cross,
        }

        protected virtual void ContinueHit()
        {
            OnContinueHit?.Invoke();
        }
    }
}


text:
package mesosphere.marathon.api

import java.io.{ IOException, InputStream, OutputStream }
import java.net._
import java.security.cert.X509Certificate
import javax.inject.Named
import javax.net.ssl._
import javax.servlet._
import javax.servlet.http.{ HttpServletRequest, HttpServletResponse }

import akka.actor.ActorRef
import com.google.inject.Inject
import mesosphere.chaos.http.HttpConf
import mesosphere.marathon.io.IO
import mesosphere.marathon.{ LeaderProxyConf, ModuleNames }
import org.apache.http.HttpStatus
import org.slf4j.LoggerFactory

import scala.annotation.tailrec
import scala.collection.JavaConverters._
import scala.util.Try
import scala.util.control.NonFatal

/**
  * Info about leadership.
  */
trait LeaderInfo {
  /** Query whether we are elected as the current leader. This should be cheap. */
  def elected: Boolean

  /**
    * Subscribe to leadership change events.
    *
    * The given actorRef will initally get the current state via the appropriate
    * [[mesosphere.marathon.event.LocalLeadershipEvent]] message and will
    * be informed of changes after that.
    */
  def subscribe(self: ActorRef)
  /** Unsubscribe to any leadership change events to this actor ref. */
  def unsubscribe(self: ActorRef)

  /**
    * Query the host/port of the current leader if any. This might involve network round trips
    * and should be called sparingly.
    *
    * @return `Some(`host:port`)`, e.g. my.local.domain:8080 or `None` if
    *        the leader is currently unknown
    */
  def currentLeaderHostPort(): Option[String]
}

/**
  * Servlet filter that proxies requests to the leader if we are not the leader.
  */
class LeaderProxyFilter @Inject() (httpConf: HttpConf,
                                   leaderInfo: LeaderInfo,
                                   @Named(ModuleNames.HOST_PORT) myHostPort: String,
                                   forwarder: RequestForwarder) extends Filter {
  //scalastyle:off null

  import LeaderProxyFilter._

  def init(filterConfig: FilterConfig): Unit = {}

  private[this] val scheme = if (httpConf.disableHttp()) "https" else "http"

  private[this] def buildUrl(leaderData: String, request: HttpServletRequest): URL = {
    buildUrl(leaderData, request.getRequestURI, Option(request.getQueryString))
  }

  private[this] def buildUrl(
    leaderData: String,
    requestURI: String = "",
    queryStringOpt: Option[String] = None): URL =
    {
      queryStringOpt match {
        case Some(queryString) => new URL(s"$scheme://$leaderData$requestURI?$queryString")
        case None              => new URL(s"$scheme://$leaderData$requestURI")
      }
    }

  //TODO: fix style issue and enable this scalastyle check
  //scalastyle:off cyclomatic.complexity method.length
  @tailrec
  final def doFilter(rawRequest: ServletRequest,
                     rawResponse: ServletResponse,
                     chain: FilterChain) {

    def waitForConsistentLeadership(response: HttpServletResponse): Boolean = {
      //scalastyle:off magic.number
      var retries = 10
      //scalastyle:on

      do {
        val weAreLeader = leaderInfo.elected
        val currentLeaderData = leaderInfo.currentLeaderHostPort()

        if (weAreLeader || currentLeaderData.exists(_ != myHostPort)) {
          log.info("Leadership info is consistent again!")
          //scalastyle:off return
          return true
          //scalastyle:on
        }

        if (retries >= 0) {
          log.info(s"Waiting for consistent leadership state. Are we leader?: $weAreLeader, leader: $currentLeaderData")
          sleep()
        }
        else {
          log.error(
            s"inconsistent leadership state, refusing request for ourselves at $myHostPort. " +
              s"Are we leader?: $weAreLeader, leader: $currentLeaderData")
        }

        retries -= 1
      } while (retries >= 0)

      false
    }

    (rawRequest, rawResponse) match {
      case (request: HttpServletRequest, response: HttpServletResponse) =>
        lazy val leaderDataOpt = leaderInfo.currentLeaderHostPort()

        if (leaderInfo.elected) {
          response.addHeader(LeaderProxyFilter.HEADER_MARATHON_LEADER, buildUrl(myHostPort).toString)
          chain.doFilter(request, response)
        }
        else if (leaderDataOpt.forall(_ == myHostPort)) { // either not leader or ourselves
          log.info(
            s"Do not proxy to myself. Waiting for consistent leadership state. " +
              s"Are we leader?: false, leader: $leaderDataOpt")
          if (waitForConsistentLeadership(response)) {
            doFilter(rawRequest, rawResponse, chain)
          }
          else {
            response.sendError(HttpStatus.SC_SERVICE_UNAVAILABLE, ERROR_STATUS_NO_CURRENT_LEADER)
          }
        }
        else {
          try {
            val url: URL = buildUrl(leaderDataOpt.get, request)
            forwarder.forward(url, request, response)
          }
          catch {
            case NonFatal(e) =>
              throw new RuntimeException("while proxying", e)
          }
        }
      case _ =>
        throw new IllegalArgumentException(s"expected http request/response but got $rawRequest/$rawResponse")
    }
  }

  protected def sleep(): Unit = {
    //scalastyle:off magic.number
    Thread.sleep(250)
    //scalastyle:on
  }

  def destroy() {
    //NO-OP
  }
}

object LeaderProxyFilter {
  private val log = LoggerFactory.getLogger(getClass.getName)

  val HEADER_MARATHON_LEADER: String = "X-Marathon-Leader"
  val ERROR_STATUS_NO_CURRENT_LEADER: String = "Could not determine the current leader"
}

/**
  * Forwards a HttpServletRequest to an URL.
  */
trait RequestForwarder {
  def forward(url: URL, request: HttpServletRequest, response: HttpServletResponse): Unit
}

class JavaUrlConnectionRequestForwarder @Inject() (
  @Named(JavaUrlConnectionRequestForwarder.NAMED_LEADER_PROXY_SSL_CONTEXT) sslContext: SSLContext,
  leaderProxyConf: LeaderProxyConf,
  @Named(ModuleNames.HOST_PORT) myHostPort: String)
    extends RequestForwarder {

  import JavaUrlConnectionRequestForwarder._

  private[this] val viaValue: String = s"1.1 $myHostPort"

  private lazy val ignoreHostnameVerifier = new javax.net.ssl.HostnameVerifier {
    override def verify(hostname: String, sslSession: SSLSession): Boolean = true
  }

  override def forward(url: URL, request: HttpServletRequest, response: HttpServletResponse): Unit = {

    def hasProxyLoop: Boolean = {
      val viaOpt = Option(request.getHeaders(HEADER_VIA)).map(_.asScala.toVector)
      viaOpt.exists(_.contains(viaValue))
    }

    def createAndConfigureConnection(url: URL): HttpURLConnection = {
      val connection = url.openConnection() match {
        case httpsConnection: HttpsURLConnection =>
          httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory)

          if (leaderProxyConf.leaderProxySSLIgnoreHostname()) {
            httpsConnection.setHostnameVerifier(ignoreHostnameVerifier)
          }

          httpsConnection
        case httpConnection: HttpURLConnection =>
          httpConnection
        case connection: URLConnection =>
          throw new scala.RuntimeException(s"unexpected connection type: ${connection.getClass}")
      }

      connection.setConnectTimeout(leaderProxyConf.leaderProxyConnectionTimeout())
      connection.setReadTimeout(leaderProxyConf.leaderProxyReadTimeout())
      connection.setInstanceFollowRedirects(false)

      connection
    }

    def copyRequestHeadersToConnection(leaderConnection: HttpURLConnection, request: HttpServletRequest): Unit = {
      // getHeaderNames() and getHeaders() are known to return null, see:
      //http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getHeaders(java.lang.String)
      val names = Option(request.getHeaderNames).map(_.asScala).getOrElse(Nil)
      for {
        name <- names
        // Reverse proxies commonly filter these headers: connection, host.
        //
        // The connection header is removed since it may make sense to persist the connection
        // for further requests even if this single client will stop using it.
        //
        // The host header is used to choose the correct virtual host and should be set to the hostname
        // of the URL for HTTP 1.1. Thus we do not preserve it, even though Marathon does not care.
        if !name.equalsIgnoreCase("host") && !name.equalsIgnoreCase("connection")
        headerValues <- Option(request.getHeaders(name))
        headerValue <- headerValues.asScala
      } {
        log.debug(s"addRequestProperty $name: $headerValue")
        leaderConnection.addRequestProperty(name, headerValue)
      }

      leaderConnection.addRequestProperty(HEADER_VIA, viaValue)
      val forwardedFor = Seq(
        Option(request.getHeader(HEADER_FORWARDED_FOR)),
        Option(request.getRemoteAddr)
      ).flatten.mkString(",")
      leaderConnection.addRequestProperty(HEADER_FORWARDED_FOR, forwardedFor)
    }

    def copyRequestBodyToConnection(leaderConnection: HttpURLConnection, request: HttpServletRequest): Unit = {
      request.getMethod match {
        case "GET" | "HEAD" | "DELETE" =>
          leaderConnection.setDoOutput(false)
        case _ =>
          leaderConnection.setDoOutput(true)

          IO.using(request.getInputStream) { requestInput =>
            IO.using(leaderConnection.getOutputStream) { proxyOutputStream =>
              copy(request.getInputStream, proxyOutputStream)
            }
          }
      }
    }

    def copyRequestToConnection(leaderConnection: HttpURLConnection, request: HttpServletRequest): Unit = {
      leaderConnection.setRequestMethod(request.getMethod)
      copyRequestHeadersToConnection(leaderConnection, request)
      copyRequestBodyToConnection(leaderConnection, request)
    }

    def copyConnectionResponse(leaderConnection: HttpURLConnection, response: HttpServletResponse): Unit = {
      val status = leaderConnection.getResponseCode
      response.setStatus(status)

      val fields = leaderConnection.getHeaderFields
      // getHeaderNames() and getHeaders() are known to return null
      if (fields != null) {
        for ((name, values) <- fields.asScala) {
          if (name != null && values != null) {
            for (value <- values.asScala) {
              response.addHeader(name, value)
            }
          }
        }
      }
      response.addHeader(HEADER_VIA, viaValue)

      IO.using(response.getOutputStream) { output =>
        try {
          IO.using(leaderConnection.getInputStream) { connectionInput => copy(connectionInput, output) }
        }
        catch {
          case e: IOException =>
            log.debug("got exception response, this is maybe an error code", e)
            IO.using(leaderConnection.getErrorStream) { connectionError => copy(connectionError, output) }
        }
      }
    }

    log.info(s"Proxying request to ${request.getMethod} $url from $myHostPort")

    try {
      if (hasProxyLoop) {
        log.error("Prevent proxy cycle, rejecting request")
        response.sendError(HttpStatus.SC_BAD_GATEWAY, ERROR_STATUS_LOOP)
      }
      else {
        val leaderConnection: HttpURLConnection = createAndConfigureConnection(url)
        try {
          copyRequestToConnection(leaderConnection, request)
          copyConnectionResponse(leaderConnection, response)
        }
        catch {
          case connException: ConnectException =>
            response.sendError(HttpStatus.SC_BAD_GATEWAY, ERROR_STATUS_CONNECTION_REFUSED)
        }
        finally {
          Try(leaderConnection.getInputStream.close())
          Try(leaderConnection.getErrorStream.close())
        }
      }
    }
    finally {
      Try(request.getInputStream.close())
      Try(response.getOutputStream.close())
    }

  }

  def copy(nullableIn: InputStream, nullableOut: OutputStream): Unit = {
    try {
      for {
        in <- Option(nullableIn)
        out <- Option(nullableOut)
      } IO.transfer(in, out, close = false)
    }
    catch {
      case e: UnknownServiceException =>
        log.warn("unexpected unknown service exception", e)
    }
  }
}

object JavaUrlConnectionRequestForwarder {
  private val log = LoggerFactory.getLogger(getClass)

  /** Header for proxy loop detection. Simply "Via" is ignored by the URL connection.*/
  val HEADER_VIA: String = "X-Marathon-Via"
  val ERROR_STATUS_LOOP: String = "Detected proxying loop."
  val ERROR_STATUS_CONNECTION_REFUSED: String = "Connection to leader refused."

  val HEADER_FORWARDED_FOR: String = "X-Forwarded-For"
  final val NAMED_LEADER_PROXY_SSL_CONTEXT = "JavaUrlConnectionRequestForwarder.SSLContext"
}


text:
package com.epi.utils;

import com.epi.search.BinarySearchTreePrototypeTemplate;
import com.epi.tree.BinaryTreePrototypeTemplate;

import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class JsonUniversalObjectWriter {
    public interface CustomJsonAdapter {
        public void write(JsonObjectBuilder b);
    }

    private interface Handler {
        void handle(JsonObjectBuilder builder, String name, Object o);

        void handle(JsonArrayBuilder builder, Object o);
    }

    private static final Map<Class, Handler> dispatch = new HashMap<Class, Handler>();

    static {
        dispatch.put(Integer.class, new Handler() {
            @Override
            public void handle(JsonObjectBuilder builder, String name, Object o) {
                builder.add(name, (Integer) o);
            }

            @Override
            public void handle(JsonArrayBuilder builder, Object o) {
                builder.add((Integer) o);
            }
        });
        dispatch.put(String.class, new Handler() {
            @Override
            public void handle(JsonObjectBuilder builder, String name, Object o) {
                builder.add(name, (String) o);
            }

            @Override
            public void handle(JsonArrayBuilder builder, Object o) {
                builder.add((String) o);
            }
        });
        dispatch.put(Boolean.class, new Handler() {
            @Override
            public void handle(JsonObjectBuilder builder, String name, Object o) {
                builder.add(name, (Boolean) o);
            }

            @Override
            public void handle(JsonArrayBuilder builder, Object o) {
                builder.add((Boolean) o);
            }
        });
        dispatch.put(Double.class, new Handler() {
            @Override
            public void handle(JsonObjectBuilder builder, String name, Object o) {
                builder.add(name, (Double) o);
            }

            @Override
            public void handle(JsonArrayBuilder builder, Object o) {
                builder.add((Double) o);
            }
        });
        dispatch.put(Long.class, new Handler() {
            @Override
            public void handle(JsonObjectBuilder builder, String name, Object o) {
                builder.add(name, (Long) o);
            }

            @Override
            public void handle(JsonArrayBuilder builder, Object o) {
                builder.add((Long) o);
            }
        });
        dispatch.put(Short.class, new Handler() {
            @Override
            public void handle(JsonObjectBuilder builder, String name, Object o) {
                builder.add(name, (Short) o);
            }

            @Override
            public void handle(JsonArrayBuilder builder, Object o) {
                builder.add((Short) o);
            }
        });
    }

    public static void handle(JsonObjectBuilder builder, String name, Object o) {
        if (o == null) {
            builder.addNull(name);
            return;
        }
        if (o instanceof List<?>) {
            handleList(builder, name, (List<?>) o);
            return;
        }
        if (o instanceof Set<?>) {
            handleSet(builder, name, (Set<?>) o);
            return;
        }
        if (o instanceof BinaryTreePrototypeTemplate.BinaryTreeNode<?>) {
            handle(builder, name, ((BinaryTreePrototypeTemplate.BinaryTreeNode<?>) o)); //.toList());
            return;
        }
        if (o instanceof BinarySearchTreePrototypeTemplate.BSTNode<?>) {
            handle(builder, name, ((BinarySearchTreePrototypeTemplate.BSTNode<?>) o)); //.toList());
            return;
        }
        if (o instanceof CustomJsonAdapter) {
            JsonObjectBuilder tmp = Json.createObjectBuilder();
            ((CustomJsonAdapter) o).write(tmp);
            builder.add(name, tmp);
            return;
        }
        Handler h = dispatch.get(o.getClass());
        if (h == null)
            builder.add(name, o.toString());
        else
            h.handle(builder, name, o);
    }

    public static void handle(JsonArrayBuilder builder, Object o) {
        if (o == null) {
            builder.addNull();
            return;
        }
        if (o instanceof List<?>) {
            handleList(builder, (List<?>) o);
            return;
        }
        if (o instanceof Set<?>) {
            handleSet(builder, (Set<?>) o);
            return;
        }
        if (o instanceof BinaryTreePrototypeTemplate.BinaryTreeNode<?>) {
            handle(builder, ((BinaryTreePrototypeTemplate.BinaryTreeNode<?>) o)); //.toList());
            return;
        }
        if (o instanceof BinarySearchTreePrototypeTemplate.BSTNode<?>) {
            handle(builder, ((BinarySearchTreePrototypeTemplate.BSTNode<?>) o)); //.toList());
            return;
        }
        if (o instanceof CustomJsonAdapter) {
            JsonObjectBuilder tmp = Json.createObjectBuilder();
            ((CustomJsonAdapter) o).write(tmp);
            builder.add(tmp);
            return;
        }
        Handler h = dispatch.get(o.getClass());
        if (h == null)
            builder.add(o.toString());
        else
            h.handle(builder, o);
    }

    private static <T> void handleList(JsonObjectBuilder builder, String name, List<T> l) {
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
        for (T elem : l)
            handle(arrayBuilder, elem);
        builder.add(name, arrayBuilder);
    }

    private static <T> void handleList(JsonArrayBuilder builder, List<T> l) {
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
        for (T elem : l)
            handle(arrayBuilder, elem);
        builder.add(arrayBuilder);
    }

    private static <T> void handleSet(JsonObjectBuilder builder, String name, Set<T> s) {
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
        for (T elem : s)
            handle(arrayBuilder, elem);
        builder.add(name, arrayBuilder);
    }

    private static <T> void handleSet(JsonArrayBuilder builder, Set<T> s) {
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
        for (T elem : s)
            handle(arrayBuilder, elem);
        builder.add(arrayBuilder);
    }

    public static void main(String[] args) {
        JsonObjectBuilder b = Json.createObjectBuilder();
        //Tests
        b.add("test", 0);
        System.out.println(b.build().toString());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/emptyInfo"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_marginTop="100dp"
    android:layout_height="wrap_content"
    android:fontFamily="sans-serif"
    android:lineSpacingExtra="16sp"
    android:layout_gravity="center"
    android:padding="20dp"
    android:text="@string/text_empty_group_items"
    android:textColor="@color/text_grey"
    android:textSize="18sp"
    android:visibility="gone"
    tools:showIn="@layout/fragment_group_items" />


text:
<?php

namespace phpDocumentor\Plugin\Core\Transformer\Writer;

use phpDocumentor\Descriptor\DescriptorAbstract;
use phpDocumentor\Descriptor\FileDescriptor;
use phpDocumentor\Descriptor\Interfaces\ProjectInterface;
use phpDocumentor\Transformer\Transformation;
use phpDocumentor\Application;

/**
 * Statistics transformation writer; generates statistic report as XML.
 *
 * Generated XML structure:
 * ```
 *  <?xml version="1.0"?>
 *  <phpdoc-stats version="2.4.0">
 *    <stat date="2014-06-02T19:26:15+02:00">
 *      <counters>
 *        <deprecated>100</deprecated>
 *        <errors>377</errors>
 *        <markers>2</markers>
 *      </counters>
 *    </stat>
 *  </phpdoc-stats>
 * ```
 *
 * @author Siad Ardroumli <siad.ardroumli@gmail.com>
 */
class Statistics extends Checkstyle
{
    /**
     * This method generates the checkstyle.xml report
     *
     * @param ProjectInterface $project        Document containing the structure.
     * @param Transformation    $transformation Transformation to execute.
     *
     * @return void
     */
    public function transform(ProjectInterface $project, Transformation $transformation)
    {
        $artifact = $this->getDestinationPath($transformation);

        $now = new \DateTime('now');
        $date = $now->format(DATE_ATOM);

        $document = new \DOMDocument();
        $document->formatOutput = true;
        $document->preserveWhiteSpace = false;

        if (is_file($artifact)) {
            $document->load($artifact);
        } else {
            $document = $this->appendPhpdocStatsElement($document);
        }

        $document = $this->appendStatElement($document, $project, $date);

        $this->saveCheckstyleReport($artifact, $document);
    }

    /**
     * Append phpdoc-stats element to the document.
     *
     * @param \DOMDocument $document
     *
     * @return \DOMDocument
     */
    protected function appendPhpdocStatsElement(\DOMDocument $document)
    {
        $stats = $document->createElement('phpdoc-stats');
        $stats->setAttribute('version', Application::$VERSION);
        $document->appendChild($stats);

        return $document;
    }

    /**
     * Appends a stat fragment.
     *
     * @param \DOMDocument $document
     * @param ProjectInterface $project
     * @param string $date
     *
     * @return \DOMDocument
     */
    protected function appendStatElement(\DOMDocument $document, ProjectInterface $project, $date)
    {
        $stat = $document->createDocumentFragment();
        $stat->appendXML(
<<<STAT
<stat date="$date">
    <counters>
        <files>{$this->getFilesCounter($project)}</files>
        <deprecated>{$this->getDeprecatedCounter($project)}</deprecated>
        <errors>{$this->getErrorCounter($project)}</errors>
        <markers>{$this->getMarkerCounter($project)}</markers>
    </counters>
</stat>
STAT
        );
        $document->documentElement->appendChild($stat);

        return $document;
    }

    /**
     * Get number of files.
     *
     * @param ProjectInterface $project
     *
     * @return int
     */
    protected function getFilesCounter(ProjectInterface $project)
    {
        return $project->getFiles()->count();
    }

    /**
     * Get number of deprecated elements.
     *
     * @param ProjectInterface $project
     *
     * @return int
     */
    protected function getDeprecatedCounter(ProjectInterface $project)
    {
        $deprecatedCounter = 0;

        /** @var DescriptorAbstract $element */
        foreach ($project->getIndexes()->get('elements') as $element) {
            if ($element->isDeprecated()) {
                $deprecatedCounter += 1;
            }
        }

        return $deprecatedCounter;
    }

    /**
     * Get number of errors.
     *
     * @param ProjectInterface $project
     *
     * @return int
     */
    protected function getErrorCounter(ProjectInterface $project)
    {
        $errorCounter = 0;

        /* @var FileDescriptor $fileDescriptor */
        foreach ($project->getFiles()->getAll() as $fileDescriptor) {
            $errorCounter += count($fileDescriptor->getAllErrors()->getAll());
        }

        return $errorCounter;
    }

    /**
     * Get number of markers.
     *
     * @param ProjectInterface $project
     *
     * @return int
     */
    protected function getMarkerCounter(ProjectInterface $project)
    {
        $markerCounter = 0;

        /* @var $fileDescriptor FileDescriptor */
        foreach ($project->getFiles()->getAll() as $fileDescriptor) {
            $markerCounter += $fileDescriptor->getMarkers()->count();
        }

        return $markerCounter;
    }
}


text:
package com.itjw.grails.birt;
import org.apache.log4j.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.RenderOption;

public class BirtEngineFactory {

    private static Logger log = Logger.getLogger(BirtEngineFactory.class);

    private static IReportEngineFactory factory;
    private static EngineConfig engineConfig;
    private static IReportEngine birtEngine;

    public static synchronized void init(EngineConfig config) {
        if (birtEngine == null) {
            try {
                engineConfig = config;
                Platform.startup(config);
                factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
                birtEngine = factory.createReportEngine(engineConfig);
            } catch (BirtException e) {
                log.error("BIRT Platform Startup threw an exception:" +
                        e.getMessage() +
                        " from " +
                        e.getPluginId() +
                        ", reporting will be disabled!");
            }
        }
    }

    public static synchronized IReportEngine getEngine() {
        return birtEngine;
    }

    public static synchronized void destroy() {
        if (birtEngine != null) birtEngine.destroy();
        Platform.shutdown();
        engineConfig=null;
        factory = null;
        birtEngine = null;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    public IRenderOption createRenderOption() {
        return new RenderOption();
    }
}


text:
/*
 * Sample code to drive the leds on the beaglebone.
 *
 * Understanding the initialization flow was done
 * by studying the TI StartWare gpioLEDBlink.c example.
 *
 * Missing from this example is the PIN muxing we need to
 * better understand this.
 */

/**
 * Mapped registers for CM_PER All taken from the Sitara TRM
 *
 */
#define CM_PER_REGS            (0x44E00000)
#define CM_PER_L4LS_CLKSTCTRL  (CM_PER_REGS + 0)    //This register enables the domain power state transition.
#define CM_PER_GPIO1_CLKCTRL   (CM_PER_REGS + 0xac) //This register manages the GPIO1 clocks.

#define CM_PER_GPIO1_CLKCTRL_OPTFCLKEN_GPIO_1_GDBCLK_SHIFT (0x12)
#define CM_PER_GPIO1_CLKCTRL_OPTFCLKEN_GPIO_1_GDBCLK_FLK_EN (0x1 << CM_PER_GPIO1_CLKCTRL_OPTFCLKEN_GPIO_1_GDBCLK_SHIFT)

#define CM_PER_L4LS_CLKSTCTRL_CLKACTIVITY_GPIO_1_GDBCLK (0x80000)

#define GPIO_CTRL 0x130           //GPIO Module control register
#define GPIO_OE 0x134             //GPIO Output enable
#define GPIO_CLEARDATAOUT 0x190	  //CLEAR DATA (Writing 1 clears data)
#define GPIO_SETDATAOUT 0x194     //SET data (writing 1 sets bits)
#define GPIO_DATAIN 0x138         //DATAIN reading from this returns the current pin value
#define GPIO_SYSCONFIG 0x10	      //The GPIO_SYSCONFIG register controls the various parameters of the L4 interconnect.
#define GPIO_SYSSTATUS 0x114	  //The GPIO_SYSSTATUS register provides the reset status information about the GPIO module.

#define GPIO_CTRL_DISABLEMODULE 0x1
#define GPIO_SYSSTATUS_RESETDONE 0x1
#define GPIO_SYSCONFIG_SOFTRESET 0x2

#define GPIO1_BASE 0x4804C000

#define REG(x)(*((volatile unsigned int *)(x)))

/**
 * Enable the functional clocks in the GPIO1 domain.
 * Before this core is called you can not write to the memory
 * mapped registers of the GPIO1 framework
 */
void enableGPIO1Clocks(){
	// SW_WKUP : SW_WKUP: Start a software forced wake-up transition on GPIO1 the domain.
	REG(CM_PER_GPIO1_CLKCTRL) =  (REG(CM_PER_L4LS_CLKSTCTRL) & ~ 0x3) | 0x2;
	// Wait for the transition to be complete
	while( (REG(CM_PER_GPIO1_CLKCTRL) & 0x2) != 0x2);

	// Enable optional function clock
	 REG(CM_PER_GPIO1_CLKCTRL) |= CM_PER_GPIO1_CLKCTRL_OPTFCLKEN_GPIO_1_GDBCLK_FLK_EN;
	 //Wait for functional clock to be enabled
	 while ( (REG(CM_PER_GPIO1_CLKCTRL) & CM_PER_GPIO1_CLKCTRL_OPTFCLKEN_GPIO_1_GDBCLK_FLK_EN) !=  CM_PER_GPIO1_CLKCTRL_OPTFCLKEN_GPIO_1_GDBCLK_FLK_EN);

	 //Next wait for the module status (IDLEST CM_PER_GPIO1_CLKCTRL bit 17 and 16) to be functional.
	 while (REG(CM_PER_GPIO1_CLKCTRL) & 0x30000 );

	 // Also wait for the GPIO1_GDBCLK to be active
	 while( (REG(CM_PER_L4LS_CLKSTCTRL)  &  CM_PER_L4LS_CLKSTCTRL_CLKACTIVITY_GPIO_1_GDBCLK) != CM_PER_L4LS_CLKSTCTRL_CLKACTIVITY_GPIO_1_GDBCLK );
}

/**
 * Enable and reset the GPIO1 block
 */
void enableGPIO1Block(){
	/* Enable GPIO Module by clearing GPIO_CTRL_DISABLEMODULE*/
	REG(GPIO1_BASE + GPIO_CTRL) &= ~(GPIO_CTRL_DISABLEMODULE);

	/* Do a soft reset and wait for the rest to be complete */
	REG(GPIO1_BASE + GPIO_SYSCONFIG) |= GPIO_SYSCONFIG_SOFTRESET;
	while ( (REG(GPIO1_BASE + GPIO_SYSSTATUS) & GPIO_SYSSTATUS_RESETDONE) !=  GPIO_SYSSTATUS_RESETDONE);
}

/**
 * Simple delay function
 */
void delay(volatile int count){
	while(count--);
}

void main(void) {
	int x;

	//Clocks
	enableGPIO1Clocks();

	//Pin muxing
	//@TODO understand pin muxing. In our setup it just "happened" to work

	/* Enable output on pin 21 to 24 the leds on the beaglebone */
	REG(GPIO1_BASE + GPIO_OE) &= ~(0xf << 21);

	/* Display a binary lock */
	for (x = 0 ; x < 16 ; x ++){
		REG(GPIO1_BASE + GPIO_CLEARDATAOUT) = 0xffffff;
		REG(GPIO1_BASE + GPIO_SETDATAOUT) =  (x << 21);
		delay(0x3fffff);
	}
}


text:
layout: other
title: New Zealand Rental Cars, Car Hire, Car Rentals New Zealand
keywords: New Zealand Rental Cars, Car Hire, Car Rentals NZ
description: New Zealand Rental Cars Guide including car hire, car rentals in New Zealand.

slug: banner-tekapo
banner-descr-main: Lake Tekapo

redirect_from: /new-zealand-rental-cars.html
permalink: /rental-cars.html

breadcrumbs: True
name: Rental Cars
region: rental-cars

side-nav:
- campervans.html: New Zealand Campervans
- tours.html: New Zealand Tours

sidebar-ad:
- Heading to Australia?
- https://www.airportrentals.com.au/
- apr.jpg
- Car Rental Australia
- Compare multiple suppliers in Australia with the vehicle and car rental experts at AirportRentals.com.au.

---

# New Zealand Rental Cars

New Zealand offers a huge variety of rental cars options. Travelling by car is one the best ways to explore the beauty of New Zealand because it allows you the freedom of traveling to the most remote places in the country. We recommend booking your hire car many months in advance (especially between November and March) as finding available cars for hire in New Zealand at the last minute can be difficult. Christchurch and Auckland airport have a large number of rental car companies nearby - many of them offer free airport transfers.


text:
require 'bundler'
require 'faraday'

module Op
  module Foodtruck
    class Client
      attr_accessor :oauth_token, :api_tld, :api_version
      FOODTRUCK_URL = Op::Foodtruck::FOODTRUCKS[:api_tld]
      API_VERSION = "v1"

      def initialize(oauth_token, api_tld=nil, api_version=nil)
        api_tld          ||= FOODTRUCK_URL
        api_version      ||= api_version
        self.oauth_token   = oauth_token
      end

      def get(path, options={})
        json_to_hashie_mash(query_trucks_api(generic_url(path, options)))
      end

      def post(path, options={})
        json_to_hashie_mash(post_trucks_api(generic_url(path), options))
      end

      def get_trucks(options = {})
        result = json_to_hashie_mash(query_trucks_api(truck_search_url(options)))

        construct_pagination(result.trucks, options[:page] || 1, 20, result.total_entries)
      end

      def get_cities
        json_to_hashie_mash(query_trucks_api(cities_url))
      end

      def get_truck(id)
        json_to_hashie_mash(query_trucks_api(truck_url(id)))
      end

    private

      def generic_url(path, options)
        [base_url, path, oauth_token_to_param, parameterize(options)].join("")
      end

      def truck_url(id)
        [base_url, "trucks/#{id}", oauth_token_to_param].join("")
      end

      def json_to_hashie_mash(json)
        Hashie::Mash.new(JSON.parse(json))
      end

      def cities_url
        [base_url, "cities/", oauth_token_to_param].join("")
      end

      # options:
      # city_id=1
      # tags=bbq,asian
      # s=searchterm
      # city_name=dc
      # page=1
      def truck_search_url(options = {})
        [base_url, "trucks/", oauth_token_to_param, parameterize(options)].join("")
      end

      def base_url
        [FOODTRUCK_URL, "api/", API_VERSION, "/"].join("")
      end

      def oauth_token_to_param
        "?access_token=#{self.oauth_token}"
      end

      def parameterize(params)
        return if params.empty?
        "&#{URI.escape(params.collect{|k,v| "#{k}=#{v}"}.join('&'))}"
      end

      def construct_pagination(results, current_page, per_page, total_entries)
        WillPaginate::Collection.create(current_page, per_page, total_entries) do |pager|
          pager.replace results
        end
      end

      def post_trucks_api(url, options)
        result = Faraday.post(url, options)
        if result.status == 201
          "success"
        else
          raise "Query with URL: #{url} resulted in a #{result.status} error"
        end
      end

      def query_trucks_api url
        result = Faraday.get(url)
        if result.status == 200
          result.body
        else
          raise "Query with URL: #{url} resulted in a #{result.status} error"
        end
      end

    end

  end

end


text:
layout: post
status: publish
published: true
title: Two VS.NET Taskbar Icons
author:
  display_name: Tomas Restrepo
  login: tomasr
  email: tomas@winterdom.com
  url: http://winterdom.com/
author_login: tomasr
author_email: tomas@winterdom.com
author_url: http://winterdom.com/
wordpress_id: 680
wordpress_url: http://winterdom.com/2004/03/twovsnettaskbaricons
date: '2004-03-14 10:40:48 +0000'
date_gmt: '2004-03-14 10:40:48 +0000'
categories:
- ".NET"
tags: []
comments: []
---

OK, this one seems to be happening all too often: While working on VS.NET 2003, I suddently end up with two different icons on the taskbar for a single instance of VS.NET. Curiously enough, one of them gets piled up with other Windows Explorer windows, not with the rest of VS.NET windows on the taskbar.

But wait, it gets worse: After a while, VS.NET gets "stuck", meaning I can't minimize the VS.NET window (I can maximize it and restore it, and work on it without problems, though). After digging a while, it seems something inside VS.NET gets screwed and one of the windows seems to end up with the Desktop Window as its parent, which comepletely screws up the shell, aparently.

Dunno if BizTalk has anything to do with it, but it seems to happen far more often while working on BizTalk projects than other kinds of projects, although opening up XML or XSD files inside VS.NET seems to trigger it sometimes, also...


text:
<?php
namespace Finance;

use Finance\Model\FinanceDAO;

class Module
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
               'Finance\Model\FinanceDAO' => function($sm) {
                    $objectManager = $sm->get('Doctrine\ORM\EntityManager');
                    return new FinanceDAO($objectManager);
                },
            ),
        );
    }
}


text:
<?php

namespace Aedart\Model\Contracts\Strings;

/**
 *
Wildcard Aware

 *
 * Component is aware of a string "wildcard" value, which can
 * also be specified.
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Model\Contracts\Strings
 */
interface WildcardAware
{
    /**
     * Set wildcard
     *
     * @param string|null $identifier Wildcard identifier
     *
     * @return self
     */
    public function setWildcard(?string $identifier);

    /**
     * Get wildcard
     *
     * If no "wildcard" value has been set, this method will
     * set and return a default "wildcard" value,
     * if any such value is available
     *
     * @see getDefaultWildcard()
     *
     * @return string|null wildcard or null if no wildcard has been set
     */
    public function getWildcard() : ?string ;

    /**
     * Check if "wildcard" has been set
     *
     * @return bool True if "wildcard" has been set, false if not
     */
    public function hasWildcard() : bool;

    /**
     * Get a default "wildcard" value, if any is available
     *
     * @return string|null Default "wildcard" value or null if no default value is available
     */
    public function getDefaultWildcard() : ?string;
}


text:
// Copyright (c) MOSA Project. Licensed under the New BSD License.

using Xunit;

namespace Mosa.Test.Collection.x86.xUnit
{
	public class StringFixture : X86TestFixture
	{
		[Fact]
		public void CheckLength()
		{
			Assert.Equal(StringTests.CheckLength(), Run<int>("Mosa.Test.Collection.StringTests.CheckLength"));
		}

		[Fact]
		public void CheckFirstCharacter()
		{
			Assert.Equal(StringTests.CheckFirstCharacter(), Run<char>("Mosa.Test.Collection.StringTests.CheckFirstCharacter"));
		}

		[Fact]
		public void CheckLastCharacter()
		{
			Assert.Equal(StringTests.CheckLastCharacter(), Run<char>("Mosa.Test.Collection.StringTests.CheckLastCharacter"));
		}

		[Fact]
		public void LastCharacterMustMatch()
		{
			Assert.Equal(StringTests.LastCharacterMustMatch(), Run<char>("Mosa.Test.Collection.StringTests.LastCharacterMustMatch"));
		}
	}
}


text:
package com.adaptris.core.jms;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.jms.JMSException;
import javax.jms.Message;
import org.junit.Test;
import com.adaptris.core.metadata.NoOpMetadataFilter;
import com.adaptris.core.metadata.RegexMetadataFilter;

/**
 * @author mwarman
 */
public class LongMetadataConverterTest extends ConvertingMetadataConverterCase {

  private static final long VALUE = 10L;
  private static final String STRING_VALUE = String.valueOf(VALUE);

  @Override
  MetadataConverter createConverter() {
    return new LongMetadataConverter();
  }

  @Override
  String getStringValue() {
    return STRING_VALUE;
  }

  @Override
  void assertValue(Message jmsMsg) throws JMSException {
    assertEquals(VALUE, jmsMsg.getLongProperty(HEADER));
  }

  @Test
  public void testConstruct() throws Exception {
    LongMetadataConverter mc = new LongMetadataConverter();
    assertTrue(mc.getMetadataFilter() instanceof NoOpMetadataFilter);
    mc = new LongMetadataConverter(new RegexMetadataFilter());
    assertTrue(mc.getMetadataFilter() instanceof RegexMetadataFilter);
  }

}


text:
package gov.nih.nci.ess.safetyreporting.advquery.common;

import java.rmi.RemoteException;

/**
 * This class is autogenerated, DO NOT EDIT.
 *
 * This interface represents the API which is accessable on the grid service from the client.
 *
 * @created by Introduce Toolkit version 1.3
 *
 */
public interface SafetyReportAdvancedQueryI {

  public org.oasis.wsrf.lifetime.DestroyResponse destroy(org.oasis.wsrf.lifetime.Destroy params) throws RemoteException ;

  public org.oasis.wsrf.lifetime.SetTerminationTimeResponse setTerminationTime(org.oasis.wsrf.lifetime.SetTerminationTime params) throws RemoteException ;

  public void getSafetyReportSummaryData() throws RemoteException ;

}


text:
haxe-linguistics was written by Martijn de Boer.

Special thanks go to;
- [Natural project for Node](https://github.com/NaturalNode/natural) for inspiration.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=7" />
<title>单页面应用框架(Single Page Application Framework)</title>
<link href="/static/css/bootstrap.min.css" rel="stylesheet" type="text/css" media="screen">
<link href="/static/css/bootstrap-responsive.min.css" rel="stylesheet" type="text/css" >
<link href="/static/css/spa.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="/static/theme/default/style.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="/static/css/spa-default.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="/static/css/icons.css" rel="stylesheet" type="text/css" media="screen"/>

管理员

消息(3)

安全退出

主题1

主题2

主题3

主题4

主题5

			主菜单

Powered by ©ruoyousi 2013

数据加载中,请稍等...

啊,出错了!

服务出错了!

会话超时,请重新登录.

HTTP 503 错误.

重新载入

关闭标签页

关闭其它标签页

关闭全部标签页

超过最多同时打开页面数:{0}


text:
package com.github.mrvilkaman.testsutils;

import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * Created by Zahar on 04.04.16.
 */
@SuppressWarnings("ALL")
@RunWith(MockitoJUnitRunner.class)
public abstract class BaseTestCase {
	@Rule
	public MockitoRule mockitoRule = MockitoJUnit.rule();

	@Before
	public void init(){

	}
}


text:
A simple tool that monitors a web host and power cycles an energenie power strip if the check fails.

## Usage

```
Usage of ./powersurge:
  -host="http://www.google.com": Address of site to use to test connectivity
  -interval="5m": Interval in which to run the test. Example: 10s, 5m, 1h
  -socket=1: Number of the socket the router is connected to
  -strip="10.1.1.213": IP address of the power strip
```

## Requirements

A power strip with LAN connection made by [EnerGenie](http://www.energenie.com/products.aspx?sg=210).

## How to build

1. Set a proper `GOPATH`
2. Run `go build`
3. There is no step 3.


text:
if (Handlebars) {
  Handlebars.registerHelper('voted', function (votersIds) {
    var userId;

    userId = Meteor.userId();

    return votersIds && votersIds.indexOf(userId) >= 0 ? 'voted' : '';
  });
}


text:
<?php

declare(strict_types=1);

namespace Doctrine\ORM\Cache\Logging;

use Doctrine\ORM\Cache\CollectionCacheKey;
use Doctrine\ORM\Cache\EntityCacheKey;
use Doctrine\ORM\Cache\QueryCacheKey;

/**
 * Interface for logging.
 */
interface CacheLogger
{
    /**
     * Log an entity put into second level cache.
     *
     * @param string         $regionName The name of the cache region.
     * @param EntityCacheKey $key        The cache key of the entity.
     */
    public function entityCachePut($regionName, EntityCacheKey $key);

    /**
     * Log an entity get from second level cache resulted in a hit.
     *
     * @param string         $regionName The name of the cache region.
     * @param EntityCacheKey $key        The cache key of the entity.
     */
    public function entityCacheHit($regionName, EntityCacheKey $key);

    /**
     * Log an entity get from second level cache resulted in a miss.
     *
     * @param string         $regionName The name of the cache region.
     * @param EntityCacheKey $key        The cache key of the entity.
     */
    public function entityCacheMiss($regionName, EntityCacheKey $key);

    /**
     * Log an entity put into second level cache.
     *
     * @param string             $regionName The name of the cache region.
     * @param CollectionCacheKey $key        The cache key of the collection.
     */
    public function collectionCachePut($regionName, CollectionCacheKey $key);

    /**
     * Log an entity get from second level cache resulted in a hit.
     *
     * @param string             $regionName The name of the cache region.
     * @param CollectionCacheKey $key        The cache key of the collection.
     */
    public function collectionCacheHit($regionName, CollectionCacheKey $key);

    /**
     * Log an entity get from second level cache resulted in a miss.
     *
     * @param string             $regionName The name of the cache region.
     * @param CollectionCacheKey $key        The cache key of the collection.
     */
    public function collectionCacheMiss($regionName, CollectionCacheKey $key);

    /**
     * Log a query put into the query cache.
     *
     * @param string        $regionName The name of the cache region.
     * @param QueryCacheKey $key        The cache key of the query.
     */
    public function queryCachePut($regionName, QueryCacheKey $key);

    /**
     * Log a query get from the query cache resulted in a hit.
     *
     * @param string        $regionName The name of the cache region.
     * @param QueryCacheKey $key        The cache key of the query.
     */
    public function queryCacheHit($regionName, QueryCacheKey $key);

    /**
     * Log a query get from the query cache resulted in a miss.
     *
     * @param string        $regionName The name of the cache region.
     * @param QueryCacheKey $key        The cache key of the query.
     */
    public function queryCacheMiss($regionName, QueryCacheKey $key);
}


text:
/**
 * Created by bob on 9/5/15.
 */
var gulp = require('gulp');
var sass = require('gulp-sass');
var csso = require('gulp-csso');
var rename = require('gulp-rename');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var uglifySaveLicense = require('uglify-save-license');
var template = require('gulp-template');

module.exports = function(options) {
  gulp.task('styles', ['clean'], function() {
    return gulp.src('src/ng-promise-loader.scss')
      .pipe(sass())
      .pipe(gulp.dest('dist/css'))
      .pipe(csso())
      .pipe(rename('ng-promise-loader.min.css'))
      .pipe(gulp.dest('dist/css'));
  });

  gulp.task('scripts',['clean'], function() {
    return gulp.src('src/ng-promise-loader.js')
      .pipe(ngAnnotate())
      .pipe(template({version: options.pkg.version}))
      .pipe(gulp.dest('dist/js'))
      .pipe(uglify({preserveComments: uglifySaveLicense}))
      .pipe(rename('ng-promise-loader.min.js'))
      .pipe(gulp.dest('dist/js'));
  });

  gulp.task('build', ['styles', 'scripts']);
};


text:
<!--

********************************************************************************

WARNING:

    DO NOT EDIT "rethinkdb/README.md"

    IT IS AUTO-GENERATED

    (from the other files in "rethinkdb/" combined with a set of templates)

********************************************************************************

-->

# Supported tags and respective `Dockerfile` links

-	[`2.0.4`, `2.0` (*jessie/2.0.4/Dockerfile*)](https://github.com/rethinkdb/rethinkdb-dockerfiles/blob/da98484fc73485fe7780546903d01dcbcd931673/jessie/2.0.4/Dockerfile)
-	[`2.1.6`, `2.1` (*jessie/2.1.6/Dockerfile*)](https://github.com/rethinkdb/rethinkdb-dockerfiles/blob/da98484fc73485fe7780546903d01dcbcd931673/jessie/2.1.6/Dockerfile)
-	[`2.2.6`, `2.2` (*jessie/2.2.6/Dockerfile*)](https://github.com/rethinkdb/rethinkdb-dockerfiles/blob/da98484fc73485fe7780546903d01dcbcd931673/jessie/2.2.6/Dockerfile)
-	[`2.3.4` (*jessie/2.3.4/Dockerfile*)](https://github.com/rethinkdb/rethinkdb-dockerfiles/blob/da98484fc73485fe7780546903d01dcbcd931673/jessie/2.3.4/Dockerfile)
-	[`2.3.5`, `2.3`, `2`, `latest` (*jessie/2.3.5/Dockerfile*)](https://github.com/rethinkdb/rethinkdb-dockerfiles/blob/da98484fc73485fe7780546903d01dcbcd931673/jessie/2.3.5/Dockerfile)

# Quick reference

-	**Where to get help**:
	[the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://blog.docker.com/2016/11/introducing-docker-community-directory-docker-community-slack/), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)

-	**Where to file issues**:
	[https://github.com/rethinkdb/rethinkdb-dockerfiles/issues](https://github.com/rethinkdb/rethinkdb-dockerfiles/issues)

-	**Maintained by**:
	[RethinkDB](https://github.com/rethinkdb/rethinkdb-dockerfiles)

-	**Published image artifact details**:
	[repo-info repo's `repos/rethinkdb/` directory](https://github.com/docker-library/repo-info/blob/master/repos/rethinkdb) ([history](https://github.com/docker-library/repo-info/commits/master/repos/rethinkdb))
	(image metadata, transfer size, etc)

-	**Image updates**:
	[official-images PRs with label `library/rethinkdb`](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Frethinkdb)
	[official-images repo's `library/rethinkdb` file](https://github.com/docker-library/official-images/blob/master/library/rethinkdb) ([history](https://github.com/docker-library/official-images/commits/master/library/rethinkdb))

-	**Source of this description**:
	[docs repo's `rethinkdb/` directory](https://github.com/docker-library/docs/tree/master/rethinkdb) ([history](https://github.com/docker-library/docs/commits/master/rethinkdb))

-	**Supported Docker versions**:
	[the latest release](https://github.com/docker/docker/releases/latest) (down to 1.6 on a best-effort basis)

# What is RethinkDB?

RethinkDB is an open-source, distributed database built to store JSON documents and effortlessly scale to multiple machines. It's easy to set up and learn and features a simple but powerful query language that supports table joins, groupings, aggregations, and functions.

![logo](https://raw.githubusercontent.com/docker-library/docs/af9f91fe186f3ea3afee511d0a53b50088fdc381/rethinkdb/logo.png)

# How to use this image

## Start an instance with data mounted in the working directory

The default CMD of the image is `rethinkdb --bind all`, so the RethinkDB daemon will bind to all network interfaces available to the container (by default, RethinkDB only accepts connections from `localhost`).

```bash
docker run --name some-rethink -v "$PWD:/data" -d rethinkdb
```

## Connect the instance to an application

```bash
docker run --name some-app --link some-rethink:rdb -d application-that-uses-rdb
```

## Connecting to the web admin interface on the same host

```bash
$BROWSER "http://$(docker inspect --format \
  '{{ .NetworkSettings.IPAddress }}' some-rethink):8080"
```

# Connecting to the web admin interface on a remote / virtual host via SSH

Where `remote` is an alias for the remote user@hostname:

```bash
# start port forwarding
ssh -fNTL localhost:8080:$(ssh remote "docker inspect --format \
  '{{ .NetworkSettings.IPAddress }}' some-rethink"):8080 remote

# open interface in browser
xdg-open http://localhost:8080

# stop port forwarding
kill $(lsof -t -i @localhost:8080 -sTCP:listen)
```

## Configuration

See the [official docs](http://www.rethinkdb.com/docs/) for infomation on using and configuring a RethinkDB cluster.

# License

View [license information](http://www.gnu.org/licenses/agpl-3.0.html) for the software contained in this image.


text:
<!doctype html>

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

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link href="../../images/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="css/index.css" rel="stylesheet" type="text/css">

      BootStrap Website

Home

About

Resume

          Projects

Project 1

Project 2

Project 3

Project 4

Project 5

Anime

T.V Shows

Contact


text:
layout: post
title: Welcome to Free Indian Land
tags: commentary life
photo_base_url: https://storage.googleapis.com/mookerji-public-gh-erpqqbqxpseyysfhbtt6phabkvutcme/mookerji.github.io/photos/2014-10-26-alcatraz
---

# {{ page.title }}

 26 October 2014 - Alcatraz, San Francisco, CA

"With Wind"

"Trace", with Ed Snowden in the foreground

Indian Land graffiti, from the 1971 Occupation.

Audio tour in the prison gallery.

Denise at the kitchen.

Graffiti.

The Golden Gate, just behind locked doors.

No day is complete without calisthenics, nor a visit to
the AWS brick-and-mortar store on the edge of the Tenderloin.


text:
cmd="psql template1 --tuples-only --command \"select count(*) from pg_database where datname = 'waterpolo-w';\""

db_exists=`eval $cmd`

if [ $db_exists -eq 0 ] ; then
   cmd="createdb waterpolo-w;"
   eval $cmd
fi

psql waterpolo-w -f schema/ncaa.sql

cat csv/games_*.csv >> /tmp/games.csv
psql waterpolo-w -f loaders/games.sql
rm /tmp/games.csv


text:
static void
draw();

static void
resetBall();

// game state functions

static void
menuTitle();

static void
gameSetup();

static void
gameMain();

static void
gamePause();

static void
menuWin1();

static void
menuWin2();

typedef void (*tick_func_t)();

static tick_func_t gameTick{ &menuTitle };
static bool twoPlayers{ false };

Ball ball;
Player1 player1;
Player2 player2;

void tick()
{
	gameTick();
}

bool twoPlayerGame()
{
	return twoPlayers;
}

void
draw()
{
	// cool border around the screen
	arduboy.drawRect(0, 0, WIDTH, HEIGHT, WHITE);
	// dotted line in the middle
	for (uint8_t i{ 2 }; i < HEIGHT; i += 8)
	{
		arduboy.drawFastVLine(WIDTH / 2, i, 4, WHITE);
	}
	// scores
	arduboy.setCursor(WIDTH/2 - 12, 2);
	arduboy.print(player1.getScore());
	arduboy.setCursor(WIDTH/2 + 3, 2);
	arduboy.print(player2.getScore());
	// objects
	ball.draw();
	player1.draw();
	player2.draw();
}

void
resetBall()
{
	ball.setPosition(Vector{ WIDTH / 2, HEIGHT / 2 });
	ball.setVelocity(Vector{ 1, 1 });
}

void
menuTitle()
{
	arduboy.setCursor(0, 0);
	arduboy.print(F("players:"));
	arduboy.setCursor(96, 0);
	arduboy.print(twoPlayers ? 2 : 1);
	if (arduboy.justPressed(LEFT_BUTTON) ||
		arduboy.justPressed(RIGHT_BUTTON))
	{
		twoPlayers = !twoPlayers;
	}
	if (arduboy.justPressed(A_BUTTON))
	{
		gameTick = &gameSetup;
	}
}

void
gameSetup()
{
	arduboy.initRandomSeed();
	resetBall();
	// set both paddles in the center of the vertical space
	player1.setPosition(Vector{ 9, 24 });
	player1.resetScore();
	player2.setPosition(Vector{ WIDTH - PADDLE_WIDTH - 9, 24 });
	player2.resetScore();
	draw();
	arduboy.display();
	delay(1000);
	gameTick = &gameMain;
}

void
gameMain()
{
	draw();
	// pause the game if needed
	if (arduboy.justPressed(LEFT_BUTTON))
	{
		gameTick = &gamePause;
		return;
	}
	ball.move();
	player1.move();
	player2.move();
	// check if player 1 scored
	if (ball.getPosition().getX() >= WIDTH - BALL_SIZE)
	{
		player1.updateScore();
		if (player1.getScore() >= SCORE_MAX)
		{
			gameTick = &menuWin1;
		}
		else
		{
			resetBall();
		}
		sound.tone(POINT_FREQ, POINT_DUR);
	}
	// check if player 2 scored
	else if (ball.getPosition().getX() < 1)
	{
		player2.updateScore();
		if (player2.getScore() >= SCORE_MAX)
		{
			gameTick = &menuWin2;
		}
		else
		{
			resetBall();
		}
		sound.tone(POINT_FREQ, POINT_DUR);
	}
}

void
gamePause()
{
	draw();
	// resume the game if needed
	if (arduboy.justPressed(LEFT_BUTTON))
	{
		gameTick = &gameMain;
	}
}

void
menuWin1()
{
	arduboy.setCursor(0, 0);
	arduboy.print(F("Player 1\nwins!\nPress A to\nrestart"));
	if (arduboy.justPressed(A_BUTTON))
	{
		gameTick = &gameSetup;
	}
}

void
menuWin2()
{
	arduboy.setCursor(0, 0);
	arduboy.print(F("Player 2\nwins!\nPress A to\nrestart"));
	if (arduboy.justPressed(A_BUTTON))
	{
		gameTick = &gameSetup;
	}
}


text:
"""Definitions for Moksha quickstart templates"""
from paste.script.templates import Template, var
from tempita import paste_script_template_renderer

class MokshaMasterTemplate(Template):
    summary = 'Moksha Master Quickstart Template'
    _template_dir = 'templates/moksha/master'
    template_renderer = staticmethod(paste_script_template_renderer)
    vars = [
            var('livewidget', 'Include an example live widget', default=False),
            var('widget_name', 'The name of the widget', default=None),
            var('stream', 'Include an example stream', default=False),
            var('stream_name', 'The name of the stream', default=None),
            var('consumer', 'Include an exmaple consumer', default=False),
            var('consumer_name', 'The name of the consumer', default=None),
            var('connector', 'Include an example connector', default=None),
            var('connector_name', 'The name of the connector', default=None),
            var('controller', 'Include an example controller', default=None),
            var('controller_name', 'The name of the controller', default=None),
    ]

    def pre(self, command, output_dir, vars):
        """Called before template is applied."""
        package_logger = vars['package']
        if package_logger == 'root':
            # Rename the app logger in the rare case a project is named 'root'
            package_logger = 'app'
        vars['package_logger'] = package_logger

        for key, value in vars.items():
            if value == 'None':
                vars[key] = None
            elif value == 'True':
                vars[key] = True
            elif value == 'False':
                vars[key] = False

class MokshaLiveWidgetTemplate(Template):
    _template_dir = 'templates/moksha/livewidget'
    template_renderer = staticmethod(paste_script_template_renderer)
    summary = 'Moksha Live Widget Quickstart Template'
    egg_plugins = ['Moksha']
    vars = [
            var('topic', 'The moksha topic to utilize',
                default='moksha.test'),
            var('livewidget', 'Include an example live widget', default=False),
            var('widget_name', 'The name of the widget', default=None),
    ]

    def pre(self, command, output_dir, vars):
        """Called before template is applied."""
        if 'widget_name' not in vars:
            vars['widget_name'] = vars['package'].title() + 'Widget'

class MokshaStreamTemplate(Template):
    summary = 'Moksha Stream Quickstart Template'
    _template_dir = 'templates/moksha/stream'
    template_renderer = staticmethod(paste_script_template_renderer)
    vars = [
            var('topic', 'The moksha topic to utilize',
                default='moksha.test'),
    ]

    def pre(self, command, output_dir, vars):
        """Called before template is applied."""
        package_logger = vars['package']
        if package_logger == 'root':
            # Rename the app logger in the rare case a project is named 'root'
            package_logger = 'app'
        vars['package_logger'] = package_logger
        vars['stream_name'] = vars['package'].title() + 'Stream'

class MokshaConsumerTemplate(Template):
    summary = 'Moksha Consumer Quickstart Template'
    _template_dir = 'templates/moksha/consumer'
    template_renderer = staticmethod(paste_script_template_renderer)
    vars = [
            var('topic', 'The moksha topic to utilize',
                default='moksha.test'),
    ]

    def pre(self, command, output_dir, vars):
        """Called before template is applied."""
        package_logger = vars['package']
        if package_logger == 'root':
            # Rename the app logger in the rare case a project is named 'root'
            package_logger = 'app'
        vars['package_logger'] = package_logger
        vars['consumer_name'] = vars['package'].title() + 'Consumer'

class MokshaConnectorTemplate(Template):
    summary = 'Moksha Connector Quickstart Template'
    _template_dir = 'templates/moksha/connector'
    template_renderer = staticmethod(paste_script_template_renderer)
    vars = []

    def pre(self, command, output_dir, vars):
        """Called before template is applied."""
        package_logger = vars['package']
        if package_logger == 'root':
            # Rename the app logger in the rare case a project is named 'root'
            package_logger = 'app'
        vars['package_logger'] = package_logger
        vars['connector_name'] = vars['package'].title() + 'Connector'

class MokshaControllerTemplate(Template):
    summary = 'Moksha Controller Quickstart Template'
    _template_dir = 'templates/moksha/controller'
    template_renderer = staticmethod(paste_script_template_renderer)
    vars = []

    def pre(self, command, output_dir, vars):
        """Called before template is applied."""
        package_logger = vars['package']
        if package_logger == 'root':
            # Rename the app logger in the rare case a project is named 'root'
            package_logger = 'app'
        vars['package_logger'] = package_logger
        vars['controller_name'] = vars['package'].title() + 'Controller'


text:
function f = imag( f )
%IMAG   Imaginary part of a SEPARABLEAPPROX.
%   IMAG(F) returns the imaginary part of a SEPARABLEAPPROX.

% Copyright 2015 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Empty check:
if ( isempty( f ) )
    return
end

f = compose( f, @imag );

end


text:
'use strict';

const assert = require('assert');
const path = require('path');
const spawn = require('child_process').spawn;
const expect = require('chai').expect;

describe('index.js', function() {
    // eslint-disable-next-line no-invalid-this
    this.timeout(8000);

    it('single jpeg with no exif', function(done) {
        let out = '';
        spawn('node', [path.join(__dirname, '../index.js'), 'test/none.jpg'], {
            cwd: path.join(__dirname, '../'),
        }).on('exit', function(code) {
            assert.strictEqual(code, 0);
            expect(out).to.match(/Number of files to check: 1/);
            expect(out).to.match(/Checking: test\/none\.jpg/);
            done();
        }).stdout.on('data', function(data) {
            out += data;
        });
    });

    it('single jpeg with exif', function(done) {
        let out = '';
        spawn('node', [path.join(__dirname, '../index.js'), 'test/exif.jpg'], {
            cwd: path.join(__dirname, '../'),
        }).on('exit', function(code) {
            assert.strictEqual(code, 1);
            expect(out).to.match(/ERROR: Exif data found for: test\/exif\.jpg/);
            done();
        }).stdout.on('data', function(data) {
            out += data;
        });
    });

    it('single heic with exif but empty', function(done) {
        let out = '';
        spawn('node', [path.join(__dirname, '../index.js'), 'test/exifempty.heic'], {
            cwd: path.join(__dirname, '../'),
        }).on('exit', function(code) {
            assert.strictEqual(code, 0);
            expect(out).to.match(/Checking: test\/exifempty\.heic/);
            done();
        }).stdout.on('data', function(data) {
            out += data;
        });
    });

    it('single webp with exif', function(done) {
        let out = '';
        spawn('node', [path.join(__dirname, '../index.js'), 'test/exif.webp'], {
            cwd: path.join(__dirname, '../'),
        }).on('exit', function(code) {
            assert.strictEqual(code, 1);
            expect(out).to.match(/ERROR: Exif data found for: test\/exif\.webp/);
            done();
        }).stdout.on('data', function(data) {
            out += data;
        });
    });

    it('single svg which cant be read', function(done) {
        let out = '';
        spawn('node', [path.join(__dirname, '../index.js'), 'test/wrong.svg'], {
            cwd: path.join(__dirname, '../'),
        }).on('exit', function(code) {
            assert.strictEqual(code, 1);
            expect(out).to.match(/Invalid image format/);
            done();
        }).stdout.on('data', function(data) {
            out += data;
        });
    });

    it('single non existing file', function(done) {
        let out = '';
        spawn('node', [path.join(__dirname, '../index.js'), 'test/404.jpg'], {
            cwd: path.join(__dirname, '../'),
        }).on('exit', function(code) {
            assert.strictEqual(code, 1);
            expect(out).to.match(/ENOENT: no such file or directory/);
            done();
        }).stdout.on('data', function(data) {
            out += data;
        });
    });

    it('multi files with exif', function(done) {
        let out = '';
        spawn('node', [path.join(__dirname, '../index.js'), 'test/none.jpg', 'test/exif.jpg', 'test/none.png'], {
            cwd: path.join(__dirname, '../'),
        }).on('exit', function(code) {
            assert.strictEqual(code, 1);
            expect(out).to.match(/Number of files to check: 3/);
            expect(out).to.match(/ERROR: Exif data found for: test\/exif\.jpg/);
            done();
        }).stdout.on('data', function(data) {
            out += data;
        });
    });

    it('multi files with no exif', function(done) {
        let out = '';
        spawn('node', [path.join(__dirname, '../index.js'), 'test/none.jpg', 'test/none.png'], {
            cwd: path.join(__dirname, '../'),
        }).on('exit', function(code) {
            assert.strictEqual(code, 0);
            expect(out).to.match(/Number of files to check: 2/);
            done();
        }).stdout.on('data', function(data) {
            out += data;
        });
    });

    it('single jpg with exif but empty', function(done) {
        let out = '';
        spawn('node', [path.join(__dirname, '../index.js'), 'test/exifempty.jpg'], {
            cwd: path.join(__dirname, '../'),
        }).on('exit', function(code) {
            assert.strictEqual(code, 0);
            expect(out).to.match(/Number of files to check: 1/);
            done();
        }).stdout.on('data', function(data) {
            out += data;
        });
    });
});


text:
$(window).load(function() { // makes sure the whole site is loaded
	$("#status").fadeOut(); // will first fade out the loading animation
	$("#preloader").delay(350).fadeOut("slow"); // will fade out the white DIV that covers the website.
})

$(document).ready(function(){

	//Detect if iOS WebApp Engaged and permit navigation without deploying Safari
	(function(a,b,c){if(c in b&&b[c]){var d,e=a.location,f=/^(a|html)$/i;a.addEventListener("click",function(a){d=a.target;while(!f.test(d.nodeName))d=d.parentNode;"href"in d&&(d.href.indexOf("http")||~d.href.indexOf(e.host))&&(a.preventDefault(),e.href=d.href)},!1)}})(document,window.navigator,"standalone")

	var owl = $(".slider-controls");
	owl.owlCarousel({
		//Basic Stuff
		singleItem:true,
		slideSpeed : 250,
		paginationSpeed : 250,
		rewindSpeed : 250,
		pagination:false,

		autoPlay : true,
	});

	// Custom Navigation Events
	$(".next-slider").click(function(){
	  owl.trigger('owl.next');
	  return false;
	});
	$(".prev-slider").click(function(){
	  owl.trigger('owl.prev');
	  return false;
	});

	var owlQuoteControls = $(".quote-slider");
	owlQuoteControls.owlCarousel({
		//Basic Stuff
		items : 4,
		itemsDesktop : [1199,4],
		itemsDesktopSmall : [980,3],
		itemsTablet: [768,3],
		itemsTabletSmall: [330,2],
		itemsMobile : [320,2],
		singleItem : false,
		itemsScaleUp : false,
		slideSpeed : 250,
		paginationSpeed : 250,
		rewindSpeed : 250,
		pagination:false,
		autoPlay : false,
		autoHeight: true,
	});

	var owlQuoteNoControls = $(".quote-slider-no-controls");
	owlQuoteNoControls.owlCarousel({
		//Basic Stuff
		singleItem:true,
		slideSpeed : 250,
		paginationSpeed : 250,
		rewindSpeed : 250,
		pagination:false,
		autoPlay : true,
		autoHeight: true,
	});

	// Custom Navigation Events
	$(".next-quote").click(function(){
	  owlQuoteControls.trigger('owl.next');
	  return false;
	});
	$(".prev-quote").click(function(){
	  owlQuoteControls.trigger('owl.prev');
	  return false;
	});

	$('.slider-two-thumbs').owlCarousel({
		singleItem:true,
	});

	$(".slider-no-controls").owlCarousel({
		//Basic Stuff
		singleItem:true,
		slideSpeed : 250,
		paginationSpeed : 250,
		rewindSpeed : 250,
		pagination:false,
		autoHeight:true,

		//Autoplay
		autoPlay : true,
		stopOnHover : true,

		//Mouse Events
		dragBeforeAnimFinish : true,
		mouseDrag : true,
		touchDrag : true,

		//Transitions
		transitionStyle : false,
	});

	/////////////////
	//Image Gallery//
	/////////////////
	$(".swipebox").swipebox({
		useCSS : true, // false will force the use of jQuery for animations
		hideBarsDelay : 3000 // 0 to always show caption and action bar
	});

	$(".swipebox-wide").swipebox({
		useCSS : true, // false will force the use of jQuery for animations
		hideBarsDelay : 3000 // 0 to always show caption and action bar
	});

	$(".portfolio-item-full-width a").colorbox({
	 	transition:"fade",
		scalePhotos:"true",
		maxWidth:"100%",
		maxHeight:"100%"
	});

	$(".portfolio-item-thumb a").colorbox({
	 	transition:"fade",
		scalePhotos:"true",
		maxWidth:"100%",
		maxHeight:"100%"
	});

});


text:
using System.Collections.Generic;
using MinesweeperPro.Mines;
using System.Linq;

namespace MinesweeperTest
{
    public class PredefinedBoard : IMineFieldBuilder
    {
        public const char CoveredEmpty = '.';
        public const char Mine = '*';
        public const char FlaggedMine = '!';
        public const char FlaggedWrong = 'x';
        public const char EmptyNoAdjacent = ' ';

        private List<string> myRows = new List<string>();

        public PredefinedBoard Row(string row)
        {
            myRows.Add(row);
            return this;
        }

        public void Grow()
        {
            var rows = myRows.Count;
            for (int i = 0; i < rows; ++i)
            {
                myRows[i] = '.' + myRows[i] + '.';
            }

            var cols = myRows[0].Length;
            var emptyRow = new string('.', cols);
            myRows.Insert(0, emptyRow);
            myRows.Add(emptyRow);
        }

        public void BuildMineField(MineField mineField)
        {
            var mines = myRows.SelectMany(row => row).Count(c => c == Mine || c == FlaggedMine);

            Desc = new MineFieldDesc(myRows.Count, myRows[0].Length, mines);

            Field = new CellState[Desc.Rows, Desc.Columns];

            for (int i = 0; i < Desc.Rows; ++i)
            {
                for (int j = 0; j < Desc.Columns; ++j)
                {
                    var state = myRows[i][j];
                    var coord = new Coord(i, j);
                    var cell = new CellState(mineField, coord);
                    Field[i, j] = cell;

                    switch (state)
                    {
                        case CoveredEmpty:
                            break;

                        case Mine:
                            cell.HasMine = true;
                            break;

                        case FlaggedMine:
                            cell.HasMine = true;
                            cell.InterfaceState = CellInterfaceState.Flagged;
                            break;

                        case FlaggedWrong:
                            cell.InterfaceState = CellInterfaceState.Flagged;
                            break;

                        case EmptyNoAdjacent:
                            cell.InterfaceState = CellInterfaceState.Opened;
                            break;

                        case '1':
                        case '2':
                        case '3':
                        case '4':
                        case '5':
                        case '6':
                        case '7':
                        case '8':
                            cell.AdjacentMines = state - '0';
                            cell.InterfaceState = CellInterfaceState.Opened;
                            break;
                    }
                }
            }

            for (int i = 0; i < Desc.Rows; ++i)
            {
                for (int j = 0; j < Desc.Columns; ++j)
                {
                    var coord = new Coord(i, j);
                    if (!Field.GetCellAt(coord).HasMine)
                        continue;

                    foreach (var adj in MineField.Adjacencies)
                    {
                        var adjPos = adj + coord;
                        var adjCell = Field.GetCellAt(adjPos);
                        if (adjCell != null && !adjCell.IsOpen)
                            adjCell.AdjacentMines++;
                    }
                }
            }
        }

        public CellState[,] Field { get; private set; }
        public MineFieldDesc Desc { get; private set; }
    }
}


text:
'use strict';

module.exports = {
  db: 'mongodb://localhost/doggerjs-test',
  facebook: {
    clientID: 'APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/facebook/callback'
  },
  twitter: {
    clientID: 'CONSUMER_KEY',
    clientSecret: 'CONSUMER_SECRET',
    callbackURL: 'http://localhost:3000/auth/twitter/callback'
  },
  google: {
    clientID: 'APP_ID',
    clientSecret: 'APP_SECRET',
    callbackURL: 'http://localhost:3000/auth/google/callback'
  },

  // Sender address like ME <me@doggerjs.com>
  emailFrom: 'SENDER EMAIL ADDRESS',
  mailer: {
    service: 'SERVICE_PROVIDER',
    auth: {
      user: 'EMAIL_ID',
      pass: 'PASSWORD'
    }
  }
};


text:
#ifndef WaveShaperProcessor_h
#define WaveShaperProcessor_h

#include "core/dom/DOMTypedArray.h"
#include "modules/webaudio/AudioNode.h"
#include "platform/audio/AudioDSPKernel.h"
#include "platform/audio/AudioDSPKernelProcessor.h"
#include "wtf/RefPtr.h"
#include "wtf/ThreadingPrimitives.h"
#include <memory>

namespace blink {

// WaveShaperProcessor is an AudioDSPKernelProcessor which uses WaveShaperDSPKernel objects to implement non-linear distortion effects.

class WaveShaperProcessor final : public AudioDSPKernelProcessor {
public:
    enum OverSampleType {
        OverSampleNone,
        OverSample2x,
        OverSample4x
    };

    WaveShaperProcessor(float sampleRate, size_t numberOfChannels);

    ~WaveShaperProcessor() override;

    std::unique_ptr<AudioDSPKernel> createKernel() override;

    void process(const AudioBus* source, AudioBus* destination, size_t framesToProcess) override;

    void setCurve(DOMFloat32Array*);
    DOMFloat32Array* curve() { return m_curve.get(); }

    void setOversample(OverSampleType);
    OverSampleType oversample() const { return m_oversample; }

private:
    // m_curve represents the non-linear shaping curve.
    CrossThreadPersistent<DOMFloat32Array> m_curve;

    OverSampleType m_oversample;
};

} // namespace blink

#endif // WaveShaperProcessor_h