text:
// Copyright (c) Jon Thysell <http://jonthysell.com>
// Licensed under the MIT License.

using System;

namespace Chordious.Core
{
    public class FullInternalNote : IComparable<FullInternalNote>, IEquatable<FullInternalNote>
    {
        public InternalNote Note { get; set; }

        public int Octave
        {
            get
            {
                return _octave;
            }
            set
            {
                if (value < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(value));
                }
                _octave = value;
            }
        }
        private int _octave;

        public FullInternalNote(InternalNote note, int octave)
        {
            Note = note;
            Octave = octave;
        }

        public FullInternalNote() : this(InternalNote.C, 4) { }

        public FullInternalNote Shift(int steps)
        {
            if (steps == 0)
            {
                return new FullInternalNote(Note, Octave);
            }

            int direction = Math.Sign(steps);

            InternalNote note = Note;
            int octave = Octave;

            for (int i = 0; i < Math.Abs(steps); i++)
            {
                int noteIndex = (int)note + direction;
                if (noteIndex < 0)
                {
                    noteIndex += 12;
                }

                note = (InternalNote)(noteIndex % 12);

                if (direction > 0 && note == InternalNote.C)
                {
                    octave++;
                }
                else if (direction < 0 && note == InternalNote.B)
                {
                    octave--;
                }
            }

            return new FullInternalNote(note, octave);
        }

        public int GetShift(FullInternalNote targetNote)
        {
            int compareTo = CompareTo(targetNote);

            if (compareTo == 0)
            {
                return 0;
            }

            FullInternalNote currentNote = Clone();

            int shiftAmount = -1 * Math.Sign(compareTo);

            int totalShift = 0;
            while (!currentNote.Equals(targetNote))
            {
                currentNote = currentNote.Shift(shiftAmount);
                totalShift += shiftAmount;
            }

            return totalShift;
        }

        public int CompareTo(FullInternalNote other)
        {
            if (other is null)
            {
                throw new ArgumentNullException(nameof(other));
            }

            if (Octave == other.Octave)
            {
                return Note.CompareTo(other.Note);
            }

            return Octave.CompareTo(other.Octave);
        }

        public bool Equals(FullInternalNote other)
        {
            if (other is null)
            {
                return false;
            }

            return Note == other.Note && Octave == other.Octave;
        }

        public FullInternalNote Clone()
        {
            return new FullInternalNote(Note, Octave);
        }

        public override string ToString()
        {
            return string.Format("{0}{1}", Note.ToString(), Octave);
        }
    }
}


text:
package com.ctrip.hermes.broker.queue;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unidal.tuple.Pair;

import com.ctrip.hermes.broker.queue.storage.FetchResult;
import com.ctrip.hermes.broker.selector.PullMessageSelectorManager;
import com.ctrip.hermes.core.bo.Offset;
import com.ctrip.hermes.core.bo.Tpg;
import com.ctrip.hermes.core.bo.Tpp;
import com.ctrip.hermes.core.lease.Lease;
import com.ctrip.hermes.core.message.TppConsumerMessageBatch;
import com.ctrip.hermes.core.meta.MetaService;
import com.ctrip.hermes.core.selector.CallbackContext;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

/**
 * @author Leo Liang(liangjinhua@gmail.com)
 *
 */
public abstract class AbstractMessageQueueCursor implements MessageQueueCursor {
	protected static final Logger log = LoggerFactory.getLogger(AbstractMessageQueueCursor.class);

	protected static final int STATE_NOT_INITED = 0;

	protected static final int STATE_INITING = 1;

	protected static final int STATE_INITED = 2;

	protected static final int STATE_INIT_ERROR = 0;

	protected static LoadingCache<Tpg, Long> m_lastPriorityTriggerTime;

	protected static LoadingCache<Tpg, Long> m_lastNonPriorityTriggerTime;

	protected static LoadingCache<Tpg, Long> m_lastResendTriggerTime;

	protected Tpg m_tpg;

	protected Tpp m_priorityTpp;

	protected Tpp m_nonPriorityTpp;

	protected Object m_priorityOffset;

	protected Object m_nonPriorityOffset;

	protected Object m_resendOffset;

	protected MetaService m_metaService;

	protected int m_groupIdInt;

	protected Lease m_lease;

	protected AtomicInteger m_state = new AtomicInteger(STATE_NOT_INITED);

	protected AtomicBoolean m_stopped = new AtomicBoolean(false);

	protected MessageQueue m_messageQueue;

	protected long m_priorityMessageFetchBySafeTriggerMinInterval;

	protected long m_nonpriorityMessageFetchBySafeTriggerMinInterval;

	protected long m_resendMessageFetchBySafeTriggerMinInterval;

	static {
		m_lastPriorityTriggerTime = CacheBuilder.newBuilder().maximumSize(5000).build(new CacheLoader<Tpg, Long>() {

			@Override
			public Long load(Tpg key) throws Exception {
				return -1L;
			}
		});
		m_lastNonPriorityTriggerTime = CacheBuilder.newBuilder().maximumSize(5000).build(new CacheLoader<Tpg, Long>() {

			@Override
			public Long load(Tpg key) throws Exception {
				return -1L;
			}
		});
		m_lastResendTriggerTime = CacheBuilder.newBuilder().maximumSize(5000).build(new CacheLoader<Tpg, Long>() {

			@Override
			public Long load(Tpg key) throws Exception {
				return -1L;
			}
		});
	}

	public AbstractMessageQueueCursor(Tpg tpg, Lease lease, MetaService metaService, MessageQueue messageQueue,
	      long priorityMsgFetchBySafeTriggerMinInterval, long nonpriorityMsgFetchBySafeTriggerMinInterval,
	      long resendMsgFetchBySafeTriggerMinInterval) {
		m_tpg = tpg;
		m_lease = lease;
		m_priorityTpp = new Tpp(tpg.getTopic(), tpg.getPartition(), true);
		m_nonPriorityTpp = new Tpp(tpg.getTopic(), tpg.getPartition(), false);
		m_metaService = metaService;
		m_groupIdInt = m_metaService.translateToIntGroupId(m_tpg.getTopic(), m_tpg.getGroupId());
		m_messageQueue = messageQueue;
		m_priorityMessageFetchBySafeTriggerMinInterval = priorityMsgFetchBySafeTriggerMinInterval;
		m_nonpriorityMessageFetchBySafeTriggerMinInterval = nonpriorityMsgFetchBySafeTriggerMinInterval;
		m_resendMessageFetchBySafeTriggerMinInterval = resendMsgFetchBySafeTriggerMinInterval;
	}

	@Override
	public void init() {
		if (m_state.compareAndSet(STATE_NOT_INITED, STATE_INITING)) {
			try {
				m_priorityOffset = loadLastPriorityOffset();
				m_nonPriorityOffset = loadLastNonPriorityOffset();
				m_resendOffset = loadLastResendOffset();
				m_state.set(STATE_INITED);
			} catch (Exception e) {
				log.error("Failed to init cursor", e);
				m_state.set(STATE_INIT_ERROR);
				throw e;
			}
		}
	}

	public Lease getLease() {
		return m_lease;
	}

	public boolean hasError() {
		return m_state.get() == STATE_INIT_ERROR;
	}

	public boolean isInited() {
		return m_state.get() == STATE_INITED;
	}

	protected abstract void doStop();

	protected abstract Object loadLastPriorityOffset();

	protected abstract Object loadLastNonPriorityOffset();

	protected abstract Object loadLastResendOffset();

	protected abstract FetchResult fetchPriorityMessages(int batchSize, String filter);

	protected abstract FetchResult fetchNonPriorityMessages(int batchSize, String filter);

	protected abstract FetchResult fetchResendMessages(int batchSize);

	@Override
	@SuppressWarnings("unchecked")
	public synchronized Pair<Offset, List<TppConsumerMessageBatch>> next(int batchSize, String filter,
	      CallbackContext callbackCtx) {
		List<TppConsumerMessageBatch> batches = doNext(batchSize, filter, callbackCtx);
		Offset offset = new Offset((long) m_priorityOffset, (long) m_nonPriorityOffset, (Pair<Date, Long>) m_resendOffset);

		return new Pair<Offset, List<TppConsumerMessageBatch>>(batches == null ? null : offset, batches);
	}

	protected List<TppConsumerMessageBatch> doNext(int batchSize, String filter, CallbackContext callbackCtx) {
		if (m_stopped.get() || m_lease.isExpired()) {
			return null;
		}

		try {
			List<TppConsumerMessageBatch> result = new LinkedList<>();
			int remainingSize = batchSize;

			long now = System.currentTimeMillis();

			if (shouldFetchPriorityMessages(callbackCtx, now)) {
				FetchResult pFetchResult = fetchPriorityMessages(batchSize, filter);
				m_lastPriorityTriggerTime.put(m_tpg, now);

				if (pFetchResult != null) {
					TppConsumerMessageBatch priorityMessageBatch = pFetchResult.getBatch();
					if (priorityMessageBatch != null && priorityMessageBatch.size() > 0) {
						result.add(priorityMessageBatch);
						remainingSize -= priorityMessageBatch.size();
						m_priorityOffset = pFetchResult.getOffset();
					}
				}
			}

			if (shouldFetchResendMessages(callbackCtx, now) && remainingSize > 0) {
				FetchResult rFetchResult = fetchResendMessages(remainingSize);
				m_lastResendTriggerTime.put(m_tpg, now);

				if (rFetchResult != null) {
					TppConsumerMessageBatch resendMessageBatch = rFetchResult.getBatch();
					if (resendMessageBatch != null && resendMessageBatch.size() > 0) {
						result.add(resendMessageBatch);
						remainingSize -= resendMessageBatch.size();
						m_resendOffset = rFetchResult.getOffset();
					}
				}
			}

			if (shouldFetchNonPriorityMessages(callbackCtx, now) && remainingSize > 0) {
				FetchResult npFetchResult = fetchNonPriorityMessages(remainingSize, filter);
				m_lastNonPriorityTriggerTime.put(m_tpg, now);

				if (npFetchResult != null) {
					TppConsumerMessageBatch nonPriorityMessageBatch = npFetchResult.getBatch();
					if (nonPriorityMessageBatch != null && nonPriorityMessageBatch.size() > 0) {
						result.add(nonPriorityMessageBatch);
						remainingSize -= nonPriorityMessageBatch.size();
						m_nonPriorityOffset = npFetchResult.getOffset();
					}
				}
			}

			return result;
		} catch (Exception e) {
			// TODO
		}

		return null;
	}

	protected boolean shouldFetchPriorityMessages(CallbackContext callbackCtx, long now) {
		return callbackCtx.getSlotMatchResults()[PullMessageSelectorManager.SLOT_PRIORITY_INDEX].isMatch()
		      || (callbackCtx.getSlotMatchResults()[PullMessageSelectorManager.SLOT_RESEND_INDEX].isMatch() && now
		            - m_lastPriorityTriggerTime.getUnchecked(m_tpg) > m_priorityMessageFetchBySafeTriggerMinInterval);
	}

	protected boolean shouldFetchNonPriorityMessages(CallbackContext callbackCtx, long now) {
		return callbackCtx.getSlotMatchResults()[PullMessageSelectorManager.SLOT_NONPRIORITY_INDEX].isMatch()
		      || (callbackCtx.getSlotMatchResults()[PullMessageSelectorManager.SLOT_RESEND_INDEX].isMatch() && now
		            - m_lastNonPriorityTriggerTime.getUnchecked(m_tpg) > m_nonpriorityMessageFetchBySafeTriggerMinInterval);
	}

	protected boolean shouldFetchResendMessages(CallbackContext callbackCtx, long now) {
		return now - m_lastResendTriggerTime.getUnchecked(m_tpg) > m_resendMessageFetchBySafeTriggerMinInterval
		      && callbackCtx.getSlotMatchResults()[PullMessageSelectorManager.SLOT_RESEND_INDEX].isMatch();
	}

	@Override
	public void stop() {
		if (m_stopped.compareAndSet(false, true)) {
			doStop();
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
<ivy-module version="2.0">
	<info organisation="org.eclipse.custom" module="core.runtime" revision="3.9.0" publication="20130326125500">
		<license name="Eclipse Public Licence v1.0" url="http://www.eclipse.org/org/documents/epl-v10.php" />
		<description homepage="http://www.eclipse.org/eclipse/" />
	</info>
	<configurations>
		<conf name="default" />
		<conf name="sources" />
	</configurations>
	<publications>
		<artifact conf="default" url="https://projectlombok.org/ivyrepo/eclipse/org.eclipse.core.runtime_3.9.0.v20130326-1255.jar" />
		<artifact type="zip" conf="sources" url="https://projectlombok.org/ivyrepo/eclipse/org.eclipse.core.runtime_3.9.0.v20130326-1255-sources.jar" />
	</publications>
</ivy-module>


text:
import random
import pickle
import os
import sys

class Markov:
    CLAUSE_ENDS = [',', '.', ';', ':']

    def __init__(self, n=3):
        self.n = n
        self.p = 0
        self.seed = None
        self.data = {}
        self.recentData = {}
        self.cln = n

    def set_cln(self, cln):
        self.cln = cln if cln is not None and cln <= self.n else self.n

    def train(self, training_data):
        prev = ()
        for token in training_data:
            token = sys.intern(token)
            for pprev in [prev[i:] for i in range(len(prev) + 1)]:
                if not pprev in self.data:
                    self.data[pprev] = [0, {}]

                if not token in self.data[pprev][1]:
                    self.data[pprev][1][token] = 0

                self.data[pprev][1][token] += 1
                self.data[pprev][0] += 1

            prev += (token,)
            if len(prev) > self.n:
                prev = prev[1:]

    def load(self, filename):
        with open(os.path.expanduser(filename), "rb") as f:
            try:
                n, self.data = pickle.load(f)

                if self.n > n:
                    print("warning: changing n value to", n)
                    self.n = n
                return True
            except:
                print("Loading data file failed!")
                return False

    def dump(self, filename):
        try:
            with open(os.path.expanduser(filename), "wb") as f:
                pickle.dump((self.n, self.data), f)
            return True
        except:
            print("Could not dump to file.")
            return False

    def reset(self, seed, prob, prev, cln):
        self.seed = seed
        self.p = prob
        self.prev = prev
        self.set_cln(cln)
        self.cleanRecentData()
        random.seed(seed)

    def __iter__(self):
        return self

    def __next__(self):
        if self.prev == () or random.random() < self.p:
            next = self._selectToken(())
        else:
            try:
                next = self._selectToken(self.prev)
            except:
                self.prev = ()
                next = self._selectToken(self.prev)

        self.prev += (next,)
        if len(self.prev) > self.n:
            self.prev = self.prev[1:]

        if next[-1] in self.CLAUSE_ENDS:
            self.prev = self.prev[-self.cln:]

        return next

    def lastStateSaturated(self):
        if self.prev not in self.recentData:
            return False
        return self.recentData[self.prev] > self.data[self.prev][0]

    def cleanRecentData(self):
        self.recentData = {}

    def _selectToken(self, state=None):
        if state is None:
            state = self.prev
        if not state in self.recentData:
            self.recentData[state] = 0
        self.recentData[state] += 1
        return self._choose(self.data[state])

    def _choose(self, freqdict):
        total, choices = freqdict
        idx = random.randrange(total)

        for token, freq in choices.items():
            if idx <= freq:
                return token

            idx -= freq


text:
using GameOfLife.Abstraction;

namespace GameOfLife.Rules
{
    public class Underpopulation : IRule
    {
        public void Apply(ICell cell)
        {
            // Any live cell with fewer than two live neighbours dies
            if (!cell.IsAlive)
            {
                return;
            }

            var countAliveNeighbourCell = 0;

            foreach (var neighbourCell in cell.NeighbourCells)
            {
                if (neighbourCell.IsAlive)
                {
                    countAliveNeighbourCell++;
                }
            }

            if (countAliveNeighbourCell < 2)
            {
                cell.Die();
            }
        }
    }
}


text:
@extends('errors.layout')

@section('title')
    Route not found.
@endsection

@section('message')
    Route not found.
@endsection


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container_all"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingTop="0dp">

    <View
        android:layout_width="fill_parent"
        android:layout_height="5dp"
        android:background="@drawable/mini_gradient_light" />

    <RelativeLayout
        android:id="@+id/container_current"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/ccl_mini_controller_icon_height"
        android:background="@color/ccl_mini_main_background">

        <View
            android:id="@+id/center"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_centerVertical="true"
            android:visibility="invisible" />

        <ImageView
            android:id="@+id/icon_view"
            android:layout_width="@dimen/ccl_mini_controller_icon_width"
            android:layout_height="@dimen/ccl_mini_controller_icon_height"
            android:layout_alignParentLeft="true"
            android:scaleType="centerCrop"
            android:src="@drawable/mini_controller_img_placeholder" />

        <ImageView
            android:id="@+id/play_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:src="@drawable/ic_mini_controller_pause" />

        <ProgressBar
            android:id="@+id/loading_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/play_pause"
            android:layout_alignLeft="@+id/play_pause"
            android:layout_alignRight="@+id/play_pause"
            android:layout_alignTop="@+id/play_pause"
            android:layout_centerVertical="true"
            android:visibility="gone" />

        <TextView
            android:id="@+id/title_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/center"
            android:layout_marginBottom="-3dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="8dp"
            android:layout_toLeftOf="@+id/play_pause"
            android:layout_toRightOf="@+id/icon_view"
            android:ellipsize="end"
            android:fontFamily="sans-serif"
            android:maxLines="1"
            android:textAppearance="@style/TextAppearance.AppCompat.Subhead" />

        <TextView
            android:id="@+id/subtitle_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/title_view"
            android:layout_alignRight="@+id/title_view"
            android:layout_below="@+id/center"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@+id/play_pause"
            android:layout_toRightOf="@+id/icon_view"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="Casting to Living Room"
            android:textAppearance="@style/TextAppearance.AppCompat.Caption" />

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="5dp"
            android:layout_alignBottom="@+id/icon_view"
            android:progressDrawable="@drawable/progress_drawable" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/container_upcoming"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/ccl_mini_controller_icon_height"
        android:background="@color/ccl_mini_upcoming_background"
        android:visibility="gone">

        <View
            android:id="@+id/center_upcoming"
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:layout_centerVertical="true"
            android:visibility="invisible" />

        <ImageView
            android:id="@+id/icon_view_upcoming"
            android:layout_width="@dimen/ccl_mini_controller_icon_width"
            android:layout_height="@dimen/ccl_mini_controller_icon_height"
            android:layout_alignParentLeft="true"
            android:scaleType="centerCrop"
            android:src="@drawable/mini_controller_img_placeholder" />

        <ImageButton
            android:id="@+id/stop_upcoming"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="14dp"
            android:background="?attr/selectableItemBackgroundBorderless"
            android:src="@drawable/ic_mini_controller_upcoming_stop" />

        <ImageButton
            android:id="@+id/play_upcoming"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="@dimen/ccl_mini_upcoming_play_margin"
            android:layout_toLeftOf="@+id/stop_upcoming"
            android:background="?attr/selectableItemBackgroundBorderless"
            android:src="@drawable/ic_mini_controller_upcoming_play" />

        <TextView
            android:id="@+id/title_view_upcoming"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/center_upcoming"
            android:layout_marginBottom="-3dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="5dp"
            android:layout_toLeftOf="@+id/play_upcoming"
            android:layout_toRightOf="@+id/icon_view_upcoming"
            android:ellipsize="end"
            android:fontFamily="sans-serif"
            android:maxLines="1"
            android:text="Tears of Steel"
            android:textAppearance="@style/TextAppearance.AppCompat.Subhead.Inverse"
            android:textColor="#FFFFFF" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/title_view_upcoming"
            android:layout_alignRight="@+id/title_view_upcoming"
            android:layout_below="@+id/center_upcoming"
            android:layout_marginTop="3dp"
            android:layout_toLeftOf="@+id/play_upcoming"
            android:layout_toRightOf="@+id/icon_view_upcoming"
            android:ellipsize="end"
            android:fontFamily="sans-serif"
            android:maxLines="1"
            android:text="@string/ccl_mini_upnext"
            android:textAppearance="@style/TextAppearance.AppCompat.Caption"
            android:textColor="@color/ccl_mini_upcoming_upnext_color"
            android:textStyle="bold" />

    </RelativeLayout>

</LinearLayout>


text:
"use strict";

const Event = require('eventemitter-co');
const cp    = require('child_process');

const defer = require('nyks/promise/defer');
const sleep = require('nyks/function/sleep');

const guid  = require('mout/random/guid');

const debug = require('debug')('omx-spawn');

const NEXT_EVENT       = guid(); //private
const EVENT_LOOP_START = guid(); //private
const EVENT_LOOP_END   = guid(); //private

class omxspawn extends Event {

  constructor() {
    super();

    this.layer = 2147483643;
    this.playlist = [];
    this.forced   = [];
    this.playlistIndex = 0;
    this.once(EVENT_LOOP_START, this._run, this);
  }

  * _run() {
    if(this.running)
      return;
    this.running  = true;

    var front;
    try{
      front = yield this._load(this._shift());
    }catch(err){
      debug(err);
      this.running  = false;
      yield sleep(500);
      return yield this._run();
    }

    var next = {ready : defer()};

    var shouldkill = false;
    var shouldJump = null;
    this.on(NEXT_EVENT, function(reject, killfront) {
       next.ready[reject]("playonce");
       shouldkill = !!killfront;
       shouldJump = reject;
    });

    var paused = true;
    do {
      front.begin();
      try{
        next = yield this._load(this._shift(), paused);
      }catch(err){
        debug(err);
        yield sleep(500);
        continue
      }

      var delay = front.duration - (Date.now() - front.startTiming) - 90;
      if(!paused)
        delay = 0;

      setTimeout(next.ready.resolve, delay);

      try {
        if(shouldJump)
          next.ready[shouldJump]("playonce");
        yield next.ready;
      } catch(err) {
        if(err == "playonce") {
          if(shouldkill)
            front.destroy();
          shouldkill = false;
          paused     = false;
        }
        next.destroy();
        continue;
      } finally {
        shouldJump = null;
      }

      paused = true;
      setTimeout(front.destroy, 1000);
      front = next;
    } while(this.running);

    this.emit(EVENT_LOOP_END);

    front.destroy();
    next.destroy();
  }

  destroy() {
    this.running = false;
    var defered = defer();
    this.on(EVENT_LOOP_END, defered.resolve);
    return defered;
  }

  playonce(file, shouldkill) {
    this.forced = [file];
    var defered = defer();
    this.once('play', defered.resolve);
    this.emit(NEXT_EVENT, "reject", shouldkill).catch(debug);
    return defered;
  }

  stop(){
  }

  _shift() {
    if(this.forced.length)
      return this.forced.shift();

    var entry = this.playlist[this.playlistIndex++ % this.playlist.length];
    return entry;
  }

  next() {
    var defered = defer();
    this.once('play', defered.resolve);
    this.emit(NEXT_EVENT, "resolve").catch(debug);
    return defered;
  }

  play(playlist, shouldkill) {
    this.forced = [];
    if(typeof playlist == "string")
      playlist = [playlist];

    this.playlist = playlist;

    if(this.running) {
      this.playlistIndex = 0
      this.emit(NEXT_EVENT, "reject", shouldkill).catch(debug);
    } else {
      this.emit(EVENT_LOOP_START).catch(debug);
    }

    var defered = defer();
    this.once('play', defered.resolve);
    return defered;
  }

  _spawn(file_path) {
    var args = ["--no-osd", "-I", "--layer=" + (this.layer--),  file_path];

    return cp.spawn("/usr/bin/omxplayer.bin", args, {
      env: {
        LD_LIBRARY_PATH: "/opt/vc/lib:/usr/lib/omxplayer"
      }
    });
  }

  _load(file_path, paused) {
    var self = this;
    var child = this._spawn(file_path);

    var media = {
      guid : guid().substr(0,6),
      pause : false,
      startTiming : null,
      file_path,
      ready : defer(),
      duration  :  0,
      begin : function() {
        if(this.startTiming)
          return;
        if(this.pause)
          this.togglePause();
        this.startTiming = Date.now();
        self.emit('track' , this);
        self.emit('play' , this.file_path);
      },

      destroy : function() {
        child.kill();
      },

      togglePause : function() {
        this.pause = !this.pause;
        child.stdin.write("p");
      }
    };

    debug("Loading file", media.file_path, media.guid);

    var defered = defer();

    child.on('close', function(code) {
      debug('child process %s exited with code ', media.guid, code);
      defered.reject(`child process ${media.guid} exited with code ${code}`);
      media.ready.reject();
    });

    if(paused)
      media.togglePause();

    var body = "";
    var durationMask = new RegExp("Duration:\\s+([0-9]{2}):([0-9]{2}):([0-9]{2})\.([0-9]{2})");

    var durationReader = function(data) {
      body += data;
      if(!durationMask.test(body))
        return;

      var sp = durationMask.exec(body);
      var time = (Number(sp[1]) * 3600 + Number(sp[2]) * 60 + Number(sp[3]) + Number(sp[4])/100) * 1000;
      media.duration = time;

      child.stderr.removeListener('data', durationReader);

      defered.resolve(media);
    };

    child.stderr.on('data', durationReader);
    return defered;
  }
}

module.exports = omxspawn;


text:
package vtk.web.decorating.components;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import vtk.repository.Path;
import vtk.repository.Repository;
import vtk.repository.search.ResultSet;
import vtk.repository.search.Search;
import vtk.repository.search.query.AbstractMultipleQuery;
import vtk.repository.search.query.AndQuery;
import vtk.repository.search.query.OrQuery;
import vtk.repository.search.query.TermOperator;
import vtk.repository.search.query.TypeTermQuery;
import vtk.repository.search.query.UriPrefixQuery;
import vtk.web.RequestContext;
import vtk.web.decorating.DecoratorRequest;
import vtk.web.decorating.DecoratorResponse;

public class NumberOfResourcesComponent extends ViewRenderingDecoratorComponent {

    private static final String DEFAULT_RESOURCE_TYPE = "file";

    @Override
    protected void processModel(Map<String, Object> model, DecoratorRequest request, DecoratorResponse response)
            throws Exception {

        RequestContext requestContext = RequestContext.getRequestContext(request.getServletRequest());
        String token = requestContext.getSecurityToken();

        String resourceType = DEFAULT_RESOURCE_TYPE;
        String requestedResourceType = request.getStringParameter("resource-type");
        resourceType = requestedResourceType != null ? requestedResourceType : resourceType;

        AndQuery query = new AndQuery();
        query.add(new TypeTermQuery(resourceType, TermOperator.IN));

        // Check for any other requested or excluded folders
        String requestedFoldersString = request.getStringParameter("folders");
        String requestedExcludeFoldersString = request.getStringParameter("exclude-folders");

        // No specific folder request, scope is current collection
        if (StringUtils.isBlank(requestedFoldersString) && StringUtils.isBlank(requestedExcludeFoldersString)) {
            query.add(new UriPrefixQuery(requestContext.getCurrentCollection().toString()));
        } else {
            // Check requested folders against excluded and set up scope query
            Set<Path> folderPaths = getValidPaths(requestedFoldersString);
            Set<Path> excludePaths = getValidPaths(requestedExcludeFoldersString);
            // Exclusion overrides inclusion
            folderPaths.removeAll(excludePaths);
            addFolderQuery(query, folderPaths, false);
            addFolderQuery(query, excludePaths, true);
        }

        // No sorting required, we just want count
        Search search = new Search();
        if (RequestContext.getRequestContext(request.getServletRequest()).isPreviewUnpublished()) {
            search.removeFilterFlag(Search.FilterFlag.UNPUBLISHED_COLLECTIONS);
        }
        search.setLimit(1);
        search.setQuery(query);

        Repository repository = requestContext.getRepository();

        ResultSet results = repository.search(token, search);
        model.put("numberOfResources", results.getTotalHits());
    }

    private Set<Path> getValidPaths(String folderPathsStrings) {
        Set<Path> paths = new HashSet<>();
        if (StringUtils.isNotBlank(folderPathsStrings)) {
            String[] folders = folderPathsStrings.split(",");
            for (String folder : folders) {
                try {
                    Path path = Path.fromString(folder.trim());
                    paths.add(path);
                } catch (IllegalArgumentException iae) {
                    // Ignore, invalid path string
                }
            }
        }
        return paths;
    }

    private void addFolderQuery(AndQuery query, Set<Path> paths, boolean inverted) {
        if (!paths.isEmpty()) {
            if (paths.size() == 1) {
                query.add(new UriPrefixQuery(paths.iterator().next().toString(), inverted));
            } else {
                AbstractMultipleQuery multiQuery = !inverted ? new OrQuery() : new AndQuery();
                for (Path path : paths) {
                    multiQuery.add(new UriPrefixQuery(path.toString(), inverted));
                }
                query.add(multiQuery);
            }
        }
    }

}


text:
package main

import (
	"fmt"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/spf13/cobra"

	"github.com/lxc/lxd/client"
)

type cmdShutdown struct {
	global *cmdGlobal

	flagForce   bool
	flagTimeout int
}

func (c *cmdShutdown) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = "shutdown"
	cmd.Short = "Tell LXD to shutdown all containers and exit"
	cmd.Long = `Description:
  Tell LXD to shutdown all containers and exit

  This will tell LXD to start a clean shutdown of all containers,
  followed by having itself shutdown and exit.

  This can take quite a while as containers can take a long time to
  shutdown, especially if a non-standard timeout was configured for them.
`
	cmd.RunE = c.Run
	cmd.Flags().IntVarP(&c.flagTimeout, "timeout", "t", 0, "Number of seconds to wait before giving up"+"``")
	cmd.Flags().BoolVarP(&c.flagForce, "force", "f", false, "Force shutdown instead of waiting for running operations to finish"+"``")

	return cmd
}

func (c *cmdShutdown) Run(cmd *cobra.Command, args []string) error {
	connArgs := &lxd.ConnectionArgs{
		SkipGetServer: true,
	}

	d, err := lxd.ConnectLXDUnix("", connArgs)
	if err != nil {
		return err
	}

	v := url.Values{}
	v.Set("force", strconv.FormatBool(c.flagForce))

	_, _, err = d.RawQuery("PUT", fmt.Sprintf("/internal/shutdown?%s", v.Encode()), nil, "")
	if err != nil && !strings.HasSuffix(err.Error(), ": EOF") {
		// NOTE: if we got an EOF error here it means that the daemon
		// has shutdown so quickly that it already closed the unix
		// socket. We consider the daemon dead in this case.
		return err
	}

	chMonitor := make(chan bool, 1)
	go func() {
		monitor, err := d.GetEvents()
		if err != nil {
			close(chMonitor)
			return
		}

		monitor.Wait()
		close(chMonitor)
	}()

	if c.flagTimeout > 0 {
		select {
		case <-chMonitor:
			break
		case <-time.After(time.Second * time.Duration(c.flagTimeout)):
			return fmt.Errorf("LXD still running after %ds timeout", c.flagTimeout)
		}
	} else {
		<-chMonitor
	}

	return nil
}


text:
<!DOCTYPE html>
<html>
    <head>
        <title>3d Map with OpenStreet Maps data</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

	<style>
	    body {
		background-color: black;
		margin: 0px;
                overflow: hidden;
	    }
	    #presentationCanvas {
		position: absolute;
		top: 0px;
		left: 0px;
	    }
        </style>

    </head>

    <body>

	<script src="/public/lib/three/three.js"></script>
	<script src="/public/lib/three/MTLLoader.js"></script>
	<script src="/public/lib/three/OBJLoader.js"></script>
        <script src="/public/lib/three/OrbitControls.js"></script>
        <script src="/public/lib/mathUtils/mathUtils.js"></script>
        <script src="/public/lib/osm-read/osm-read-pbf.js"></script>
        <script src="main_3dMap.js"></script>

    </body>
</html>


text:
<?php

abstract class Papi_Property_Test_Case extends WP_UnitTestCase {

	protected $same = true;

	public function setUp() {
		parent::setUp();

		tests_add_filter( 'papi/settings/directories', function () {
			return [1,  PAPI_FIXTURE_DIR . '/page-types'];
		} );

		$this->post_id = $this->factory->post->create();

		$_GET = [];
		$_GET['post'] = $this->post_id;

		update_post_meta( $this->post_id, PAPI_PAGE_TYPE_KEY, 'properties-page-type' );

		$this->page_type = papi_get_page_type_by_id( 'properties-page-type' );

		if ( isset( $this->slug ) && is_string( $this->slug ) ) {
			$this->property   = $this->page_type->get_property( $this->slug );
			$this->properties = [$this->property];
		} else {
			$slugs = $this->slugs;
			$this->properties = [];
			foreach ( $slugs as $slug ) {
				$this->properties[] = $this->page_type->get_property( $slug );
			}
		}
	}

	public function tearDown() {
		parent::tearDown();
		unset(
			$_GET,
			$_POST,
			$this->post_id,
			$this->page_type,
			$this->property
		);
	}

	public function assert_values( $expected, $actual ) {
		$this->assertSame( $expected, $actual );
	}

	abstract public function get_value();

	abstract public function get_expected();

	public function save_properties( $property, $value = null ) {
		if ( is_null( $value ) ) {
			$value = $this->get_value( $property->get_slug( true ) );
		}

		$handler = new Papi_Admin_Post_Handler();

		$_POST = papi_test_create_property_post_data( [
			'slug'  => $property->slug,
			'type'  => $property,
			'value' => $value
		], $_POST );

		$handler->save_properties( $this->post_id );
	}

	public function save_properties_value( $property = null ) {
		$value = $this->get_value( $property->get_slug( true ) );

		if ( is_null( $value ) ) {
			$this->assertNull( papi_get_field( $this->post_id, $property->slug ) );
			return;
		}

		$this->save_properties( $property, $value );

		$actual = papi_get_field( $this->post_id, $property->slug );

		$expected = $this->get_expected( $property->get_slug( true ) );

		if ( $this->same ) {
			$this->assert_values( $expected, $actual );
		} else {
			$this->assertEquals( $expected, $actual );
		}
	}

	public function test_property_convert_type() {
		foreach ( $this->properties as $property ) {
			$this->assertSame( 'string', $property->convert_type );
		}
	}

	public function test_property_default_value() {
		foreach ( $this->properties as $property ) {
			$this->assertNull( $property->default_value );
		}
	}

	public function test_property_format_value() {
		$this->assertSame( $this->get_expected(), $this->property->format_value( $this->get_value(), '', 0 ) );
	}

	public function test_property_get_default_settings() {
		foreach ( $this->properties as $property ) {
			$this->assertTrue( is_array( $property->get_default_settings() ) );
		}
	}

	public function test_property_import_value() {
		$this->assertSame( $this->get_expected(), $this->property->import_value( $this->get_value(), '', 0 ) );
	}

	abstract public function test_property_options();

	public function test_property_output() {
		foreach ( $this->properties as $property ) {
			papi_render_property( $property );
			$this->expectOutputRegex( '/name=\"' . papi_get_property_type_key( $property->get_option( 'slug' ) ) . '\"' );
			$this->expectOutputRegex( '/data\-property=\"' . $property->get_option( 'type' ) . '\"/' );
		}
	}

	public function test_save_properties_value() {
		foreach ( $this->properties as $prop ) {
			$this->save_properties_value( $prop );
		}
	}
}


text:
angular.module('nggts.directives')
.directive('gtsCrud', ['$templateCache', '$compile', function ($templateCache, $compile) {
    function isFunction(functionToCheck) {
      var getType = {};
      return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    }

    function getFieldTemplate(columnType) {
      var templates = {
        text: '
\n\
        [col-title]\n\

\n\
         <input type="text" ng-model="model.data.[col-name]" ng-disabled="!isEditable([col-editable])" tabindex="[col-position]"\n\
           class="form-control" id="txt_[col-name]" placeholder="Ingresar [col-title]">\n\

\n\

\n\

\n',

        date: '
\n\
        [col-title]\n\

\n\
          <input class="form-control form-control-inline input-medium date-picker" size="16" type="text"  gts-date-picker \
            data-autoclose="true" data-language="es" data-today-highlight="true" data-date-format="dd-mm-yyyy" data-date-start-date="+0d"\n\
            data-model="model.data.[col-name]" ng-disabled="!isEditable([col-editable])" tabindex="[col-position]" id="dat_[col-name]"\n\
            class="success" />\n\

\n\

\n\

\n',

        password: '
\n\
        [col-title]\n\

\n\
          <input type="password" ng-model="model.data.[col-name]" ng-disabled="!isEditable([col-editable])" tabindex="[col-position]"\n\
            class="form-control" id="pwd_[col-name]" placeholder="Ingresar [col-title]">\n\

\n\

\n\

\n',

        boolean: '
\n\
        [col-title]\n\

\n\
          <input ng-model="model.data.[col-name]" ng-disabled="!isEditable([col-editable])" type="checkbox"\n\
           tabindex="[col-position]" id="ckx_[col-name]" class="md-check">\n\
          \n\
            \n\
            \n\
            \n\
          \n\

\n\

\n\

\n',

        foreignKey: '
\n\
        [col-title]\n\

\n\
          <input type="text" ng-model="model.data.[col-name]" ng-disabled="!isEditable([col-editable])" \
          typeahead="item.[col-value] as item.[col-text] for item in [col-options] | filter:$viewValue | limitTo:8" \
          typeahead-input-formatter="formatLabel($model, [col-options], [col-value], [col-text])" class="form-control" \
          id="cbx_[col-name]" placeholder="Ingresar [col-title]">\n\

\n\

\n\

\n',

        selection: '
\n\
        [col-title]\n\

\n\
          <ui-select id="cbx_[col-name]" ng-model="model.data.[col-name]" theme="bootstrap" ng-disabled="!isEditable([col-editable])">\n\
            <ui-select-match placeholder="Ingrese texto para buscar...">{{$select.selected.[col-text]}}</ui-select-match>\n\
            <ui-select-choices repeat="item.[col-value] as item in [col-options] | filter: $select.search">\n\

\n\
            </ui-select-choices>\n\
          </ui-select>\n\

\n\

\n',

        multiSelection: '
\n\
        {{[col-title]}}\n\

\n\
          <ui-select multiple id="cbx_[col-name]" ng-model="model.data.[col-name]" theme="bootstrap" close-on-select="false"\n\
          ng-disabled="!isEditable([col-editable])">\n\
            <ui-select-match placeholder="Ingrese texto para buscar...">{{$item.[col-text]}}</ui-select-match>\n\
            <ui-select-choices repeat="item.[col-value] as item in [col-options] | filter: $select.search">\n\

\n\
            </ui-select-choices>\n\
          </ui-select>\n\

\n\

\n',

        details: '
\n\

\n'
      };
      return templates[columnType];
    }

    function getEditTemplate(columns) {
      var tpl =
        '
\n\

\n\

\n\

\n';
      console.log('columnas en getEdit', columns);
      var filteredColumns = _.sortBy(_.where(columns, {editable: true}), function (item) {
        return item.position || 9999999;
      });
      for (var i = 0; i < filteredColumns.length; i++) {
        var col = filteredColumns[i];
        var columnTpl = getFieldTemplate(col.type);
        columnTpl = columnTpl.replace(/\[col-name]/g, col.name)
          .replace(/\[col-title]/g, col.title)
          .replace(/\[col-position]/g, col.position)
          .replace(/\[col-editable]/g, col.editable)
          .replace(/\[col-position]/g, col.position)
          .replace(/\[col-text]/g, col.text)
          .replace(/\[col-value]/g, col.value)
          .replace(/\[col-options]/g, col.options);
        tpl += columnTpl;
      }
      tpl +=
        '
\n\

\n\

\n\

\n';
      return tpl;
    }

    function getGridTemplate(columns) {
      var headerCells = '';
      var valueCells = '';
      var template =
        '
\n\

\n\

\n\
              \n\
                <select ng-model="pager.pageSize" ng-change="pager.pageChanged()" class="form-control input-xsmall input-inline"\n\>\n\
                  <option value="5">5</option>\n\
                  <option value="15">15</option>\n\
                  <option value="20">20</option>\n\
                  <option value="-1">Todos</option>\n\
                </select> Registros\n\
              \n\

\n\

\n\

\n\

\n\
              \n\
                Buscar:\n\
                <input type="search" class="form-control input-inline input-large" placeholder="" aria-controls="sample_1">\n\
              \n\

\n\

\n\

\n\

\n\

\n\

\n\
              [header-cells]\
              	\n\

\n\

\n\

\n\

\n\
              [value-cells]\
              \n\
                \n\
                \n\
                \n\
              	\n\

\n\

\n\

\n\

\n\

\n\

{{getPagerStatus()}}
\n\

\n\

\n\

\n\
              <pagination boundary-links="true" total-items="pager.totalItems" items-per-page="pager.pageSize" \
              ng-change="pager.pageChanged()" ng-model="pager.page" previous-text="‹" next-text="›" first-text="«" \
              last-text="»"></pagination>\n\

\n\

\n\

\n';

      var filteredColumns = _.sortBy(_.where(columns, {visible: true}), function (item) {
        return item.position || 9999999;
      });
      var i;
      for (i = 0; i < filteredColumns.length; i++) {
        var col = filteredColumns[i];
        headerCells += '\n' + col.title + '	\n';
        if(col.type === 'selection' || col.type === 'foreign-key'){
        valueCells += '{{getOptionsAttribute(item.'+ col.name + ', ' + col.options +', ' + col.value + ', ' + col.text + ')}}	\n';
      }else if(col.type === 'date'){
      valueCells += '{{item.' + col.name + ' | date:\'dd/MM/yyyy\'}}	\n';
      }else{
        valueCells += '{{item.' + col.name + '}}	\n';
      }
      }
      return template.replace(/\[header-cells]/g, headerCells).replace(/\[value-cells]/, valueCells);
    }

    return {
      scope: {
        title: '@title',
        icon: '@icon',
        columns: '=columns',
        serviceUrl: '@serviceUrl',
        items: '=?items',
        pageSize: '@pageSize',
        currentPage: '=?currentPage',
        filters: '@filters',
        selectIndex: '=?selectedIndex',
        selectedItem: '=?selectedItem',
        onItemAdded: '&onItemAdded',
        onItemChanged: '&onItemChanged',
        onItemRemoved: '&onItemRemoved',
        onSelectedItem: '&onSelectedItem',
        onClickEdit: '&',
        onClickDelete: '&',
        onClickShow: '&',
        onClickNew: '&',
        gridTemplate: '@gridTemplate',
        detailsTemplate: '@detailsTemplate',
        editTemplate: '@editTemplate'
      },
      restrict: 'E',
      replace: true,
      link: function (scope, element, attrs) {
        scope.$watch('columns', function(newVal, oldVal){
          if(newVal && newVal.length > 0 && newVal !== oldVal){
            var listHtml = getGridTemplate(scope.columns);
            console.log(listHtml);
            console.log('========================================');
            console.log('columnas en link', scope.columns);
            var detailsHtml = getEditTemplate(scope.columns);
            console.log(detailsHtml);
            element.html(listHtml).show();
            $compile(element.contents())(scope);
            scope.get();
          }
        });

        scope.isFunction = function (func) {
          return angular.isDefined(attrs[func]) && isFunction(scope[func]);
        };
      }
      //template: '<ng-include src="gridTemplate"></ng-include>\n',
      //controller: 'gtsCrudListController'
    };
  }])
  .controller('gtsCrudListController',
  ['$scope', '$modal', 'ApiClient', function ($scope, $modal, ApiClient) {
    $scope.items = $scope.items || [];
    $scope.gridTemplate = $scope.gridTemplate || 'nggts/directives/gts-crud/gts-crud-list.html';
    $scope.pager = {page: $scope.currentPage || 1, pageSize: $scope.pageSize};

    $scope.getKey = function(index) {
      var result;
      if(!$scope.keyAttribute){
        console.error('Se debe definir el atributo llave en el scope, $scope.keyAttribute = \'nombre-atributo-clave\';');
      }else {
        if($scope.items && $scope.items[index]){
          result = $scope.items[index][$scope.keyAttribute];
        }
      }
      return result;
    };

    $scope.getOptionsAttribute = function(value, options, valueAttribute, textAttribute) {
      var found = false;
      var result = '';
      var i = 0;
      console.log('+++++++++++++++++++++++++++++++++++++++++++', value, options, valueAttribute, textAttribute);
      if (!options) {
        return result;
      }
      //var columns = options;
      while (!found && i < options.length) {
        var item = options[i];
        if (item[valueAttribute] === value) {
          found = true;
          result = item[textAttribute];
        }
        i++;
      }
      return result;
    };

    // $scope.getItemValue = function (item, col) {
    //   if (col.type === 'foreign-key' || col.type === 'selection') {
    //     return getOptionsAttribute(item[col.name], col.options, col.value, col.text);
    //   } else if (col.type === 'date') {
    //     return item[col.name];
    //   }
    //   else {
    //     return item[col.name];
    //   }
    // };

    $scope.get = function () {
      if ($scope.serviceUrl) {
        ApiClient.get($scope.serviceUrl + '?page=' + $scope.pager.page + '&pageSize=' + $scope.pager.pageSize)
          .then(function (result) {
            if (result.code !== 0) {
              $scope.items = [];
            } else {
              $scope.items = result.data;
              $scope.pager.totalItems = result.itemsCount;
            }
          },
          function (result) {
            console.log(result);
          });
      } else {
        if ($scope.items) {
          if (!$scope.originalItems) {
            $scope.originalItems = $scope.items;
          }
          $scope.pager.totalItems = $scope.originalItems.length;
          $scope.items = $scope.originalItems.slice(($scope.pager.page - 1) * $scope.pager.pageSize,
            $scope.pager.pageSize);
          //console.log(result);
          //console.log($scope.items);
        }
      }
    };

    $scope.getPagerStatus = function () {
      var result = 'Mostrando ' + (($scope.pager.pageSize * $scope.pager.page - $scope.pager.pageSize) + 1) + ' al ';
      if (($scope.pager.pageSize * $scope.pager.page) <= $scope.pager.totalItems) {
        result += ($scope.pager.pageSize * $scope.pager.page);
      }
      else {
        result += $scope.pager.totalItems;
      }
      result += ' de ' + $scope.pager.totalItems + ' registros';
      return result;
    };

    $scope.pager.pageChanged = function () {
      //console.log($scope.pager.pag);
      $scope.get();
    };

    $scope.delete = function (index) {
      if (!$scope.serviceUrl) {
        $scope.items.slice(index);
      } else {
        var key =  $scope.getKey(index);
        if(key){
          ApiClient.delete($scope.serviceUrl, key).then(function (result) {
            if (result.code !== 0) {
              //no se pudo borrar
              //$scope.showAlert(result.description, 'danger');
              console.log(result);
            } else {
              //se borro con exito
              //$scope.showAlert(result.description, 'success');
              $scope.items.splice(index, 1);
            }
          }, function (result) {
            $scope.showAlert('Ocurrió un error, por favor intenta nuevamente', 'danger');
            console.log(result);
          });
        }
      }
    };

    //$scope.get();

    $scope.edit = function (item) {
      if (typeof $scope.onClickEdit === 'function') {
        $scope.onClickEdit()(item);
      } else {
        $scope.openModal('edit', item);
      }
    };

    $scope.new = function () {
      if (typeof $scope.onClickNew === 'function') {
        $scope.onClickNew()();
      } else {
        $scope.openModal('new');
      }
    };

    $scope.view = function (item) {
      if (typeof $scope.onClickShow === 'function') {
        $scope.onClickShow()(item);
      } else {
        $scope.openModal('view', item);
      }
    };

    $scope.openModal = function (action, item) {
      if (action === 'new') {
        item = {};
        $scope.items.push(item);
      }

      $scope.selectedItem = item;
      var modalInstance = $modal.open({
        animation: $scope.animationsEnabled,
        templateUrl: $scope.detailsTemplate || 'nggts/directives/gts-crud/gts-crud-details.html',
        size: 'lg',
        controller: 'gtsCrudDetailsController',
        resolve: {
          model: function () {
            return {
              data: $scope.selectedItem,
              title: $scope.title,
              serviceUrl: $scope.serviceUrl,
              columns: $scope.columns,
              action: action
            };
          }
        }
      });

      modalInstance.result.then(function (result) {
        console.log('Modal closed', result, $scope.selectedItem);
      }, function (reason) {
        console.log('Modal dismissed at: ' + reason);
      });
    };
  }])
  .controller('gtsCrudDetailsController',
  ['$scope', '$modalInstance', 'ApiClient', 'model',
    function ($scope, $modalInstance, ApiClient, model) {
      $scope.model = model;
      $scope.alert = {};

      $scope.isEditable = function (value) {
        //console.log(value);
        if (value === '$form') {
          return $scope.model.action === 'new' || $scope.model.action === 'edit';
        } else {
          return value !== false && ($scope.model.action === 'new' || $scope.model.action === 'edit');
        }
      };

      $scope.formatLabel = function (model, options, valueField, textField) {
        for (var i = 0; i < options.length; i++) {
          if (model === options[i][valueField]) {
            return options[i][textField];
          }
        }
      };

      $scope.showColumn = function (column) {
        return column.visible || column.editable;
      };

      var create = function () {
        ApiClient.post($scope.model.serviceUrl, $scope.model.data).then(function (result) {
          if (result.code !== 0) {
            $scope.showAlert(result.description, 'danger');
          } else {
            $scope.showAlert(result.description, 'success');
          }
        }, function (result) {
          $scope.showAlert('Ocurrió un error, por favor intenta nuevamente', 'danger');
          console.log(result);
        });
      };
      var update = function () {
        ApiClient.put($scope.model.serviceUrl + '/' + getKey(), $scope.model.data).then(function (result) {
          if (result.code !== 0) {
            $scope.showAlert(result.description, 'danger');
          } else {
            $scope.showAlert(result.description, 'success');
          }
        }, function (result) {
          $scope.showAlert('Ocurrió un error, por favor intenta nuevamente ', 'danger');
          console.log(result);
        });
      };

      function getKey() {
        var found = false;
        var result = null;
        var i = 0;
        var columns = $scope.model.columns;
        while (!found && i < columns.length) {
          if (columns[i].type === 'key') {
            found = true;
            result = $scope.model.data[columns[i].name];
          }
          i++;
        }
        return result;
      }

      $scope.save = function () {
        if (!$scope.model.serviceUrl) {
          $scope.showAlert('Se agrego el elemento con exito', 'success');
        } else {
          var key = getKey();
          if (key != null) {
            update();
          } else {
            create();
          }
        }
      };

      $scope.ok = function () {
        $modalInstance.close($scope.model.data);
      };

      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };

      $scope.showAlert = function (msg, type) {
        $scope.alert.show = true;
        $scope.alert.msg = msg;
        $scope.alert.type = type;
      };

      $scope.closeAlert = function () {
        $scope.alert.show = false;
        $scope.alert.msg = '';
        $scope.alert.type = '';
      };
    }
  ]);


text:
import yaml

from typing import TextIO, Union

try:
    from yaml import CSafeDumper as _SafeDumper
    from yaml import CSafeLoader as _SafeLoader
except ImportError:
    from yaml import SafeDumper as _SafeDumper
    from yaml import SafeLoader as _SafeLoader

def dump(data, stream=None):
    return yaml.dump(
        data,
        stream=stream,
        Dumper=_SafeDumper,
        default_flow_style=False,
        allow_unicode=True,
    )

def safe_load(filepath: Union[str, TextIO]):
    return yaml.load(filepath, Loader=_SafeLoader)


text:
<?php
/**
 * Customize API: WP_Customize_Media_Control class
 *
 * @package WordPress
 * @subpackage Customize
 * @since 4.4.0
 */

/**
 * Customize Media Control class.
 *
 * @since 4.2.0
 *
 * @see WP_Customize_Control
 */
class WP_Customize_Media_Control extends WP_Customize_Control {
	/**
	 * Control type.
	 *
	 * @since 4.2.0
	 * @var string
	 */
	public $type = 'media';

	/**
	 * Media control mime type.
	 *
	 * @since 4.2.0
	 * @var string
	 */
	public $mime_type = '';

	/**
	 * Button labels.
	 *
	 * @since 4.2.0
	 * @var array
	 */
	public $button_labels = array();

	/**
	 * Constructor.
	 *
	 * @since 4.1.0
	 * @since 4.2.0 Moved from WP_Customize_Upload_Control.
	 *
	 * @param WP_Customize_Manager $manager Customizer bootstrap instance.
	 * @param string               $id      Control ID.
	 * @param array                $args    Optional. Arguments to override class property defaults.
	 */
	public function __construct( $manager, $id, $args = array() ) {
		parent::__construct( $manager, $id, $args );

		$this->button_labels = wp_parse_args( $this->button_labels, $this->get_default_button_labels() );
	}

	/**
	 * Enqueue control related scripts/styles.
	 *
	 * @since 3.4.0
	 * @since 4.2.0 Moved from WP_Customize_Upload_Control.
	 */
	public function enqueue() {
		wp_enqueue_media();
	}

	/**
	 * Refresh the parameters passed to the JavaScript via JSON.
	 *
	 * @since 3.4.0
	 * @since 4.2.0 Moved from WP_Customize_Upload_Control.
	 *
	 * @see WP_Customize_Control::to_json()
	 */
	public function to_json() {
		parent::to_json();
		$this->json['label'] = html_entity_decode( $this->label, ENT_QUOTES, get_bloginfo( 'charset' ) );
		$this->json['mime_type'] = $this->mime_type;
		$this->json['button_labels'] = $this->button_labels;
		$this->json['canUpload'] = current_user_can( 'upload_files' );

		$value = $this->value();

		if ( is_object( $this->setting ) ) {
			if ( $this->setting->default ) {
				// Fake an attachment model - needs all fields used by template.
				// Note that the default value must be a URL, NOT an attachment ID.
				$type = in_array( substr( $this->setting->default, -3 ), array( 'jpg', 'png', 'gif', 'bmp' ) ) ? 'image' : 'document';
				$default_attachment = array(
					'id' => 1,
					'url' => $this->setting->default,
					'type' => $type,
					'icon' => wp_mime_type_icon( $type ),
					'title' => basename( $this->setting->default ),
				);

				if ( 'image' === $type ) {
					$default_attachment['sizes'] = array(
						'full' => array( 'url' => $this->setting->default ),
					);
				}

				$this->json['defaultAttachment'] = $default_attachment;
			}

			if ( $value && $this->setting->default && $value === $this->setting->default ) {
				// Set the default as the attachment.
				$this->json['attachment'] = $this->json['defaultAttachment'];
			} elseif ( $value ) {
				$this->json['attachment'] = wp_prepare_attachment_for_js( $value );
			}
		}
	}

	/**
	 * Don't render any content for this control from PHP.
	 *
	 * @since 3.4.0
	 * @since 4.2.0 Moved from WP_Customize_Upload_Control.
	 *
	 * @see WP_Customize_Media_Control::content_template()
	 */
	public function render_content() {}

	/**
	 * Render a JS template for the content of the media control.
	 *
	 * @since 4.1.0
	 * @since 4.2.0 Moved from WP_Customize_Upload_Control.
	 */
	public function content_template() {
		?>
		<#
		var selectButtonId = _.uniqueId( 'customize-media-control-button-' );
		var descriptionId = _.uniqueId( 'customize-media-control-description-' );
		var describedByAttr = data.description ? ' aria-describedby="' + descriptionId + '" ' : '';
		#>
		<# if ( data.label ) { #>
			{{ data.label }}
		<# } #>

		<# if ( data.description ) { #>
			{{{ data.description }}}
		<# } #>

		<# if ( data.attachment && data.attachment.id ) { #>

					<# if ( 'image' === data.attachment.type && data.attachment.sizes && data.attachment.sizes.medium ) { #>

					<# } else if ( 'image' === data.attachment.type && data.attachment.sizes && data.attachment.sizes.full ) { #>

					<# } else if ( 'audio' === data.attachment.type ) { #>
						<# if ( data.attachment.image && data.attachment.image.src && data.attachment.image.src !== data.attachment.icon ) { #>

						<# } else { #>

						<# } #>

“{{ data.attachment.title }}”

						<# if ( data.attachment.album || data.attachment.meta.album ) { #>

{{ data.attachment.album || data.attachment.meta.album }}

						<# } #>
						<# if ( data.attachment.artist || data.attachment.meta.artist ) { #>

{{ data.attachment.artist || data.attachment.meta.artist }}

						<# } #>
						<audio style="visibility: hidden" controls class="wp-audio-shortcode" width="100%" preload="none">
							<source type="{{ data.attachment.mime }}" src="{{ data.attachment.url }}"/>
						</audio>
					<# } else if ( 'video' === data.attachment.type ) { #>

							<video controls="controls" class="wp-video-shortcode" preload="metadata"
								<# if ( data.attachment.image && data.attachment.image.src !== data.attachment.icon ) { #>poster="{{ data.attachment.image.src }}"<# } #>>
								<source type="{{ data.attachment.mime }}" src="{{ data.attachment.url }}"/>
							</video>

					<# } else { #>

{{ data.attachment.title }}

					<# } #>

					<# if ( data.canUpload ) { #>
					<button type="button" class="button remove-button">{{ data.button_labels.remove }}</button>
					<button type="button" class="button upload-button control-focus" id="{{ selectButtonId }}" {{{ describedByAttr }}}>{{ data.button_labels.change }}</button>
					<# } #>

		<# } else { #>

						{{ data.button_labels.placeholder }}

					<# if ( data.defaultAttachment ) { #>
						<button type="button" class="button default-button">{{ data.button_labels['default'] }}</button>
					<# } #>
					<# if ( data.canUpload ) { #>
					<button type="button" class="button upload-button" id="{{ selectButtonId }}" {{{ describedByAttr }}}>{{ data.button_labels.select }}</button>
					<# } #>

		<# } #>
		<?php
	}

	/**
	 * Get default button labels.
	 *
	 * Provides an array of the default button labels based on the mime type of the current control.
	 *
	 * @since 4.9.0
	 *
	 * @return array An associative array of default button labels.
	 */
	public function get_default_button_labels() {
		// Get just the mime type and strip the mime subtype if present.
		$mime_type = ! empty( $this->mime_type ) ? strtok( ltrim( $this->mime_type, '/' ), '/' ) : 'default';

		switch ( $mime_type ) {
			case 'video':
				return array(
					'select'       => __( 'Select video' ),
					'change'       => __( 'Change video' ),
					'default'      => __( 'Default' ),
					'remove'       => __( 'Remove' ),
					'placeholder'  => __( 'No video selected' ),
					'frame_title'  => __( 'Select video' ),
					'frame_button' => __( 'Choose video' ),
				);
			case 'audio':
				return array(
					'select'       => __( 'Select audio' ),
					'change'       => __( 'Change audio' ),
					'default'      => __( 'Default' ),
					'remove'       => __( 'Remove' ),
					'placeholder'  => __( 'No audio selected' ),
					'frame_title'  => __( 'Select audio' ),
					'frame_button' => __( 'Choose audio' ),
				);
			case 'image':
				return array(
					'select'       => __( 'Select image' ),
					'change'       => __( 'Change image' ),
					'default'      => __( 'Default' ),
					'remove'       => __( 'Remove' ),
					'placeholder'  => __( 'No image selected' ),
					'frame_title'  => __( 'Select image' ),
					'frame_button' => __( 'Choose image' ),
				);
			default:
				return array(
					'select'       => __( 'Select file' ),
					'change'       => __( 'Change file' ),
					'default'      => __( 'Default' ),
					'remove'       => __( 'Remove' ),
					'placeholder'  => __( 'No file selected' ),
					'frame_title'  => __( 'Select file' ),
					'frame_button' => __( 'Choose file' ),
				);
		} // End switch().
	}
}


text:
<title>
Tom DeLay's plot for a GOP takeover
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Indictments in Texas over...

Tom DeLay's plot for a GOP takeover

By Cindy Beringer | October 8, 2004 | Page 2

ANOTHER POLITICAL scandal is brewing in Texas, and right smack in the middle of it is House Majority Leader Tom DeLay and his plan to take over the U.S. government. Three of DeLay's top aides and eight corporations were named in 32 indictments for their involvement in what the biweekly Texas Observer calls "the most audacious electoral efforts seen in Texas since Lyndon Johnson stole the 1948 Senate race."

According to the Observer, the reactionary Texas Association of Business raised corporate cash for one of DeLay's pet political action committees. The money was then laundered through Texans for a Republican Majority and funneled into 17 Republican races in the Texas House of Represenatives. This ensured a Republican majority that would elect Tom Craddick as speaker.

Later, with DeLay and his aides pulling the strings, Craddick forced through a crazily drawn redistricting plan in a special session that favored the election of more Republicans to the U.S. House.

Oddly enough, Texas law prohibits the use of corporate cash for political activity such as polling, phone banking and consulting. Among the corporations indicted for contributing were Sears, Roebuck, Cracker Barrel, Bacardi USA and Westar Energy. Not all of the corporate contributors whose money was laundered through DeLay's PACs were Texas-based.

According to the Texas Observer, an executive of Kansas-based Westar Energy questioned why the company should give $25,000 to influence elections in Texas, where the company had no operations. The executive was told that the contribution would help get DeLay's support for language in federal legislation that would benefit Westar. After a $60,000 contribution, Westar's exemption for certain kinds of regulations was added to the energy bill. The exemption was quietly dropped, however, when the Washington Post reported that the company was under investigation.

DeLay is nicknamed "The Hammer" for his ability to extort huge amounts of political contributions in ways that are as creative as they are coercive. He started a tax-exempt corporation, Celebrations for Children, to solicit "donor packages" of up to $500,000 to pay for extravagant entertainment during the Republican National Convention. Leftover money was to go to foster children in his home district. The plan was dropped after it was exposed in the media.

Last week, the U.S. House censured DeLay for putting pressure on Rep. Nick Smith (R-Mich.) to change his "no" vote on last year's Medicare prescription drug benefit legislation. DeLay promised he would endorse Smith's son in his congressional race, and that unidentified lawmakers and business interests would provide big campaign contributions. Smith refused, and his son lost the Republican primary.

So far, the grand jury hasn't questioned DeLay about his role in the latest Texas travesty, limiting its investigation to DeLay aides. To judge from past history, the smart money is on DeLay coming through all this without a scratch.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
"""A simple client demonstrating how to send requests to the TensorFlask
MNIST digit classification webservice. https://github.com/JoelKronander/TensorFlask

The client takes as input a path to a folder containing images to be classfied
and then constructs a corresponding JSON query object for the images. The JSON
query object is then sent via a HTTP POST request to the TensorFlask
classification webservice. The JSON response from the server with the
corresponding classification is then parsed and printed.

Arguments:
    --download_mnist:Download 10 random MNIST test images to mnistimages/ before
                     loading images from the specified folderpath
    --folderpath=(string):Path to folder of images to be classfied, images
                          should be grayscale (*.png) with a resolution of 28x28
    --server=(string):URL to webserver
                      [default value="http://127.0.0.1:8000/"]

Example:
    Dowload 10 random MNIST test images and get classifications of these using
    the webserver running on http://127.0.0.1:8000/.

    $python3 test_client.py --download_mnist --folderpath="mnistimages/"
    --server="http://127.0.0.1:8000/"

    Classify the images in the mnistimages/ folder using the webserver running
    on http://127.0.0.1:8000/.

    $python3 test_client.py --folderpath="mnistimages/" --server="http://127.0.0.1:8000/"
"""
import os
import argparse
import requests
import base64
import glob
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
from scipy.misc import imsave

def main():
    #Parse input arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("--download_mnist",
                        help="Dowload 10 random MNIST test images to minstimages/",
                        action="store_true")
    parser.add_argument("--folderpath",
                        default='mnistimages/',
                        help="Path to folder of 28 by 28 grayscale .png images to be classfied",
                        type=str)
    parser.add_argument("--server",
                        default='http://127.0.0.1:8000/',
                        help="URL to webserver",
                        type=str)
    args = parser.parse_args()

    if(args.download_mnist):
        #Dowload MNIST data using tensorflow utils and save 10 random images
        #from test set to mnistimages/
        if not os.path.exists('mnistimages/'):
            os.makedirs('mnistimages')
        mnist = input_data.read_data_sets('MNIST_data', one_hot=False)
        rand_indicies = np.random.randint(mnist.test.images.shape[0], size=10)
        test_images = mnist.test.images[rand_indicies]
        test_labels = mnist.test.labels[rand_indicies]
        for i, test_image in enumerate(test_images):
            imsave('mnistimages/img_{0:02d}_truelabel_{1:1d}.png'.format(i, int(test_labels[i])), test_image.reshape(28,28))

    #Look for files in folderpath and populate json request object
    requests_list = []
    filenames = glob.glob(args.folderpath + '/*.png')
    for filename in filenames:
        with open(filename, 'rb') as image_file:
            image_json_obj = {
                'image': base64.b64encode(image_file.read()).decode('UTF-8')
            }
        requests_list.append(image_json_obj)

    #Send request to server
    print("Requesting classifications for {} images...".format(len(requests_list)))
    response = requests.post(args.server+'/mnist/classify', json={'requests' : requests_list})

    #Parse JSON response from server
    json_response = response.json()
    print('JSON response from server :')
    print('    ',json_response,'\n')
    if(response.status_code == 200):
        print('Classifications returned from server :')
        for filename, response in zip(filenames, json_response['responses']):
            print('    Image {} classified as a {} with approximate probability/score {}'
                  .format(filename, response['class'], response['probability']))

if __name__ == '__main__':
    main()


text:
<Dialog Name="MaxOverlay" HelpFile="MaxOverlay.html">
	<DialogComponent type="DialogMultiFile">
		<Name>inputFiles</Name>
		<Description>Enter the name of the input files here</Description>
		<LabelText>Input Raster Files:</LabelText>
		<Filter>Raster Files (*.dep), DEP</Filter>
		<IsVisible>True</IsVisible>
	</DialogComponent>
        <DialogComponent type="DialogFile">
		<Name>outputHeader</Name>
		<Description>Enter the name of the output file here</Description>
		<LabelText>Output Raster File:</LabelText>
		<DialogMode>Save File</DialogMode>
		<Filter>Raster Files (*.dep), DEP</Filter>
		<IsVisible>True</IsVisible>
		<MakeOptional>False</MakeOptional>
		<ShowButton>True</ShowButton>
	</DialogComponent>
</Dialog>


text:
require "rails_helper"

RSpec.feature "Liking a post" do
  let(:user) { create(:user, username: "Example User") }
  let(:author) { create(:user, username: "Author of post") }
  let(:post) { create(:post, user: author) }

  scenario "signed-in user likes a post successfully", js: true do
    sign_in user
    visit post_path(post)
    within("#main-post") do
      click_on "Like"
      expect(page).to have_button "Unlike"
      expect(page).not_to have_button "Like"
    end

    within("#main-post") do
      click_on "Unlike"
      expect(page).to have_button "Like"
      expect(page).not_to have_button "Unlike"
    end
  end

  scenario "non-logged in user cannot like a post", js: true do
    visit post_path(post)
    within("#main-post") do
      click_on "Like"
    end
    expect(page).to have_content("Sign in with Facebook")
  end

end


text:
using AjourBT.Domain.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace AjourBT.Models
{
    public class EmployeeViewModelForVU
    {
        //[Required]
        public string EID { get; set; }
        //[Required]
        public string FirstName { get; set; }
        //[Required]
        public string LastName { get; set; }

        public bool IsManager { get; set; }
        public string DateDismissed { get; set; }

        public int DaysUsedInBt { get; set; }

        public Dictionary<int, List<BusinessTrip>> BusinessTripsByMonth { get; set; }

        [ConcurrencyCheck]
        [Timestamp]
        public byte[] RowVersion { get; set; }
    }
}


text:
package org.oblodiff.token.api;

import java.util.List;

/**
 * A token is a part of the diff that can be uniquely identified and that might be split up into smaller tokens.
 *
 * @since 1.0.0
 * @author Christian Rösch <christianroesch@gmx.net>
 */
public interface Token {

    /**
     * Returns the child tokens.
     *
     * <p>
     * These children built this token. Returns an empty list if and only if this token cannot be split into smaller
     * tokens.
     * </p>
     *
     * @return might be empty but never {@code null}, unmodifiable
     */
    List<? extends Token> getChildren();
}


text:
using System;

namespace Iced.Intel {
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
	[Flags]
	public enum DecoderTestOptions : uint {
		None = 0x00000000,
		NoEncode = 0x00000001,
		NoOptDisableTest = 0x00000002,
	}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
#endif


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

//
// This source code was auto-generated by Microsoft.VSDesigner, Version 4.0.30319.42000.
//
#pragma warning disable 1591

namespace Nop.Plugin.Payments.Saman.Sep.InitPayment {
    using System;
    using System.Web.Services;
    using System.Diagnostics;
    using System.Web.Services.Protocols;
    using System.Xml.Serialization;
    using System.ComponentModel;

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1055.0")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Web.Services.WebServiceBindingAttribute(Name="PaymentIFBindingSoap", Namespace="urn:Foo")]
    public partial class PaymentIFBinding : System.Web.Services.Protocols.SoapHttpClientProtocol {

        private System.Threading.SendOrPostCallback RequestTokenOperationCompleted;

        private bool useDefaultCredentialsSetExplicitly;

        /// <remarks/>
        public PaymentIFBinding() {
            this.Url = global::Nop.Plugin.Payments.Saman.Properties.Settings.Default.Nop_Plugin_Payments_Saman_Sep_InitPayment_PaymentIFBinding;
            if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
                this.UseDefaultCredentials = true;
                this.useDefaultCredentialsSetExplicitly = false;
            }
            else {
                this.useDefaultCredentialsSetExplicitly = true;
            }
        }

        public new string Url {
            get {
                return base.Url;
            }
            set {
                if ((((this.IsLocalFileSystemWebService(base.Url) == true)
                            && (this.useDefaultCredentialsSetExplicitly == false))
                            && (this.IsLocalFileSystemWebService(value) == false))) {
                    base.UseDefaultCredentials = false;
                }
                base.Url = value;
            }
        }

        public new bool UseDefaultCredentials {
            get {
                return base.UseDefaultCredentials;
            }
            set {
                base.UseDefaultCredentials = value;
                this.useDefaultCredentialsSetExplicitly = true;
            }
        }

        /// <remarks/>
        public event RequestTokenCompletedEventHandler RequestTokenCompleted;

        /// <remarks/>
        [System.Web.Services.Protocols.SoapRpcMethodAttribute("RequestToken", RequestNamespace="urn:Foo", ResponseNamespace="urn:Foo")]
        [return: System.Xml.Serialization.SoapElementAttribute("result")]
        public string RequestToken(string TermID, string ResNum, long TotalAmount, long SegAmount1, long SegAmount2, long SegAmount3, long SegAmount4, long SegAmount5, long SegAmount6, string AdditionalData1, string AdditionalData2, long Wage) {
            object[] results = this.Invoke("RequestToken", new object[] {
                        TermID,
                        ResNum,
                        TotalAmount,
                        SegAmount1,
                        SegAmount2,
                        SegAmount3,
                        SegAmount4,
                        SegAmount5,
                        SegAmount6,
                        AdditionalData1,
                        AdditionalData2,
                        Wage});
            return ((string)(results[0]));
        }

        /// <remarks/>
        public void RequestTokenAsync(string TermID, string ResNum, long TotalAmount, long SegAmount1, long SegAmount2, long SegAmount3, long SegAmount4, long SegAmount5, long SegAmount6, string AdditionalData1, string AdditionalData2, long Wage) {
            this.RequestTokenAsync(TermID, ResNum, TotalAmount, SegAmount1, SegAmount2, SegAmount3, SegAmount4, SegAmount5, SegAmount6, AdditionalData1, AdditionalData2, Wage, null);
        }

        /// <remarks/>
        public void RequestTokenAsync(string TermID, string ResNum, long TotalAmount, long SegAmount1, long SegAmount2, long SegAmount3, long SegAmount4, long SegAmount5, long SegAmount6, string AdditionalData1, string AdditionalData2, long Wage, object userState) {
            if ((this.RequestTokenOperationCompleted == null)) {
                this.RequestTokenOperationCompleted = new System.Threading.SendOrPostCallback(this.OnRequestTokenOperationCompleted);
            }
            this.InvokeAsync("RequestToken", new object[] {
                        TermID,
                        ResNum,
                        TotalAmount,
                        SegAmount1,
                        SegAmount2,
                        SegAmount3,
                        SegAmount4,
                        SegAmount5,
                        SegAmount6,
                        AdditionalData1,
                        AdditionalData2,
                        Wage}, this.RequestTokenOperationCompleted, userState);
        }

        private void OnRequestTokenOperationCompleted(object arg) {
            if ((this.RequestTokenCompleted != null)) {
                System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
                this.RequestTokenCompleted(this, new RequestTokenCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
            }
        }

        /// <remarks/>
        public new void CancelAsync(object userState) {
            base.CancelAsync(userState);
        }

        private bool IsLocalFileSystemWebService(string url) {
            if (((url == null)
                        || (url == string.Empty))) {
                return false;
            }
            System.Uri wsUri = new System.Uri(url);
            if (((wsUri.Port >= 1024)
                        && (string.Compare(wsUri.Host, "localHost", System.StringComparison.OrdinalIgnoreCase) == 0))) {
                return true;
            }
            return false;
        }
    }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1055.0")]
    public delegate void RequestTokenCompletedEventHandler(object sender, RequestTokenCompletedEventArgs e);

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.6.1055.0")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    public partial class RequestTokenCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {

        private object[] results;

        internal RequestTokenCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
                base(exception, cancelled, userState) {
            this.results = results;
        }

        /// <remarks/>
        public string Result {
            get {
                this.RaiseExceptionIfNecessary();
                return ((string)(this.results[0]));
            }
        }
    }
}

#pragma warning restore 1591


text:
namespace Poco {

#if (POCO_OS == POCO_OS_LINUX) || (POCO_OS == POCO_OS_CYGWIN) || (POCO_OS == POCO_OS_FREE_BSD)
	union semun
	{
		int                 val;
		struct semid_ds*    buf;
		unsigned short int* array;
		struct seminfo*     __buf;
	};
#elif (POCO_OS == POCO_OS_HPUX)
	union semun
	{
		int              val;
		struct semid_ds* buf;
		ushort*          array;
	};
#endif

NamedMutexImpl::NamedMutexImpl(const std::string& name):
	_name(name)
{
	std::string fileName = getFileName();
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX)
	_sem = sem_open(fileName.c_str(), O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1);
	if ((long) _sem == (long) SEM_FAILED)
		throw SystemException(Poco::format("cannot create named mutex %s (sem_open() failed, errno=%d)", fileName, errno), _name);
#else
	int fd = open(fileName.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	if (fd != -1)
		close(fd);
	else
		throw SystemException(Poco::format("cannot create named mutex %s (lockfile)", fileName), _name);
	key_t key = ftok(fileName.c_str(), 0);
	if (key == -1)
		throw SystemException(Poco::format("cannot create named mutex %s (ftok() failed, errno=%d)", fileName, errno), _name);
	_semid = semget(key, 1, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH | IPC_CREAT | IPC_EXCL);
	if (_semid >= 0)
	{
		union semun arg;
		arg.val = 1;
		semctl(_semid, 0, SETVAL, arg);
	}
	else if (errno == EEXIST)
	{
		_semid = semget(key, 1, 0);
	}
	else throw SystemException(Poco::format("cannot create named mutex %s (semget() failed, errno=%d)", fileName, errno), _name);
#endif // defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX)
}

NamedMutexImpl::~NamedMutexImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX)
	sem_close(_sem);
#endif
}

void NamedMutexImpl::lockImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX)
	int err;
	do
	{
		err = sem_wait(_sem);
	}
	while (err && errno == EINTR);
	if (err) throw SystemException("cannot lock named mutex", _name);
#else
	struct sembuf op;
	op.sem_num = 0;
	op.sem_op  = -1;
	op.sem_flg = SEM_UNDO;
	int err;
	do
	{
		err = semop(_semid, &op, 1);
	}
	while (err && errno == EINTR);
	if (err) throw SystemException("cannot lock named mutex", _name);
#endif
}

bool NamedMutexImpl::tryLockImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX)
	return sem_trywait(_sem) == 0;
#else
	struct sembuf op;
	op.sem_num = 0;
	op.sem_op  = -1;
	op.sem_flg = SEM_UNDO | IPC_NOWAIT;
	return semop(_semid, &op, 1) == 0;
#endif
}

void NamedMutexImpl::unlockImpl()
{
#if defined(sun) || defined(__APPLE__) || defined(__osf__) || defined(__QNX__) || defined(_AIX)
	if (sem_post(_sem) != 0)
	   	throw SystemException("cannot unlock named mutex", _name);
#else
	struct sembuf op;
	op.sem_num = 0;
	op.sem_op  = 1;
	op.sem_flg = SEM_UNDO;
	if (semop(_semid, &op, 1) != 0)
	   	throw SystemException("cannot unlock named mutex", _name);
#endif
}

std::string NamedMutexImpl::getFileName()
{
#if defined(sun) || defined(__APPLE__) || defined(__QNX__)
	std::string fn = "/";
#else
	std::string fn = "/tmp/";
#endif
	fn.append(_name);
	fn.append(".mutex");
	return fn;
}

} // namespace Poco


text:
package org.pathvisio.gui.dialogs;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;

/**
 * The basis for a dialog with ok / cancel buttons at the bottom
 *
 * The central panel can have arbitrarily complex contents
 */
public class OkCancelDialog extends JDialog implements ActionListener {
	public static final String OK = "Ok";
	public static final String CANCEL = "Cancel";

	private String exitCode = CANCEL;
	JButton setButton;
	JPanel contentPanel;

	/**
	 * Create a dialog with ok/cancel buttons. A custom content component can
	 * be set using {@link #setDialogComponent(Component)}.
	 * @param frame The frame to base the dialogs location on
	 * @param title The title of the dialog
	 * @param locationComp The component to base the dialogs location on
	 * @param modal Whether the dialog should be modal
	 * @param cancellable Whether to add a cancel button
	 */
	public OkCancelDialog(Frame frame, String title, Component locationComp, boolean modal, boolean cancellable) {
		super(frame, title, modal);
		contentPanel = new JPanel(new BorderLayout());

		JButton cancelButton = new JButton(CANCEL);
		cancelButton.addActionListener(this);

		setButton = new JButton(OK);
		setButton.setActionCommand(OK);
		setButton.addActionListener(this);
		getRootPane().setDefaultButton(setButton);

		JPanel buttonPane = new JPanel();
		buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
		buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		buttonPane.add(Box.createHorizontalGlue());
		if(cancellable) {
			buttonPane.add(cancelButton);
			buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
		}
		buttonPane.add(setButton);

		contentPanel.add(buttonPane, BorderLayout.PAGE_END);
		add(contentPanel);
		pack();
		setLocationRelativeTo(locationComp);

		//Make buttons respond to pressing 'Enter'
		UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);
		KeyStroke esc = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
		contentPanel.registerKeyboardAction(this, CANCEL, esc,JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
	}

	public OkCancelDialog(Frame frame, String title, Component locationComp, boolean modal) {
		this(frame, title, locationComp, modal, true);
	}

	/**
	 * Set the component that contains the dialog contents. Subclasses must
	 * call this method to set custom dialog contents.
	 * @param dialogComponent
	 */
	public final void setDialogComponent(Component dialogComponent) {
		contentPanel.add(dialogComponent, BorderLayout.CENTER);
		invalidate();
	}

	public String getExitCode() {
		return exitCode;
	}

	protected void okPressed() {
		setButton.requestFocus(); //Fix for bug #228
								 //Request focus to allow possible open celleditors
								 //in this dialog to apply the current value
		exitCode = OK;
		setVisible(false);
	}

	protected void cancelPressed() {
		exitCode = CANCEL;
		setVisible(false);
	}

	public void actionPerformed(ActionEvent e) {
		if (OK.equals(e.getActionCommand())) {
			okPressed();
		}
		if(CANCEL.equals(e.getActionCommand())) {
			cancelPressed();
		}
	}
}


text:
var searchData=
[
  ['zeroorderhold',['ZeroOrderHold',['../classdrake_1_1systems_1_1_zero_order_hold.html#a0d112baac097caa5fed5378a07d423ce',1,'drake::systems::ZeroOrderHold']]]
];


text:
static NSString *const DCMDriveControllerProfileName = @"driveController";

static NSString *const DCMDriveControllerProfileAttrMove = @"move";
static NSString *const DCMDriveControllerProfileAttrStop = @"stop";
static NSString *const DCMDriveControllerProfileAttrRotate = @"rotate";
static NSString *const DCMDriveControllerProfileParamAngle = @"angle";
static NSString *const DCMDriveControllerProfileParamSpeed = @"speed";

@implementation TestDriveControllerProfile

- (id) init {
    self = [super init];

    if (self) {

        // API登録(didReceivePostDriveControllerMoveRequest相当)
        NSString *postDriveControllerMoveRequestApiPath = [self apiPath: nil
                                                          attributeName: DCMDriveControllerProfileAttrMove];
        [self addPostPath: postDriveControllerMoveRequestApiPath
                      api:^BOOL(DConnectRequestMessage *request, DConnectResponseMessage *response) {

                          NSString *serviceId = [request serviceId];

                          CheckDID(response, serviceId) {
                              response.result = DConnectMessageResultTypeOk;
                          }

                          return YES;
                      }];

        // API登録(didReceivePutDriveControllerRotateRequest相当)
        NSString *putDriveControllerRotateRequestApiPath = [self apiPath: nil
                                                           attributeName: DCMDriveControllerProfileAttrRotate];
        [self addPutPath: putDriveControllerRotateRequestApiPath
                     api:^BOOL(DConnectRequestMessage *request, DConnectResponseMessage *response) {

                         NSString *serviceId = [request serviceId];

                         CheckDID(response, serviceId) {
                             response.result = DConnectMessageResultTypeOk;
                         }

                         return YES;
                     }];

        // API登録(didReceiveDeleteDriveControllerStopRequest相当)
        NSString *deleteDriveControllerStopRequestApiPath = [self apiPath: nil
                                                            attributeName: DCMDriveControllerProfileAttrStop];
        [self addDeletePath: deleteDriveControllerStopRequestApiPath
                        api:^BOOL(DConnectRequestMessage *request, DConnectResponseMessage *response) {

                            NSString *serviceId = [request serviceId];

                            CheckDID(response, serviceId) {
                                response.result = DConnectMessageResultTypeOk;
                            }

                            return YES;
                        }];
    }

    return self;
}

- (NSString *) profileName {
    return DCMDriveControllerProfileName;
}

@end


text:
package nats

import (
	"github.com/dictyBase/apihelpers/pubsub"
	gnats "github.com/nats-io/go-nats"
)

type natsReply struct {
	conn *gnats.Conn
}

func NewReply(url string, options ...gnats.Option) (pubsub.Reply, error) {
	nc, err := gnats.Connect(url, options...)
	if err != nil {
		return &natsReply{}, err
	}
	return &natsReply{
		conn: nc,
	}, err
}

func (r *natsReply) Publish(subj string, data []byte) error {
	return r.conn.Publish(subj, data)
}

func (r *natsReply) Start(fn pubsub.ReplyFn, subj string) error {
	_, err := r.conn.Subscribe(subj, func(msg *gnats.Msg) {
		r.Publish(msg.Reply, fn(msg.Data))
	})
	if err != nil {
		return err
	}
	if err := r.conn.Flush(); err != nil {
		return err
	}
	if err := r.conn.LastError(); err != nil {
		return err
	}
	return nil
}

func (r *natsReply) Stop() error {
	r.conn.Close()
	return nil
}