text:
package javax.sql;

public interface StatementEventListener
  extends java.util.EventListener
{
  // Methods

  @com.francetelecom.rd.stubs.annotation.CallBack("statementEventListener")
  public void statementClosed(StatementEvent arg1);
  public void statementErrorOccurred(StatementEvent arg1);
}

redpajama_set_name: RedPajamaGithub


text:
package com.homer.receiver;

import com.homer.app.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * @author 	sunboy_2050
 * @date		2012-03-16
 * @blog		http://blog.csdn.net/sunboy_2050/
 */

public class PlayMusicRecevicerActivity extends Activity implements OnClickListener {

	private Button playBtn;
	private Button stopBtn;
	private Button pauseBtn;
	private Button exitBtn;
	private Button closeBtn;

	private Intent intent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.music_receiver);

		this.getActionBar().setDisplayHomeAsUpEnabled(true);

		playBtn = (Button) findViewById(R.id.play);
		stopBtn = (Button) findViewById(R.id.stop);
		pauseBtn = (Button) findViewById(R.id.pause);
		exitBtn = (Button) findViewById(R.id.exit);
		closeBtn = (Button) findViewById(R.id.close);

		playBtn.setOnClickListener(this);
		stopBtn.setOnClickListener(this);
		pauseBtn.setOnClickListener(this);
		exitBtn.setOnClickListener(this);
		closeBtn.setOnClickListener(this);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		int op = -1;
		 intent = new Intent("com.homer.receiver.musicReceiver");

		switch (v.getId()) {
		case R.id.play:								// play music
			op = 1;
			break;
		case R.id.stop:								// stop music
			op = 2;
			break;
		case R.id.pause:							// pause music
			op = 3;
			break;
		case R.id.close:							// close activity
			this.finish();
			break;
		case R.id.exit:								// process by MusicReceiver
			op = 4;
			this.finish();
			break;
		}

		Bundle bundle = new Bundle();
		bundle.putInt("op", op);
		intent.putExtras(bundle);

		 sendBroadcast(intent);						// sendBroadcast
	}

	@Override
	public void onDestroy(){
		super.onDestroy();

		if(intent != null){
			stopService(intent);
		}
	}
}


text:
require('./setup-editor');
require('./setup-enzyme');
require('./setup-jsdom');


text:
using Evol.TMovie.Domain.Commands.Dto;
using Evol.TMovie.Domain.Models.AggregateRoots;
using Evol.Domain.Commands;

namespace Evol.TMovie.Domain.Commands
{
    public class MovieCreateCommand : Command
    {
        public MovieCreateDto Input { get; set; }
    }
}


text:
        {{option}}

LOGOUT


text:
using ::testing::_;
using ::testing::InSequence;
using ::testing::StrictMock;

namespace vr {

namespace {
constexpr float kFontHeightMeters = 0.050f;
}

class TextInputSceneTest : public UiTest {
 public:
  void SetUp() override {
    UiTest::SetUp();
    CreateScene(kNotInWebVr);

    // Make test text input.
    text_input_delegate_ =
        std::make_unique<StrictMock<MockTextInputDelegate>>();
    edited_text_ = std::make_unique<EditedText>(u"asdfg");
    auto text_input = CreateTextInput(1, model_, edited_text_.get(),
                                      text_input_delegate_.get());
    text_input_ = text_input.get();
    scene_->AddUiElement(k2dBrowsingForeground, std::move(text_input));
    EXPECT_TRUE(AdvanceFrame());
  }

 protected:
  raw_ptr<TextInput> text_input_;
  std::unique_ptr<StrictMock<MockTextInputDelegate>> text_input_delegate_;
  std::unique_ptr<EditedText> edited_text_;
  testing::Sequence in_sequence_;

 private:
  std::unique_ptr<TextInput> CreateTextInput(
      float font_height_meters,
      Model* model,
      EditedText* text_input_model,
      TextInputDelegate* text_input_delegate) {
    auto text_input = std::make_unique<TextInput>(
        font_height_meters,
        base::BindRepeating(
            [](EditedText* model, const EditedText& text_input_info) {
              *model = text_input_info;
            },
            base::Unretained(text_input_model)));
    EventHandlers event_handlers;
    event_handlers.focus_change = base::BindRepeating(
        [](Model* model, TextInput* text_input, EditedText* text_input_info,
           bool focused) {
          if (focused) {
            model->editing_input = true;
            text_input->UpdateInput(*text_input_info);
          } else {
            model->editing_input = false;
          }
        },
        base::Unretained(model), base::Unretained(text_input.get()),
        base::Unretained(text_input_model));
    text_input->SetSize(1.0f, 0.1f);
    text_input->set_event_handlers(event_handlers);
    text_input->SetDrawPhase(kPhaseNone);
    text_input->SetTextInputDelegate(text_input_delegate);
    text_input->AddBinding(std::make_unique<Binding<EditedText>>(
        VR_BIND_LAMBDA([](EditedText* info) { return *info; },
                       base::Unretained(text_input_model)),
        VR_BIND_LAMBDA([](TextInput* e,
                          const EditedText& value) { e->UpdateInput(value); },
                       base::Unretained(text_input.get()))));
    return text_input;
  }
};

TEST_F(TextInputSceneTest, InputFieldFocus) {
  // Set mock delegates.
  auto* kb = static_cast<Keyboard*>(scene_->GetUiElementByName(kKeyboard));
  auto kb_delegate = std::make_unique<StrictMock<MockKeyboardDelegate>>();
  EXPECT_CALL(*kb_delegate, HideKeyboard()).InSequence(in_sequence_);
  kb->SetKeyboardDelegate(kb_delegate.get());

  // Clicking on the text field should request focus.
  EXPECT_CALL(*text_input_delegate_, RequestFocus(_)).InSequence(in_sequence_);
  text_input_->OnButtonUp(gfx::PointF(), base::TimeTicks());

  // Focusing on an input field should show the keyboard and tell the delegate
  // the field's content.
  EXPECT_CALL(*text_input_delegate_, UpdateInput(edited_text_->current))
      .InSequence(in_sequence_);
  text_input_->OnFocusChanged(true);
  EXPECT_CALL(*kb_delegate, ShowKeyboard()).InSequence(in_sequence_);
  EXPECT_CALL(*kb_delegate, OnBeginFrame()).InSequence(in_sequence_);
  EXPECT_CALL(*kb_delegate, SetTransform(_)).InSequence(in_sequence_);
  EXPECT_TRUE(AdvanceFrame());
  EXPECT_EQ(*edited_text_, text_input_->edited_text());

  // Focusing out of an input field should hide the keyboard.
  text_input_->OnFocusChanged(false);
  EXPECT_CALL(*kb_delegate, HideKeyboard()).InSequence(in_sequence_);
  EXPECT_CALL(*kb_delegate, OnBeginFrame()).InSequence(in_sequence_);
  EXPECT_CALL(*kb_delegate, SetTransform(_)).InSequence(in_sequence_);
  EXPECT_TRUE(AdvanceFrame());
  EXPECT_EQ(*edited_text_, text_input_->edited_text());
}

TEST_F(TextInputSceneTest, InputFieldEdit) {
  // UpdateInput should not be called if the text input doesn't have focus.
  EXPECT_CALL(*text_input_delegate_, UpdateInput(_))
      .Times(0)
      .InSequence(in_sequence_);
  text_input_->OnFocusChanged(false);

  // Focus on input field.
  EXPECT_CALL(*text_input_delegate_, UpdateInput(_)).InSequence(in_sequence_);
  text_input_->OnFocusChanged(true);

  // Edits from the keyboard update the underlying text input  model.
  EXPECT_CALL(*text_input_delegate_, UpdateInput(_)).InSequence(in_sequence_);
  EditedText info(u"asdfgh");
  text_input_->OnInputEdited(info);
  EXPECT_TRUE(AdvanceFrame());
  EXPECT_EQ(info, *edited_text_);
}

TEST_F(TextInputSceneTest, ClickOnTextGrabsFocus) {
  EXPECT_CALL(*text_input_delegate_, RequestFocus(_));
  text_input_->get_text_element()->OnButtonUp({0, 0}, base::TimeTicks());
}

TEST(TextInputTest, ControllerInteractionsSentToDelegate) {
  auto keyboard = std::make_unique<Keyboard>();
  auto kb_delegate = std::make_unique<StrictMock<MockKeyboardDelegate>>();
  testing::Sequence s;
  EXPECT_CALL(*kb_delegate, HideKeyboard()).InSequence(s);
  keyboard->SetKeyboardDelegate(kb_delegate.get());

  EXPECT_CALL(*kb_delegate, OnHoverEnter(_)).InSequence(s);
  EXPECT_CALL(*kb_delegate, OnHoverLeave()).InSequence(s);
  EXPECT_CALL(*kb_delegate, OnHoverMove(_)).InSequence(s);
  EXPECT_CALL(*kb_delegate, OnButtonDown(_)).InSequence(s);
  EXPECT_CALL(*kb_delegate, OnButtonUp(_)).InSequence(s);
  gfx::PointF p;
  keyboard->OnHoverEnter(p, base::TimeTicks());
  keyboard->OnHoverLeave(base::TimeTicks());
  keyboard->OnHoverMove(p, base::TimeTicks());
  keyboard->OnButtonDown(p, base::TimeTicks());
  keyboard->OnButtonUp(p, base::TimeTicks());
}

TEST(TextInputTest, HintText) {
  UiScene scene;

  auto instance = std::make_unique<TextInput>(
      kFontHeightMeters, TextInput::OnInputEditedCallback());
  EventHandlers event_handlers;
  event_handlers.focus_change = TextInput::OnFocusChangedCallback();
  instance->set_event_handlers(event_handlers);
  instance->SetName(kOmniboxTextField);
  instance->SetSize(1, 0);
  TextInput* element = instance.get();
  scene.root_element().AddChild(std::move(instance));

  // Text field is empty, so we should be showing hint text.
  scene.OnBeginFrame(base::TimeTicks(), kStartHeadPose);
  EXPECT_GT(element->get_hint_element()->GetTargetOpacity(), 0);

  // When text enters the field, the hint should disappear.
  EditedText info(u"text");
  element->UpdateInput(info);
  scene.OnBeginFrame(base::TimeTicks(), kStartHeadPose);
  EXPECT_EQ(element->get_hint_element()->GetTargetOpacity(), 0);
}

TEST(TextInputTest, CursorBlinking) {
  UiScene scene;
  auto instance = std::make_unique<TextInput>(
      kFontHeightMeters, TextInput::OnInputEditedCallback());
  EventHandlers event_handlers;
  event_handlers.focus_change = TextInput::OnFocusChangedCallback();
  instance->set_event_handlers(event_handlers);
  instance->SetName(kOmniboxTextField);
  instance->SetSize(1, 0);
  TextInput* element = instance.get();
  scene.root_element().AddChild(std::move(instance));

  // The cursor should not be blinking or visible.
  float initial = element->get_cursor_element()->GetTargetOpacity();
  EXPECT_EQ(initial, 0.f);
  for (int ms = 0; ms <= 2000; ms += 100) {
    scene.OnBeginFrame(gfx::MsToTicks(ms), kStartHeadPose);
    EXPECT_EQ(initial, element->get_cursor_element()->GetTargetOpacity());
  }

  // When focused, the cursor should start blinking.
  element->OnFocusChanged(true);
  initial = element->get_cursor_element()->GetTargetOpacity();
  bool toggled = false;
  for (int ms = 0; ms <= 2000; ms += 100) {
    scene.OnBeginFrame(gfx::MsToTicks(ms), kStartHeadPose);
    if (initial != element->get_cursor_element()->GetTargetOpacity())
      toggled = true;
  }
  EXPECT_TRUE(toggled);

  // With a selection, the cursor should not be blinking or visible.
  EditedText info(u"text");
  info.current.selection_start = 0;
  info.current.selection_end = info.current.text.size();
  element->UpdateInput(info);
  EXPECT_EQ(0.f, element->get_cursor_element()->GetTargetOpacity());
  for (int ms = 0; ms <= 2000; ms += 100) {
    scene.OnBeginFrame(gfx::MsToTicks(ms), kStartHeadPose);
    EXPECT_EQ(0.f, element->get_cursor_element()->GetTargetOpacity());
  }
}

// TODO(cjgrant): Have this test, and others similar, check the actual position
// of the cursor element.  To make this work, the OnBeginFrame logic needs to be
// updated to perform more of the measurement and layout steps in a test
// environment.  As of now, much of this is skipped due to lack of a GL context.
TEST(TextInputTest, CursorPositionUpdatesOnKeyboardInput) {
  auto element = std::make_unique<TextInput>(
      kFontHeightMeters, TextInput::OnInputEditedCallback());
  EventHandlers event_handlers;
  event_handlers.focus_change = TextInput::OnFocusChangedCallback();
  element->set_event_handlers(event_handlers);
  element->SetSize(1, 0);

  EditedText info(u"text");
  info.current.selection_start = 0;
  info.current.selection_end = 0;
  element->UpdateInput(info);
  element->get_text_element()->PrepareToDrawForTest();
  int x1 = element->get_text_element()->GetRawCursorBounds().x();

  info.current.selection_start = 1;
  info.current.selection_end = 1;
  element->UpdateInput(info);
  element->get_text_element()->PrepareToDrawForTest();
  int x2 = element->get_text_element()->GetRawCursorBounds().x();

  EXPECT_LT(x1, x2);
}

TEST(TextInputTest, CursorPositionUpdatesOnClicks) {
  auto element = std::make_unique<TextInput>(
      kFontHeightMeters, TextInput::OnInputEditedCallback());
  EventHandlers event_handlers;
  event_handlers.focus_change = TextInput::OnFocusChangedCallback();
  element->set_event_handlers(event_handlers);
  element->SetSize(1, 0);

  EditedText info(u"text");
  element->UpdateInput(info);
  element->get_text_element()->PrepareToDrawForTest();

  // Click on the left edge of the field.
  element->OnButtonDown(gfx::PointF(0.0, 0.5), base::TimeTicks());
  element->OnButtonUp(gfx::PointF(0.0, 0.5), base::TimeTicks());
  element->get_text_element()->PrepareToDrawForTest();
  auto x1 = element->get_text_element()->GetRawCursorBounds().x();

  // Click on the right edge of the field.
  element->OnButtonDown(gfx::PointF(1.0, 0.5), base::TimeTicks());
  element->OnButtonUp(gfx::PointF(1.0, 0.5), base::TimeTicks());
  element->get_text_element()->PrepareToDrawForTest();
  auto x2 = element->get_text_element()->GetRawCursorBounds().x();

  EXPECT_EQ(x1, 0);
  EXPECT_GT(x2, 0);

  // Set a selection and ensure that a click clears it.
  info.current.selection_start = 0;
  info.current.selection_end = info.current.text.size();
  element->UpdateInput(info);
  EXPECT_GT(element->edited_text().current.SelectionSize(), 0u);
  element->OnButtonDown(gfx::PointF(0.5, 0.5), base::TimeTicks());
  element->OnButtonUp(gfx::PointF(0.5, 0.5), base::TimeTicks());
  EXPECT_EQ(element->edited_text().current.SelectionSize(), 0u);
}

TEST(TextInputTest, TextSelectionUpdatesOnTouchMove) {
  auto element = std::make_unique<TextInput>(
      kFontHeightMeters, TextInput::OnInputEditedCallback());
  element->SetSize(1.0, 0);

  EditedText info(TextInputInfo(
      u"this is a long text with the cursor at the beginning", 0, 0));
  element->UpdateInput(info);
  element->get_text_element()->PrepareToDrawForTest();
  EXPECT_EQ(element->edited_text().current.SelectionSize(), 0u);

  // Click on the left edge of the field.
  element->OnButtonDown(gfx::PointF(0.0, 0.5), base::TimeTicks());
  EXPECT_EQ(element->edited_text().current.selection_start, 0);
  EXPECT_EQ(element->edited_text().current.selection_end, 0);

  element->OnTouchMove(gfx::PointF(0.5, 0.5), base::TimeTicks());
  EXPECT_EQ(element->edited_text().current.selection_start, 0);
  auto end1 = element->edited_text().current.selection_end;
  EXPECT_GT(end1, 0);

  // Move to the right edge of the field.
  element->OnTouchMove(gfx::PointF(1.0, 0.5), base::TimeTicks());
  EXPECT_EQ(element->edited_text().current.selection_start, 0);
  auto end2 = element->edited_text().current.selection_end;
  EXPECT_GT(end2, end1);

  // Move past the right edge of the field and release.
  element->OnTouchMove(gfx::PointF(2.0, 0.5), base::TimeTicks());
  element->OnButtonUp(gfx::PointF(2.0, 0.5), base::TimeTicks());
  auto end3 = element->edited_text().current.selection_end;
  EXPECT_GT(end3, end2);
}

}  // namespace vr


text:
package me.chanjar.mockito;

import me.chanjar.common.Bar;
import me.chanjar.common.FooImpl;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.Collections;

import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;

public class MockitoTest {

  @Mock
  private Bar bar;

  @InjectMocks
  private FooImpl foo;

  @BeforeMethod(alwaysRun = true)
  public void initMock() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testCheckCodeDuplicate() throws Exception {

    when(bar.getAllCodes()).thenReturn(Collections.singleton("123"));
    assertEquals(foo.checkCodeDuplicate("123"), true);

  }

}


text:
package com.threerings.s3.client;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;

/**
 * A representation of a (locally file-backed) object stored in S3.
 */
public class S3FileObject extends S3Object {

    /**
     * Instantiate an S3 file-backed object with the given key.
     * @param key S3 object key.
     * @param file File backing.
     */
    public S3FileObject(String key, File file)
        throws FileNotFoundException
    {
        super(key);
        _file = file;
    }

    /**
     * Instantiate an S3 file-backed object with the given key.
     * @param key S3 object key.
     * @param file File backing.
     * @param mimeType Object's MIME type.
     */
    public S3FileObject(String key, File file, String mimeType)
        throws FileNotFoundException
    {
        super(key, mimeType);
        _file = file;
    }

    @Override // From S3Object
    public InputStream getInputStream ()
        throws S3ClientException
    {
        try {
            return new FileInputStream(_file);
        } catch (FileNotFoundException fnf) {
            throw new S3ClientException("File was not found.", fnf);
        }
    }

    @Override // From S3Object
    public byte[] getMD5 ()
        throws S3ClientException
    {
         InputStream input;
         MessageDigest md;
         byte data[];
         int nbytes;

         // Initialize
         try {
             md = MessageDigest.getInstance("md5");
         } catch (NoSuchAlgorithmException nsa) {
             // If MD5 isn't available, we're in trouble.
             throw new RuntimeException(nsa);
         }

         input = getInputStream();
         data = new byte[1024];

         // Compute the digest
         try {
             while ((nbytes = input.read(data)) > 0) {
                 md.update(data, 0, nbytes);
             }
         } catch (IOException ioe) {
             throw new S3ClientException("Failure reading input file: " + ioe, ioe);
         }
         return md.digest();
    }

    @Override // From S3Object
    public long lastModified () {
        return _file.lastModified();
    }

    @Override // From S3Object
    public long length () {
        return _file.length();
    }

    /** File path. */
    private final File _file;
}


text:
/* @test
 * @bug 4607272 6842687
 * @summary Unit test for AsynchronousChannelGroup
 * @build Restart
 * @run main/othervm -XX:-UseVMInterruptibleIO Restart
 */

import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.io.IOException;

/**
 * Exercise replacement of threads in the thread pool when completion handlers
 * terminate due to errors or runtime exceptions.
 */

public class Restart {
    static final Random rand = new Random();

    public static void main(String[] args) throws Exception {
        // thread group for thread pools
        final ThreadGroup tg = new ThreadGroup("test");

        // keep track of the number of threads that terminate
        final AtomicInteger exceptionCount = new AtomicInteger(0);
        final Thread.UncaughtExceptionHandler ueh =
            new Thread.UncaughtExceptionHandler() {
                public void uncaughtException(Thread t, Throwable e) {
                    exceptionCount.incrementAndGet();
                }
            };
        ThreadFactory factory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(tg, r);
                t.setUncaughtExceptionHandler(ueh);
                return t;
            }
        };

        // group with fixed thread pool
        int nThreads = 1 + rand.nextInt(4);
        AsynchronousChannelGroup group =
            AsynchronousChannelGroup.withFixedThreadPool(nThreads, factory);
        testRestart(group, 100);
        group.shutdown();

        // group with custom thread pool
        ExecutorService pool = Executors.newCachedThreadPool(factory);
        group = AsynchronousChannelGroup.withCachedThreadPool(pool, rand.nextInt(5));
        testRestart(group, 100);
        group.shutdown();

        // give time for threads to terminate
        Thread.sleep(3000);
        int actual = exceptionCount.get();
        if (actual != 200)
            throw new RuntimeException(actual + " exceptions, expected: " + 200);
    }

    static void testRestart(AsynchronousChannelGroup group, int count)
        throws Exception
    {
        AsynchronousServerSocketChannel listener =
            AsynchronousServerSocketChannel.open(group)
                .bind(new InetSocketAddress(0));

        for (int i=0; i<count; i++) {
            final CountDownLatch latch = new CountDownLatch(1);

            listener.accept((Void)null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
                public void completed(AsynchronousSocketChannel ch, Void att) {
                    try {
                        ch.close();
                    } catch (IOException ignore) { }

                    latch.countDown();

                    // throw error or runtime exception
                    if (rand.nextBoolean()) {
                        throw new Error();
                    } else {
                        throw new RuntimeException();
                    }
                }
                public void failed(Throwable exc, Void att) {
                }
            });

            // establish loopback connection which should cause completion
            // handler to be invoked.
            int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
            AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();
            InetAddress lh = InetAddress.getLocalHost();
            ch.connect(new InetSocketAddress(lh, port)).get();
            ch.close();

            // wait for handler to be invoked
            latch.await();
        }

        // clean-up
        listener.close();
    }
}


text:
{-# LANGUAGE BangPatterns  #-}
{-# LANGUAGE CPP           #-}
{-# LANGUAGE MagicHash     #-}
{-# LANGUAGE UnboxedTuples #-}

module Data.RingBuffer.Sequence
    ( Sequence
    , mkSequence
    , readSequence
    , writeSequence
    , casSequence
    , minimumSequence
    )
where

import Data.Atomics.Internal
import Data.List              (foldl')
#if MIN_VERSION_base(4,7,0)
import           GHC.Base           hiding ((==#))
import qualified GHC.PrimopWrappers as GPW
#else
import GHC.Base
#endif

-- GHC 7.8 changed some primops
#if MIN_VERSION_base(4,7,0)
(==#) :: Int# -> Int# -> Bool
(==#) x y = case x GPW.==# y of { 0# -> False; _ -> True }
#endif

#include "MachDeps.h"
#ifndef SIZEOF_HSINT
#define SIZEOF_HSINT  INT_SIZE_IN_BYTES
#endif

data Sequence = Sequence (MutableByteArray# RealWorld)

mkSequence :: IO Sequence
mkSequence = do
    raw <- mkRaw
    writeSequence raw (-1)
    return raw
{-# INLINABLE mkSequence #-}

mkRaw :: IO Sequence
mkRaw = IO $ \ s ->
    case newPinnedByteArray# size s of
        (# s', arr #) -> (# s', Sequence arr #)
  where
    !(I# size) = SIZEOF_HSINT * 15
{-# INLINABLE mkRaw #-}

readSequence :: Sequence -> IO Int
readSequence (Sequence arr) = IO $ \ s ->
    case readIntArray# arr 7# s of
        (# s', i #) -> (# s', I# i #)
{-# INLINABLE readSequence #-}

writeSequence :: Sequence -> Int -> IO ()
writeSequence (Sequence arr) (I# i) = IO $ \ s ->
    case writeIntArray# arr 7# i s of
        s' -> (# s', () #)
{-# INLINABLE writeSequence #-}

casSequence :: Sequence -> Int -> Int -> IO Bool
casSequence (Sequence arr#) (I# old#) (I# new#) = IO $ \ s1# ->
    let (# s2#, res# #) = casIntArray# arr# 7# old# new# s1#
     in case res# ==# old# of
        False -> (# s2#, False #)
        True  -> (# s2#, True  #)
{-# INLINABLE casSequence #-}

minimumSequence :: [Sequence] -> Int -> IO Int
minimumSequence [] def = return def
minimumSequence ss def = return . foldl' min def =<< mapM readSequence ss
{-# INLINABLE minimumSequence #-}

-- vim: set ts=4 sw=4 et:


text:
require 'spec_helper'

describe "Faye browser javascript" do

  it "should be served by asset pipeline" do
    get '/assets/faye.js'
    response.status.should be(200)
  end

  it "should match Faye versions" do
    get '/assets/faye.js'
    response.body.should include("VERSION:'#{Faye::VERSION}'")
  end
end


text:
package com.linecorp.armeria.client.endpoint.dns;

import static io.netty.handler.codec.dns.DnsRecordType.A;
import static io.netty.handler.codec.dns.DnsRecordType.AAAA;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Nullable;

import com.google.common.collect.ImmutableMap;

import com.linecorp.armeria.common.CommonPools;
import com.linecorp.armeria.internal.common.util.TransportType;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.dns.DatagramDnsQuery;
import io.netty.handler.codec.dns.DatagramDnsQueryDecoder;
import io.netty.handler.codec.dns.DatagramDnsResponse;
import io.netty.handler.codec.dns.DatagramDnsResponseEncoder;
import io.netty.handler.codec.dns.DefaultDnsRawRecord;
import io.netty.handler.codec.dns.DnsQuestion;
import io.netty.handler.codec.dns.DnsRecord;
import io.netty.handler.codec.dns.DnsResponse;
import io.netty.handler.codec.dns.DnsResponseCode;
import io.netty.handler.codec.dns.DnsSection;
import io.netty.util.NetUtil;
import io.netty.util.ReferenceCountUtil;

public final class TestDnsServer implements AutoCloseable {

    public static DnsRecord newAddressRecord(String name, String ipAddr) {
        return newAddressRecord(name, ipAddr, 60);
    }

    public static DnsRecord newAddressRecord(String name, String ipAddr, long ttl) {
        return new DefaultDnsRawRecord(
                name, NetUtil.isValidIpV4Address(ipAddr) ? A : AAAA,
                ttl, Unpooled.wrappedBuffer(NetUtil.createByteArrayFromIpAddressString(ipAddr)));
    }

    private final Channel channel;
    private volatile Map<DnsQuestion, DnsResponse> responses;

    public TestDnsServer(Map<DnsQuestion, DnsResponse> responses) {
        this(responses, null);
    }

    public TestDnsServer(Map<DnsQuestion, DnsResponse> responses,
                         @Nullable ChannelInboundHandlerAdapter beforeDnsServerHandler) {
        this.responses = ImmutableMap.copyOf(responses);

        final Bootstrap b = new Bootstrap();
        b.channel(TransportType.datagramChannelType(CommonPools.workerGroup()));
        b.group(CommonPools.workerGroup());
        b.handler(new ChannelInitializer() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                final ChannelPipeline p = ch.pipeline();
                p.addLast(new DatagramDnsQueryDecoder());
                p.addLast(new DatagramDnsResponseEncoder());
                if (beforeDnsServerHandler != null) {
                    p.addLast(beforeDnsServerHandler);
                }
                p.addLast(new DnsServerHandler());
            }
        });

        channel = b.bind(NetUtil.LOCALHOST, 0).syncUninterruptibly().channel();
    }

    public InetSocketAddress addr() {
        return (InetSocketAddress) channel.localAddress();
    }

    public void setResponses(Map<DnsQuestion, DnsResponse> responses) {
        this.responses.values().forEach(DnsResponse::release);
        this.responses = ImmutableMap.copyOf(responses);
    }

    @Override
    public void close() {
        if (!channel.isOpen()) {
            return;
        }

        channel.close().syncUninterruptibly();
        responses.values().forEach(DnsResponse::release);
    }

    private class DnsServerHandler extends SimpleChannelInboundHandler<DatagramDnsQuery> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramDnsQuery query) {
            final DnsQuestion question = query.recordAt(DnsSection.QUESTION, 0);
            boolean responded = false;
            for (Entry<DnsQuestion, DnsResponse> e : responses.entrySet()) {
                final DnsQuestion q = e.getKey();
                final DnsResponse r = e.getValue();
                if (question.dnsClass() == q.dnsClass() &&
                    question.name().equals(q.name()) &&
                    question.type() == q.type()) {

                    final DnsResponse res = new DatagramDnsResponse(
                            null, query.sender(), query.id(), query.opCode(), r.code());

                    if (r.count(DnsSection.QUESTION) == 0) {
                        res.addRecord(DnsSection.QUESTION, question);
                    }
                    for (DnsSection section : DnsSection.values()) {
                        final int count = r.count(section);
                        for (int i = 0; i < count; i++) {
                            res.addRecord(section, ReferenceCountUtil.retain(r.recordAt(section, i)));
                        }
                    }

                    ctx.writeAndFlush(res);
                    responded = true;
                }
            }

            if (!responded) {
                final DnsResponse res = new DatagramDnsResponse(
                        null, query.sender(), query.id(), query.opCode(), DnsResponseCode.NXDOMAIN);
                res.addRecord(DnsSection.QUESTION, question);
                ctx.writeAndFlush(res);
            }
        }
    }
}


text:
package org.spongepowered.api.data.manipulators.entities;

import org.spongepowered.api.data.manipulators.SingleValueData;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.living.animal.Horse;
import org.spongepowered.api.entity.living.animal.Pig;
import org.spongepowered.api.item.inventory.ItemStack;

/**
 * Signifies that a {@link Entity} is currently "saddled". Usually applicable
 * to {@link Pig}s and {@link Horse}s.
 */
public interface SaddleData extends SingleValueData<ItemStack, SaddleData> {

    /**
     * Gets the current saddle this horse is equipped with.
     *
     *
A saddled horse is player rideable. Not all horses can be saddled.

     *
     * @return The saddle, if available
     */
    ItemStack getSaddle();

    /**
     * Sets the horse to be equipped with the given saddle.
     *
     *
A saddled horse is player rideable. Not all horses can be saddled.

     *
     * @param itemStack The saddle item
     * @return This instance, for chaining
     */
    SaddleData setSaddle(ItemStack itemStack);
}


text:
struct SequencePointInfo
{
    int lineNumber, ilOffset;
    WCHAR* fileName;
};

struct LocalVarInfo
{
    int startOffset;
    int endOffset;
    WCHAR *name;
};

struct MethodDebugInfo
{
    SequencePointInfo* points;
    int size;
    LocalVarInfo* locals;
    int localsSize;

    MethodDebugInfo(int numPoints, int numLocals);
    ~MethodDebugInfo();
};

typedef BOOL (CALLBACK *GetInfoForMethodDelegate)(const char*, unsigned int, MethodDebugInfo& methodDebugInfo);
extern GetInfoForMethodDelegate getInfoForMethodDelegate;

#endif // !__GDBJITHELPERS_H__


text:
package ibis.ipl.impl.stacking.dummy;

import ibis.ipl.SendPort;
import ibis.ipl.WriteMessage;

import java.io.IOException;
import java.nio.ByteBuffer;

public class StackingWriteMessage implements WriteMessage {

    final WriteMessage base;
    final StackingSendPort port;

    public StackingWriteMessage(WriteMessage base, StackingSendPort port) {
        this.base = base;
        this.port = port;
    }

    public long bytesWritten() throws IOException {
        return base.bytesWritten();
    }

    public int capacity() throws IOException {
        return base.capacity();
    }

    public int remaining() throws IOException {
        return base.remaining();
    }

    public long finish() throws IOException {
        return base.finish();
    }

    public void finish(IOException e) {
        base.finish(e);
    }

    public SendPort localPort() {
        return port;
    }

    public void reset() throws IOException {
        base.reset();
    }

    public int send() throws IOException {
        return base.send();
    }

    public void flush() throws IOException {
        base.flush();
    }

    public void sync(int ticket) throws IOException {
        base.sync(ticket);
    }

    public void writeArray(boolean[] val, int off, int len) throws IOException {
        base.writeArray(val, off, len);
    }

    public void writeArray(boolean[] val) throws IOException {
        base.writeArray(val);
    }

    public void writeArray(byte[] val, int off, int len) throws IOException {
        base.writeArray(val, off, len);
    }

    public void writeArray(byte[] val) throws IOException {
        base.writeArray(val);
    }

    public void writeArray(char[] val, int off, int len) throws IOException {
        base.writeArray(val, off, len);
    }

    public void writeArray(char[] val) throws IOException {
        base.writeArray(val);
    }

    public void writeArray(double[] val, int off, int len) throws IOException {
        base.writeArray(val, off, len);
    }

    public void writeArray(double[] val) throws IOException {
        base.writeArray(val);
    }

    public void writeArray(float[] val, int off, int len) throws IOException {
        base.writeArray(val, off, len);
    }

    public void writeArray(float[] val) throws IOException {
        base.writeArray(val);
    }

    public void writeArray(int[] val, int off, int len) throws IOException {
        base.writeArray(val, off, len);
    }

    public void writeArray(int[] val) throws IOException {
        base.writeArray(val);
    }

    public void writeArray(long[] val, int off, int len) throws IOException {
        base.writeArray(val, off, len);
    }

    public void writeArray(long[] val) throws IOException {
        base.writeArray(val);
    }

    public void writeArray(Object[] val, int off, int len) throws IOException {
        base.writeArray(val, off, len);
    }

    public void writeArray(Object[] val) throws IOException {
        base.writeArray(val);
    }

    public void writeArray(short[] val, int off, int len) throws IOException {
        base.writeArray(val, off, len);
    }

    public void writeArray(short[] val) throws IOException {
        base.writeArray(val);
    }

    public void writeBoolean(boolean val) throws IOException {
        base.writeBoolean(val);
    }

    public void writeByte(byte val) throws IOException {
        base.writeByte(val);
    }

    public void writeChar(char val) throws IOException {
        base.writeChar(val);
    }

    public void writeDouble(double val) throws IOException {
        base.writeDouble(val);
    }

    public void writeFloat(float val) throws IOException {
        base.writeFloat(val);
    }

    public void writeInt(int val) throws IOException {
        base.writeInt(val);
    }

    public void writeLong(long val) throws IOException {
        base.writeLong(val);
    }

    public void writeObject(Object val) throws IOException {
        base.writeObject(val);
    }

    public void writeShort(short val) throws IOException {
        base.writeShort(val);
    }

    public void writeString(String val) throws IOException {
        base.writeString(val);
    }

    public void writeByteBuffer(ByteBuffer value) throws IOException {
	base.writeByteBuffer(value);
    }

}


text:
using CodeHub.Helpers;
using System;
using Windows.UI.Xaml.Data;

namespace CodeHub.Converters
{
	class TimeAgoConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, string language)
		{
			if (value == null)
			{
				return null;
			}

			var dt = DateTime.Parse(value.ToString());
			return GlobalHelper.ConvertDateToTimeAgoFormat(dt);
		}

		public object ConvertBack(object value, Type targetType, object parameter, string language)
			=> throw new NotSupportedException();
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oyosoft.AgenceImmobiliere.Core.DataAccess;
using Oyosoft.AgenceImmobiliere.Core.Model;
using Oyosoft.AgenceImmobiliere.Core.Service;
using Oyosoft.AgenceImmobiliere.Core.Tools;

namespace Oyosoft.AgenceImmobiliere.WcfService.Operations
{
    internal static class Synchro
    {
        internal async static Task<OperationResult<SynchroList>> LireElementsASynchroniser(Connection connection, DateTime? date = null, params object[] nonUtilise)
        {
            OperationResult<SynchroList> resultat = new OperationResult<SynchroList>();

            // Chargement des paramètres
            if (date == null)
            {
                Manager.ReadURIParameter("date", out date);
            }

            // Lecture de la liste des éléments à synchroniser
            ErrorsList errors = new ErrorsList();
            resultat.Result = await connection.SelectSynchronize(date);
            errors.AddRange(connection.Errors);
            if (resultat.Result == null || !errors.IsEmpty)
            {
                await Manager.ManageError(resultat, errors);
                return resultat;
            }

            resultat.Success = resultat.Errors.IsEmpty;

            return resultat;
        }
        internal async static Task<OperationResult> SynchroniserElements(Connection connection, SynchroList elements, params object[] nonUtilise)
        {
            OperationResult resultat = new OperationResult();

            // Chargement des paramètres
            if (elements == null)
            {
                Manager.ReadURIParameter("elements", out elements);
            }

            // Exécution de la synchro
            ErrorsList errors = new ErrorsList();
            await connection.Synchronize(elements, false);
            errors.AddRange(connection.Errors);
            if (!errors.IsEmpty)
            {
                await Manager.ManageError(resultat, errors);
                return resultat;
            }

            resultat.Success = resultat.Errors.IsEmpty;

            return resultat;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <EditText
        android:id="@+id/edit_text"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:text="@string/default_game_name"
        android:selectAllOnFocus="true"
        android:layout_height="wrap_content"/>

</LinearLayout>


text:
<?xml version="1.0" encoding="UTF-8" ?>

<CodeXL>
    <Tests>
	        <TestResultsDirectory>GoldMasters_APPSDK_2_9</TestResultsDirectory>
        <LogFilesDirectory>C:\TEMP\testResults\</LogFilesDirectory>
		<Test>
            <ExecutablePath>samples\opencl\bin\x86\MatrixMultiplication.exe</ExecutablePath>
            <WorkingDirectory>samples\opencl\bin\x86</WorkingDirectory>
            <TestName>MatrixMultiplication_LocalsTest</TestName>
            <TestType>LocalsTest</TestType>
            <Kernels>
                <Kernel>
                    <KernelName>mmmKernel</KernelName>
					<WorkItemId>0,0,0</WorkItemId>
					<KernelLocals>
						<LocalsInLine lineNumber="30"></LocalsInLine>
						<LocalsInLine lineNumber="33"></LocalsInLine>
						<LocalsInLine lineNumber="34"></LocalsInLine>
						<LocalsInLine lineNumber="35"></LocalsInLine>
						<LocalsInLine lineNumber="36"></LocalsInLine>
					</KernelLocals>
                </Kernel>
            </Kernels>
        </Test>
	</Tests>
</CodeXL>


text:
#lightbulb {
  font-size: 100px;
  display: block;
  text-align: center;
}

h1 {
  padding: 0;
  margin: 10px 0;
}

.chat-user-avatar {
  font-size: 40px;
  background: #ccc;
  padding: 5px 10px;
}

.feature-icon {
  font-size: 44px;
  padding: 0;
  line-height: 68px;
  width: 72px;
  text-align: center;
  opacity: .8;
  border: 3px solid;
  border-radius: 200px;
  height: 72px;
  margin-bottom: 20px;
}

.feature-icon.fa-gamepad {
  line-height: 60px;
}

.feature-icon.fa-tachometer {
  line-height: 60px;
}

.app-content-loading {
  text-align: center;
  height: 100%;
  width: 100%;
  background: #fff;
  position: relative;
}

.loading-spinner {
  position: absolute;
  font-size: 50px;
  left: 50%;
  top: 50%;
  margin-left: -25px;
  margin-top: -25px;
}

.carousel-example-content {
  position: absolute;
  font-size: 50px;
  line-height: 50px;
  width: 100%;
  text-align: center;
  top: 50%;
  margin-top: -50px;
}

.carousel-item {
  display: block;
  color: #444;
  background: #f4f4f4;
  box-shadow: 0px 0px 3px rgba(0,0,0,0.5);
  -webkit-transition: opacity 0.3s;
  -moz-transition: opacity 0.3s;
  transition: opacity 0.3s;
  opacity: 1;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.carousel {
  padding: 20px;
  overflow: visible;
}

.carousel-inner {
  position: relative;
  overflow: visible;
}

.carousel>.item, .carousel-item {
  top: 0;
  left: 0;
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
  background-size: cover;
}

.carousel-item {
  -webkit-transition: -webkit-transform 500ms;
  -moz-transition: -moz-transform 500ms;
  transition: transform 500ms;
}

[drag-to-dismiss]{
  transform: translate(0,0); /* NOTE: this is required to prevent mobile webkit issues */
  -webkit-user-drag: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-transition: opacity 300ms, -webkit-transform 300ms;
  -moz-transition: opacity 300ms, -moz-transform 300ms;
  transition: opacity 300ms, transform 300ms;
  opacity: 1;
}

.notices-container {
  overflow-x: hidden;
}

.dismiss {
  -webkit-transition: opacity 300ms, -webkit-transform 300ms;
  -moz-transition: opacity 300ms, -moz-transform 300ms;
  transition: opacity 300ms, transform 300ms;
  opacity: 0.5;
}

.dismitted {
  -webkit-transition: opacity 300ms, -webkit-transform 300ms;
  -moz-transition: opacity 300ms, -moz-transform 300ms;
  transition: opacity 300ms, transform 300ms;
  opacity: 0;
}

.list-group-item-home {
  padding: 20px;
}

pre {
  text-align: left !important;
}

input.scrollable-header {
  border-bottom: 3px solid #ccc;
}

.toucharea {width: 100%; height: 100%;}


text:
import sys
import os

#HACK OF DENDROPY setup.py BELOW

###############################################################################
# setuptools/distutils/etc. import and configuration

from setuptools import setup, find_packages

sys.stderr.write("searching for packages\n")
PACKAGES = find_packages()
EXTRA_KWARGS = dict(
    install_requires = ['dendropy', 'six'],
    include_package_data=True,
    zip_safe=True
    )

PACKAGE_DIRS = [p.replace(".", os.path.sep) for p in PACKAGES]
PACKAGE_INFO = [("% 40s : %s" % p) for p in zip(PACKAGES, PACKAGE_DIRS)]
sys.stderr.write("packages identified:\n%s\n" % ("\n".join(PACKAGE_INFO)))
ENTRY_POINTS = {}

###############################################################################
# Script paths

SCRIPT_SUBPATHS = [
    ['scripts', 'terraphy.main.py'],
]
SCRIPTS = [os.path.join(*i) for i in SCRIPT_SUBPATHS]
sys.stderr.write("\nscripts identified: %s\n" % "\n\t".join(SCRIPTS))

###############################################################################
# setuptools/distuils command extensions

try:
    from setuptools import Command
except ImportError:
    sys.stderr.write("setuptools.Command could not be imported: setuptools extensions not available\n")
else:
    sys.stderr.write("setuptools command extensions are available\n")
    command_hook = "distutils.commands"
    ENTRY_POINTS[command_hook] = []

    ###########################################################################

###############################################################################
# Main setup

__version__ = 1.0

### compose long description ###
#long_description = open('README.txt').read()
long_description='Scripts for analyzing phylogenetic terraces.'

setup(name='terraphy',
      version=__version__,
      author='Derrick Zwickl',
      author_email='zwickl@email.arizona.edu',
      url='https://github.com/zwickl/terraphy',
      description='Scripts for analyzing phylogenetic terraces.',
      license='MIT',
      packages=PACKAGES,
      package_dir=dict(zip(PACKAGES, PACKAGE_DIRS)),
      scripts = SCRIPTS,
      long_description=long_description,
      entry_points = ENTRY_POINTS,
      classifiers = [
            "Environment :: Console",
            "Intended Audience :: Developers",
            "Intended Audience :: Science/Research",
            "License :: OSI Approved :: GPL3",
            "Natural Language :: English",
            "Operating System :: OS Independent",
            "Programming Language :: Python",
            "Topic :: Scientific/Engineering :: Bio-Informatics",
            ],
      keywords='phylogenetics phylogeny phylogenies phylogenomics evolution evolutionary biology systematics phyloinformatics bioinformatics',
      **EXTRA_KWARGS
      )


text:
package summea.kanjoto.test.unit;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import summea.kanjoto.data.ApprenticeScorecardsDataSource;
import summea.kanjoto.data.KanjotoDatabaseHelper;
import summea.kanjoto.model.ApprenticeScorecard;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;

public class ApprenticeScorecardsDataSourceTest extends AndroidTestCase {

    private ApprenticeScorecardsDataSource asds;
    private KanjotoDatabaseHelper db;
    private RenamingDelegatingContext context;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        context = new RenamingDelegatingContext(getContext(), "test_");
        db = new KanjotoDatabaseHelper(context);
        asds = new ApprenticeScorecardsDataSource(context);
    }

    @Override
    public void tearDown() throws Exception {
        db.close();
        super.tearDown();
    }

    public void test_createApprenticeScorecard_paramApprenticeScorecard() throws Throwable {
        ApprenticeScorecard apprenticeScorecard = new ApprenticeScorecard();
        apprenticeScorecard.setCorrect(1);
        apprenticeScorecard.setTotal(2);
        apprenticeScorecard.setApprenticeId(1);
        TimeZone timezone = TimeZone.getTimeZone("UTC");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'",
                Locale.getDefault());
        dateFormat.setTimeZone(timezone);
        String takenAtISO = dateFormat.format(new Date());
        apprenticeScorecard.setTakenAt(takenAtISO);
        ApprenticeScorecard result = asds.createApprenticeScorecard(apprenticeScorecard);
        assertNotNull("created apprentice scorecard is not null", result);
    }

    public void test_deleteApprenticeScorecard_paramApprenticeScorecard() throws Throwable {
        ApprenticeScorecard apprenticeScorecard = new ApprenticeScorecard();
        apprenticeScorecard.setId(1);
        apprenticeScorecard.setCorrect(1);
        apprenticeScorecard.setTotal(2);
        apprenticeScorecard.setApprenticeId(1);
        TimeZone timezone = TimeZone.getTimeZone("UTC");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'",
                Locale.getDefault());
        dateFormat.setTimeZone(timezone);
        String takenAtISO = dateFormat.format(new Date());
        apprenticeScorecard.setTakenAt(takenAtISO);
        ApprenticeScorecard result = asds.createApprenticeScorecard(apprenticeScorecard);
        assertNotNull("created apprentice scorecard is not null", result);
        asds.deleteApprenticeScorecard(apprenticeScorecard);
        apprenticeScorecard = new ApprenticeScorecard();
        apprenticeScorecard = asds.getApprenticeScorecard(1);
        assertTrue(apprenticeScorecard.getId() != 1);
    }

    public void test_getAllApprenticeScorecards_paramApprenticeId_paramOrderBy() throws Throwable {
        test_createApprenticeScorecard_paramApprenticeScorecard();
        List<ApprenticeScorecard> apprenticeScorecards = new ArrayList<ApprenticeScorecard>();
        apprenticeScorecards = asds.getAllApprenticeScorecards(1, KanjotoDatabaseHelper.COLUMN_ID);
        assertNotNull("get all apprentice scorecards is not null", apprenticeScorecards);
        assertFalse(apprenticeScorecards.isEmpty());
    }

    public void test_getAllApprenticeScorecardListPreviews_paramApprenticeId() throws Throwable {
        test_createApprenticeScorecard_paramApprenticeScorecard();
        List<String> previews = asds.getAllApprenticeScorecardListPreviews(1);
        assertNotNull("get all apprentice scorecard list previews is not null", previews);
        assertFalse(previews.isEmpty());
    }

    public void test_getApprenticeScorecard_paramApprenticeScorecardId() throws Throwable {
        test_createApprenticeScorecard_paramApprenticeScorecard();
        ApprenticeScorecard apprenticeScorecard = new ApprenticeScorecard();
        apprenticeScorecard = asds.getApprenticeScorecard(1);
        assertNotNull("get apprentice scorecard is not null", apprenticeScorecard);
        assertTrue(apprenticeScorecard.getId() > 0);
    }

    public void test_updateApprenticeScorecard_paramApprenticeScorecard() throws Throwable {
        test_createApprenticeScorecard_paramApprenticeScorecard();
        ApprenticeScorecard apprenticeScorecard = asds.getApprenticeScorecard(1);
        apprenticeScorecard.setCorrect(2);
        asds.updateApprenticeScorecard(apprenticeScorecard);
        ApprenticeScorecard apprenticeScorecard2 = asds.getApprenticeScorecard(1);
        assertNotNull("update apprenticeScorecard is not null", apprenticeScorecard2);
        assertTrue(apprenticeScorecard.getCorrect() == 2);
    }
}


text:
package main

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/sqs"
	"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
)

type mockedReceiveMsgs struct {
	sqsiface.SQSAPI
	Resp sqs.ReceiveMessageOutput
}

func (m mockedReceiveMsgs) ReceiveMessage(in *sqs.ReceiveMessageInput) (*sqs.ReceiveMessageOutput, error) {
	// Only need to return mocked response output
	return &m.Resp, nil
}

func TestQueueGetMessage(t *testing.T) {
	cases := []struct {
		Resp     sqs.ReceiveMessageOutput
		Expected []Message
	}{
		{ // Case 1, expect parsed responses
			Resp: sqs.ReceiveMessageOutput{
				Messages: []*sqs.Message{
					{Body: aws.String(`{"from":"user_1","to":"room_1","msg":"Hello!"}`)},
					{Body: aws.String(`{"from":"user_2","to":"room_1","msg":"Hi user_1 :)"}`)},
				},
			},
			Expected: []Message{
				{From: "user_1", To: "room_1", Msg: "Hello!"},
				{From: "user_2", To: "room_1", Msg: "Hi user_1 :)"},
			},
		},
		{ // Case 2, not messages returned
			Resp:     sqs.ReceiveMessageOutput{},
			Expected: []Message{},
		},
	}

	for i, c := range cases {
		q := Queue{
			Client: mockedReceiveMsgs{Resp: c.Resp},
			URL:    fmt.Sprintf("mockURL_%d", i),
		}
		msgs, err := q.GetMessages(20)
		if err != nil {
			t.Fatalf("%d, unexpected error, %v", i, err)
		}
		if a, e := len(msgs), len(c.Expected); a != e {
			t.Fatalf("%d, expected %d messages, got %d", i, e, a)
		}
		for j, msg := range msgs {
			if a, e := msg, c.Expected[j]; a != e {
				t.Errorf("%d, expected %v message, got %v", i, e, a)
			}
		}
	}
}


text:
package main

import (
	"log"
	"time"

	"github.com/deckarep/golang-set"
	"github.com/jonboulle/clockwork"
)

// Records jobs and creates alerts about them
type JobList struct {
	config  CharacterConfig
	clock   clockwork.Clock
	alerter Alerter
	jobs    mapset.Set
}

func NewJobList(config CharacterConfig, clock clockwork.Clock, alerter Alerter) *JobList {
	return &JobList{
		config:  config,
		clock:   clock,
		alerter: alerter,
		jobs:    mapset.NewSet(),
	}
}

func (self *JobList) Count() int {
	return self.jobs.Cardinality()
}

func (self *JobList) String() string {
	return self.jobs.String()
}

// Given the current complete list of Jobs read from the jobs API, record
// interesting jobs and initialise alerts.
func (self *JobList) SetJobs(jobs []Job) {
	currentJobs := mapset.NewSet()
	for _, job := range jobs {
		if self.isInteresting(&job) {
			currentJobs.Add(job)
		}
	}
	newJobs := currentJobs.Difference(self.jobs)
	// TODO add a lock around this
	self.jobs = currentJobs

	for newJobInterface := range newJobs.Iter() {
		newJob := newJobInterface.(Job)
		self.startAlertTimer(&newJob)
	}
}

// A job is interesting if it belongs to a configured character.
func (self *JobList) isInteresting(job *Job) bool {
	return self.config.CharacterSet().Contains(job.Installer)
}

// Alert about the job 1 minute before its end date
func (self *JobList) startAlertTimer(job *Job) {
	duration := job.EndDate.Sub(self.clock.Now()) - time.Minute
	// Do not bother to create an alert if it is due in the past
	if duration < 0 {
		return
	}
	c := self.clock.After(duration)
	go func() {
		_ = <-c
		self.Alert(job)
	}()
	log.Printf("Will alert about %s in %s", job.Blueprint, duration)
}

func (self *JobList) Alert(job *Job) {
	// Do not bother if it is superceded
	if self.IsSuperceded(*job) {
		return
	}
	self.alerter.Alert(job, self.config.AlertUsername(job.Installer))
}

// If there is another job for the same blueprint & character due within the
// next minute, return false
func (self *JobList) IsSuperceded(job Job) bool {
	for otherJobInterface := range self.jobs.Iter() {
		otherJob := otherJobInterface.(Job)
		if job == otherJob {
			continue
		}
		if job.Installer != otherJob.Installer {
			continue
		}
		if job.Blueprint != otherJob.Blueprint {
			continue
		}
		delta := otherJob.EndDate.Sub(job.EndDate)
		// For jobs at identical times, the highest ID wins
		if delta == 0 {
			return job.ID < otherJob.ID
		}
		if delta > 0 && delta <= time.Minute {
			return true
		}
	}
	return false
}


text:
'use strict';

var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var mockery = require('mockery');
var Q = require('q');
var path = require('path');

chai.use(require('chai-as-promised'));
chai.use(require('sinon-chai'));

describe('native-builder', function () {
  describe('Running with no engine', function () {
    it('should be ok', function () {
      var nativeBuilder = require('../lib');

      return expect(nativeBuilder.resolve()).to.be.fulfilled;
    });
  });

  describe('Running atom shell win32', function () {
    before(function () {
      var whichNativeStub = sinon.stub().returns(Q.resolve({ asVersion: '0.30.1' }));

      mockery.registerMock('which-native-nodish', whichNativeStub);
      mockery.enable({
        useCleanCache: true,
        warnOnReplace: false,
        warnOnUnregistered: false
      });
    });

    after(function () {
      mockery.deregisterMock('which-native-nodish');
      mockery.disable();
      Object.defineProperty(process, 'platform', {
        value: this.originalPlatform
      });
    });

    it('should work', function () {
      var nativeBuilder = require('../lib');
      var builder = '"' + path.resolve(__dirname, '..', 'node_modules', '.bin', 'node-gyp') + '"';
      var electronSetup = 'SET USERPROFILE=%USERPROFILE%\\.electron-gyp&& ';
      var distUrl = '  --dist-url=https://atom.io/download/atom-shell';

      this.originalPlatform = process.platform;
      Object.defineProperty(process, 'platform', {
        value: 'win32'
      });

      return expect(nativeBuilder.resolve()).to.eventually.equal(electronSetup.concat(builder, ' rebuild --target=0.30.1', distUrl));
    });
  });

  describe('Running atom shell otherOS', function () {
    before(function () {
      var whichNativeStub = sinon.stub().returns(Q.resolve({ asVersion: '0.30.1' }));

      mockery.registerMock('which-native-nodish', whichNativeStub);
      mockery.enable({
        useCleanCache: true,
        warnOnReplace: false,
        warnOnUnregistered: false
      });
    });

    after(function () {
      mockery.deregisterMock('which-native-nodish');
      mockery.disable();
      Object.defineProperty(process, 'platform', {
        value: this.originalPlatform
      });
    });

    it('should work', function () {
      var nativeBuilder = require('../lib');
      var builder = '"' + path.resolve(__dirname, '..', 'node_modules', '.bin', 'node-gyp') + '"';
      var electronSetup = 'HOME=~/.electron-gyp ';
      var distUrl = '  --dist-url=https://atom.io/download/atom-shell';

      // Can't happen before the creation of native builder, since it ruins the child-process require
      this.originalPlatform = process.platform;
      Object.defineProperty(process, 'platform', {
        value: 'JustSomeOS'
      });

      return expect(nativeBuilder.resolve()).to.eventually.equal(electronSetup.concat(builder, ' rebuild --target=0.30.1', distUrl));
    });
  });

  describe('Running node webkit', function () {
    before(function () {
      var whichNativeStub = sinon.stub().returns(Q.resolve({ nwVersion: '0.12.0' }));

      mockery.registerMock('which-native-nodish', whichNativeStub);
      mockery.enable({
        useCleanCache: true,
        warnOnReplace: false,
        warnOnUnregistered: false
      });
      this.env = Object.getOwnPropertyDescriptor(process, 'env');
      this.env.BUILD_DEBUG = true;
      Object.defineProperty(process, 'env', {
        value: this.env
      });
    });

    after(function () {
      mockery.deregisterMock('which-native-nodish');
      mockery.disable();

      this.env.BUILD_DEBUG = false;
      Object.defineProperty(process, 'env', {
        value: this.env
      });
    });

    it('should work in debug', function () {
      var nativeBuilder = require('../lib');
      var builder = '"' + path.resolve(__dirname, '..', 'node_modules', '.bin', 'nw-gyp') + '"';

      return expect(nativeBuilder.resolve()).to.eventually.equal(builder.concat(' rebuild --target=0.12.0  --debug'));
    });
  });

  describe('Trying to build', function () {
    var execStub;

    before(function () {
      var whichNativeStub = sinon.stub().returns(Q.resolve({ nwVersion: '0.12.0' }));

      execStub = sinon.stub();

      mockery.registerMock('child_process', {exec: execStub});
      mockery.registerMock('which-native-nodish', whichNativeStub);
      mockery.enable({
        useCleanCache: true,
        warnOnReplace: false,
        warnOnUnregistered: false
      });
    });

    after(function () {
      mockery.deregisterMock('which-native-nodish');
      mockery.deregisterMock('child_process');
      mockery.disable();
    });

    it('should call exec with resolved command', function () {
      var nativeBuilder = require('../lib');

      return nativeBuilder.build()
        .then(function () {
          return expect(execStub).to.have.been.calledWithMatch('nw-gyp" rebuild --target=0.12.0');
        });
    });
  });
});


text:
<!DOCTYPE html>

<title>PDF2SVG</title>
<meta charset="UTF-8">

Convert PDF to SVG

<form action="pdf2svg.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input type="file" name="file" id="file" accept="application/pdf" />
<input type="submit" name="submit" value="Convert to SVG" />
</form>

Convert SVG to PNG

<form action="svg2png.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input type="file" name="file" id="file" accept="image/svg+xml" />
<input type="submit" name="submit" value="Convert to PNG" />

<input type="checkbox" name="no-antialiasing" value="1" id="no-antialiasing" /> disable anti-aliasing (experimental)
</form>

This tool is maintained by Rillke and others. Issues and pull requests?  On GitHub.


text:
<?php

$online_user = erLhcoreClassModelChatOnlineUser::fetchByVid($Params['user_parameters']['vid']);

if ($online_user !== false && isset($online_user->online_attr_system_array['ishare_enabled']) && $online_user->online_attr_system_array['ishare_enabled'] == 1) // Allow add messages only if chat is active
{
    $fileData = erLhcoreClassModelChatConfig::fetch('file_configuration');
    $data = (array) $fileData->data;
    $path = 'var/storage/' . date('Y') . 'y/' . date('m') . '/' . date('d') . '/ou' . $online_user->id . '/';

    erLhcoreClassChatEventDispatcher::getInstance()->dispatch('file.uploadfile.file_path', array(
        'path' => & $path,
        'storage_id' => $online_user->id
    ));

    $upload_handler = new erLhcoreClassFileUpload(array(
        'user_id' => 0,
        'max_file_size' => $data['fs_max'] * 1024,
        'accept_file_types_lhc' => '/\.(' . $data['ft_us'] . ')$/i',
        'online_user' => $online_user,
        'download_via_php' => true,
        'upload_dir' => $path
    ));

    if ($upload_handler->uploadedFile instanceof erLhcoreClassModelChatFile) {
        erLhcoreClassChatEventDispatcher::getInstance()->dispatch('file.uploadfile.file_store', array(
            'chat_file' => $upload_handler->uploadedFile
        ));
    };

    echo json_encode(array(
        'error' => 'false'
    ));
}

exit;

?>


text:
package org.optaplanner.examples.projectjobscheduling.app;

import org.optaplanner.examples.common.app.CommonApp;
import org.optaplanner.examples.common.persistence.AbstractSolutionImporter;
import org.optaplanner.examples.common.persistence.SolutionDao;
import org.optaplanner.examples.common.swingui.SolutionPanel;
import org.optaplanner.examples.projectjobscheduling.domain.Schedule;
import org.optaplanner.examples.projectjobscheduling.persistence.ProjectJobSchedulingDao;
import org.optaplanner.examples.projectjobscheduling.persistence.ProjectJobSchedulingImporter;
import org.optaplanner.examples.projectjobscheduling.swingui.ProjectJobSchedulingPanel;

public class ProjectJobSchedulingApp extends CommonApp<Schedule> {

    public static final String SOLVER_CONFIG
            = "org/optaplanner/examples/projectjobscheduling/solver/projectJobSchedulingSolverConfig.xml";

    public static void main(String[] args) {
        prepareSwingEnvironment();
        new ProjectJobSchedulingApp().init();
    }

    public ProjectJobSchedulingApp() {
        super("Project job scheduling",
                "Official competition name:" +
                        " multi-mode resource-constrained multi-project scheduling problem (MRCMPSP)\n\n" +
                        "Schedule all jobs in time and execution mode.\n\n" +
                        "Minimize project delays.",
                SOLVER_CONFIG,
                ProjectJobSchedulingPanel.LOGO_PATH);
    }

    @Override
    protected ProjectJobSchedulingPanel createSolutionPanel() {
        return new ProjectJobSchedulingPanel();
    }

    @Override
    protected SolutionDao createSolutionDao() {
        return new ProjectJobSchedulingDao();
    }

    @Override
    protected AbstractSolutionImporter[] createSolutionImporters() {
        return new AbstractSolutionImporter[]{
                new ProjectJobSchedulingImporter()
        };
    }

}


text:
class OperatorsController < ApplicationController
  include ApplicationHelper

  # GET /operators
  # GET /operators.json
  # GET /operators.xml
  def index
    @q = params[:q]
    if @q && !@q.empty?
      @operators = Operator.where("upper(code) LIKE ? OR upper(name) LIKE ?", @q.upcase, "%#{@q.upcase}%").page(params[:page])
    else
      @operators = Operator.page(params[:page])
    end

    respond_to do |format|
      format.html
      format.xml { render xml: @operators }
      format.json { render json: @operators, callback: params['callback'] }
    end
  end

  # GET /operators/all
  # GET /operators/all.json
  # GET /operators/all.xml
  def all
    @operators = Operator.all

    respond_to do |format|
      format.html
      format.xml { render xml: @operators }
      format.json { render json: @operators, callback: params['callback'] }
    end
  end

  # GET /operators/1
  # GET /operators/1.json
  # GET /operators/1.xml
  def show
    @operator = Operator.find_by! uuid: params[:uuid]

    @og = {
        "og:title" => @operator,
        "og:type" => "train-track:operator",
        "og:url" => request.original_url,
        "og:image" => "",
        "og:site_name" => "dyl.anjon.es",
        "fb:app_id" => "272514462916508",
        "train-track:code" => @operator.code
      }

    respond_to do |format|
      format.html
      format.xml { render xml: @operator }
      format.json { render json: @operator, callback: params['callback'] }
    end
  end

end


text:
__version__ = '1.2.2'
__author__ = 'Maxim Kamenkov'

from .boxview import BoxView, BoxViewError, RetryAfter

__all__ = ['BoxView', 'BoxViewError', 'RetryAfter']


text:
package org.wso2.carbon.dataservices.core;

import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.dataservices.common.DBConstants;

/**
 * This class represents the Axis2 message receiver used to dispatch in-only service calls.
 */
public class DBInOnlyMessageReceiver extends RawXMLINOnlyMessageReceiver {

	private static final Log log = LogFactory.getLog(DBInOnlyMessageReceiver.class);

	/**
	 * Invokes the business logic invocation on the service implementation
	 * class
	 *
	 * @param msgContext
	 *            the incoming message context
	 * @throws AxisFault
	 *             on invalid method (wrong signature) or behavior (return
	 *             null)
	 */
	public void invokeBusinessLogic(MessageContext msgContext) throws AxisFault {
		try {
			if (log.isDebugEnabled()) {
				log.debug("Request received to DSS:  Data Service - " + msgContext.getServiceContext().getName() +
				          ", Operation - " + msgContext.getSoapAction() + ", Request body - " +
				          msgContext.getEnvelope().getText() + ", ThreadID - " + Thread.currentThread().getId());
			}
			DataServiceProcessor.dispatch(msgContext);
		} catch (Exception e) {
			log.error("Error in in-only message receiver", e);
			msgContext.setProperty(Constants.FAULT_NAME, DBConstants.DS_FAULT_NAME);
			throw DBUtils.createAxisFault(e);
		} finally {
			if (log.isDebugEnabled()) {
				log.debug("Request processing completed from DSS: Data Service - " +
				          msgContext.getServiceContext().getName() + ", Operation - " + msgContext.getSoapAction() +
				          ", ThreadID - " + Thread.currentThread().getId());
			}
		}
	}

}


text:
Opens your Travis-ci repository of the current github repo

#Install
```bash
npm install -g travis-open
```

#Usage
As simply as
```bash
travis-open
```
inside your github repository.

Based on [git-open](https://github.com/paulirish/git-open) idea & some of their code.


text:
package com.heima.smartbeijing.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * SharedPreference·â×°
 * @author lenovo
 *
 */
public class PrefUtils {
	public static boolean getBoolean(Context context,String key,boolean defValue){
		//´æ´¢ÔÚconfigÎļþÖÐ
		SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		return sp.getBoolean(key, defValue);
	}
	public static void setBoolean(Context context,String key,boolean value){
		SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		sp.edit().putBoolean(key, value).commit();
	}

	public static String getString(Context context,String key,String defValue){
		SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		return sp.getString(key, defValue);
	}

	public static void setString(Context context,String key,String value){
		SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		sp.edit().putString(key, value).commit();
	}

	public static int getInt(Context context,String key,int defValue){
		SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		return sp.getInt(key, defValue);
	}

	public static void setInt(Context context,String key,int value){
		SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		sp.edit().putInt(key, value).commit();
	}

}


text:
<!DOCTYPE html>

		<form id="monthlyNotificationsForm"
			th:action="@{/async/paas/smsaas/monthly}"
			th:object="${MonthlyNotificationForm}" method="post">

								<input type="checkbox" name="monthlyNot" id="monthlyNot"
									checked="checked" value="monthlyNot" />

								<input type="checkbox" name="monthlyNot" id="monthlyNot"
									value="monthlyNot" />

 Attiva notifica mensile

									<input type="checkbox" name="monthlySms" id="monthlySms"
										value="monthlySms" checked="checked" />

									<input type="checkbox" name="monthlySms" id="monthlySms"
										value="monthlySms" />

 SMS

									<input type="checkbox" name="monthlyEmail" id="monthlyEmail"
										value="monthlyEmail" checked="checked" />

									<input type="checkbox" name="monthlyEmail" id="monthlyEmail"
										value="monthlyEmail" />

 Email

						Inserisci numero di telefono

							<input type="text" class="form-control" id="numberMonthly"
								name="numberMonthly" th:value="${notification.monthSms}" />

						Indirizzo di notifica

							<input type="email" class="form-control" id="emailAddressMonthly"
								name="emailAddressMonthly"
								placeholder="Inserisci indirizzo email"
								th:value="${notification.monthEmail}" required="required" />

						Inserisci soglia

							<input type="number" class="form-control"
								id="smsThresholdMonthly" name="smsThresholdMonthly" min="1"
								th:value="${notification.thresholdMonth}" step="1" />

					<button type="button" id="saveMonthlyNotification"
						class="btn btn-primary">Salva</button>

Notifiche salvate!

		</form>


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 Copyright 2003 - 2016 The eFaps Team

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

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

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

 Original Author: Mark James (mjames at gmail.com)
 Original Name:   note.png
 Original Web:    Silk icon set 1.3
                  [ http://www.famfamfam.com/lab/icons/silk/ ]
 Original License:Creative Commons Attribution 2.5 License
                  [ http://creativecommons.org/licenses/by/2.5/ ]

-->

<ui-image xmlns="http://www.efaps.org/xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">

  <uuid>0a81d863-b94f-457b-ae7d-4d124acd884c</uuid>
  <file-application>eFaps-Kernel</file-application>

  <definition>
    <version-expression>(version==latest)</version-expression>
    <name>Admin_User_AttributeAbstract</name>
    <file>Admin_User_AttributeAbstract.gif</file>
    <!-- is type icon for -->
    <type>Admin_User_AttributeAbstract</type>
  </definition>

</ui-image>


text:
var util = require('util'),
    EventEmitter = require('events').EventEmitter,
    zlib = require('zlib');

var thrift = require('helenus-thrift'),
    P = require('p-promise'),
    _ = require('lodash');

var Cassandra = require('./cassandra/Cassandra'),
    ttype = require('./cassandra/cassandra_types'),
    Row = require('./row'),
    Keyspace = require('./keyspace'),
    errors = require('./errors'),
    helpers = require('./helpers');

var Connection = module.exports = function Connection(options)
{
    options = Object(options);
    if (!options.port && options.host && options.host.indexOf(':') > -1)
    {
        var split = options.host.split(':');
        options.host = split[0];
        options.port = split[1];
    }
    _.extend(this, options, function (destinationValue, sourceValue)
    {
        return sourceValue == null ? destinationValue : sourceValue;
    });

    this.proxyErrorBound = _.bindKey(this, 'proxyError');
    this.pingBound = _.bindKey(this, 'ping');
};

util.inherits(Connection, EventEmitter);

Connection.TTL = 20 * 60 * 1000;
Connection.PING_QUERY = new Buffer('SELECT * FROM system.schema_keyspaces;');

Connection.prototype.port = 9160;
Connection.prototype.host = 'localhost';

Connection.prototype.timeout = 3000;
Connection.prototype._connectTimeout = null;

Connection.prototype.pingInterval = 30000;
Connection.prototype._pingTimer = null;
Connection.prototype.healthy = false;

Connection.prototype.consistencylevel = 1;
Connection.prototype.ready = false;

Connection.prototype.user = Connection.prototype.password = null;
Connection.prototype.keyspace = null;
Connection.prototype.cqlVersion = '3.0.0';

Connection.prototype.proxyError = function proxyError(error)
{
    this.healthy = false;
    this.emit('error', error);
};

function createDeflate(buffer)
{
    var deferred = P.defer();
    zlib.deflate(buffer, function (error, result)
    {
        if (error)
            return deferred.reject(error);
        deferred.resolve(result);
    });
    return deferred.promise;
}

Connection.prototype.connect = function connect()
{
    var deferred = P.defer(),
        self = this;

    var connection = this._connection = thrift.createConnection(this.host, this.port),
        client = this._client = thrift.createClient(Cassandra, connection);

    connection.on('error', onError);
    function onError(error)
    {
        var connection = self._connection;

        connection.removeListener('error', onError);
        connection.removeListener('close', onClose);
        connection.removeListener('connect', onConnect);

        clearTimeout(self._connectTimeout);
        connection.connection.destroy();

        self.healthy = false;
        deferred.reject(error);
    }

    connection.on('close', onClose);
    function onClose()
    {
        var connection = self._connection;

        connection.removeListener('error', onError);
        connection.removeListener('connect', onConnect);

        clearTimeout(self._connectTimeout);
        self.ready = false;
        self.healthy = false;
        self.emit('close');
    }

    connection.on('connect', onConnect);
    function onConnect(error)
    {
        connection.removeListener('connect', onConnect);

        if (error)
        {
            connection.removeListener('error', onError);
            return deferred.reject(error);
        }

        self.authenticate().then(function ()
        {
            self.emit('log', 'successful authentication');

            connection.removeListener('error', onError);
            connection.on('error', self.proxyErrorBound);

            clearTimeout(self._connectTimeout);
            return self.cqlVersion ? self.setCqlVersion() : P();
        }).then(function()
        {
            return self.selectCqlVersion().fail(deferred.reject);
        })
        .then(function(keyspace)
        {
            self._pingTimer = setTimeout(self.pingBound, self.pingInterval);
            self.healthy = true;
            deferred.resolve(keyspace);
        })
        .fail(function(error)
        {
            self.emit('log', 'authentication error; destroying connection');

            clearTimeout(self._connectTimeout);
            connection.removeListener('error', self.proxyErrorBound);

            var socket = connection.connection;
            socket.destroy();
            deferred.reject(error);
        }).done();
    }

    this._connectTimeout = setTimeout(function ()
    {
        deferred.reject(errors.create({ name: 'TimeoutException', why: 'Connection Timed Out' }));
        connection.connection.destroy();
    }, this.timeout);

    return deferred.promise;
};

Connection.prototype.refreshConnection = function refreshConnection()
{
    var self = this;

    self.emit('log', 'handling connection end-of-life');

    self._connection.removeAllListeners();
    self._connection.end();
    self._connection.connection.destroy();

    self.connect()
    .then(function()
    {
        self.emit('log', 'successfully reconnected after connection end-of-life');
        return 'OK';
    })
    .fail(function(err)
    {
        self.emit('log', 'reconnection error; throwing', err.message);
        throw(err);
    }).done();
};

Connection.prototype.authenticate = function authenticate()
{
    var deferred = P.defer(),
        self = this;
    var user = this.user, password = this.password;
    if (!user && !password)
    {
        deferred.resolve();
        return deferred.promise;
    }
    var authRequest = new ttype.AuthenticationRequest({ 'credentials': { 'username': user, 'password': password }});
    this._client.login(authRequest, function (error)
    {
        if (error)
            return deferred.reject(errors.create(error));
        deferred.resolve();
    });
    return deferred.promise;
};

Connection.prototype.setCqlVersion = function setCqlVersion()
{
    var deferred = P.defer(),
        connection = this._connection.connection;
    this._client.set_cql_version(this.cqlVersion, function (error)
    {
        if (error)
        {
            connection.destroy();
            return deferred.reject(errors.create(error));
        }
        deferred.resolve();
    });
    return deferred.promise;
};

Connection.prototype.selectCqlVersion = function selectCqlVersion()
{
    var deferred = P.defer(),
        self = this;
    this.ready = true;
    this._client.describe_version(function (error, version)
    {
        if (error)
            return deferred.reject(error);
        self.version = version.split('.');
        deferred.resolve();
    });
    return deferred.promise.then(function ()
    {
        var keyspace = self.keyspace;
        if (keyspace == null)
            return;
        return self.use(keyspace);
    });
};

Connection.prototype.execute = function execute()
{
    var args = [].slice.call(arguments, 0),
        deferred = P.defer(),
        command = args.shift();
    args.push(function onReturn(error, results)
    {
        if (error)
            return deferred.reject(error);
        deferred.resolve(results);
    });
    var client = this._client;
    client[command].apply(client, args);
    return deferred.promise;
};

Connection.prototype.executeCQL = function executeCQL(cqlBuffer, options)
{
    var deferred = P.defer(),
        self = this;

    options || (options = {});

    var useGzip = options.gzip === true,
        query = (useGzip ? createDeflate : P)(cqlBuffer);

    var queryResult = query.then(function (queryString)
    {
        var args =
        [
            queryString,
            ttype.Compression[useGzip ? 'GZIP' : 'NONE']
        ];
        if (self.cqlVersion == '3.0.0' && self.version[0] == '19' && self.version[1] > '33')
        {
            args.unshift('execute_cql3_query');
            args.push(self.consistencylevel);
        }
        else
        {
            args.unshift('execute_cql_query');
        }

        return self.execute.apply(self, args);
    });

    return queryResult.then(function (result)
    {
        switch (result.type)
        {
            case ttype.CqlResultType.ROWS:
                var schema = result.schema;
                return _.map(result.rows, function (row)
                {
                    return new Row(row, schema);
                });
            case ttype.CqlResultType.INT:
                return result.num;
            case ttype.CqlResultType.VOID:
                return null;
        }
    });
};

Connection.prototype.cql = function cql(cmd, args, options)
{
    if (!Array.isArray(args))
    {
        options = args;
        args = null;
    }

    var cqlBuffer = new Buffer(args ? helpers.escape(cmd, args, this.cqlVersion) : cmd);
    return this.executeCQL(cqlBuffer, options);
};

Connection.prototype.useKeyspace = function use(keyspace)
{
    var deferred = P.defer(),
        self = this;
    this._client.describe_keyspace(keyspace, function (error, definition)
    {
        if (error)
            return deferred.reject(errors.create(error));
        self._client.set_keyspace(keyspace, function (error)
        {
            if (error)
                return deferred.reject(errors.create(error));
            deferred.resolve(new Keyspace(self, definition));
        });
    });
    return deferred.promise;
};
Connection.prototype.use = Connection.prototype.useKeyspace;

// Uses if it already exists, creates if it does not.
Connection.prototype.assignKeyspace = function assignKeyspace(keyspace, options)
{
    var self = this;

    return self.useKeyspace(keyspace)
    .fail(function(err)
    {
        if (err.name !== 'ScamandriosNotFoundException')
            throw err;

        return self.createKeyspace(keyspace, options).then(function()
        {
            return self.useKeyspace(keyspace);
        });
    }).then(function(ks)
    {
        return ks;
    });
};

Connection.prototype.createKeyspace = function createKeyspace(keyspace, options)
{
    var deferred = P.defer(),
        self = this;

    if (!keyspace)
    {
        deferred.reject(errors.create({ 'name': 'InvalidNameError', 'why': 'Keyspace name not specified' }));
        return deferred.promise;
    }

    options = Object(options);
    var args =
    {
        'name': keyspace,
        'strategy_class': options.strategyClass || 'SimpleStrategy',
        'strategy_options': options.strategyOptions || {},
        'replication_factor': options.replication || 1,
        'durable_writes': options.durable || true,
        'cf_defs': []
    };
    if (args.strategy_class === 'SimpleStrategy' && !args.strategy_options.replication_factor)
        args.strategy_options.replication_factor = '' + args.replication_factor;

    var ksdef = new ttype.KsDef(args);
    this._client.system_add_keyspace(ksdef, function (error, response)
    {
        if (error)
            return deferred.reject(errors.create(error));
        deferred.resolve(response);
    });
    return deferred.promise;
};

Connection.prototype.dropKeyspace = function dropKeyspace(keyspace, options)
{
    var deferred = P.defer();
    if (!keyspace)
    {
        deferred.reject(errors.create({ 'name': 'InvalidNameError', 'why': 'Keyspace name not specified' }));
        return deferred.promise;
    }
    this._client.system_drop_keyspace(keyspace, function (error, response)
    {
        if (error)
            return deferred.reject(errors.create(error));
        deferred.resolve(response);
    });
    return deferred.promise;
};

Connection.prototype.close = function close()
{
    clearTimeout(this._connectTimeout);
    clearTimeout(this._pingTimer);
    clearTimeout(this._pingTimeout);

    this._connection.removeAllListeners();
    this._connection.end();
    this._connection.connection.destroy();
    this.emit('close');
};

Connection.prototype.setHealthy = function setHealthy(healthy)
{
    healthy = !!healthy;
    if (this.healthy != healthy)
    {
        this.healthy = healthy;
        this.emit('health', this);
    }
};

Connection.prototype.ping = function ping()
{
    var self = this,
        deferred = P.defer();

    if (this._isPinging)
        return;

    this._isPinging = true;
    this._pingTimeout = setTimeout(function()
    {
        self._isPinging = false;
        self.setHealthy(false);
        deferred.reject(new Error('Ping timed out.'));
    }, this.timeout);

    function updateHealth(healthy)
    {
        clearTimeout(self._pingTimeout);
        self._isPinging = false;
        self.setHealthy(healthy);
        self._pingTimer = setTimeout(self.pingBound, self.pingInterval);
        self.emit('ping', healthy);
    }

    self.executeCQL(Connection.PING_QUERY)
    .then(function()
    {
        updateHealth(true);
        deferred.resolve('good');
    }, function(err)
    {
        updateHealth(false);
        deferred.reject(err);
    })
    .done();

    return deferred.promise;
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Umb2Meteor.Models {
    public class ContentModel {
        public int Id { get; set; }
        public string Name { get; set; }
        public string NodeTypeAlias { get; set; }
        public string Path { get; set; }
        public int Parent { get; set; }
        public string UrlName { get; set; }
        public DateTime CreateDate { get; set; }
        public DateTime UpdateDate { get; set; }
        public string Url { get; set; }
        public int Level { get; set; }
        public string Template { get; set; }
        public int SortOrder { get; set; }
        public List<PropertyModel> Properties;
        public string NiceUrl { get; set; }
        public string CreatorName { get; set; }
        public string WriteName { get; set; }

        public ContentModel() {
            Properties = new List<PropertyModel>();
        }
    }

    public class PropertyModel {
        public string Alias { get; set; }
        public object Value { get; set; }
    }
}


text:
/*
 * debugfs interface
 */

#ifndef __DBGAUFS_H__
#define __DBGAUFS_H__

#ifdef __KERNEL__

struct super_block;
struct au_sbinfo;

#ifdef CONFIG_DEBUG_FS
/* dbgaufs.c */
void dbgaufs_brs_del(struct super_block *sb, aufs_bindex_t bindex);
void dbgaufs_brs_add(struct super_block *sb, aufs_bindex_t bindex);
void dbgaufs_si_fin(struct au_sbinfo *sbinfo);
int dbgaufs_si_init(struct au_sbinfo *sbinfo);
void dbgaufs_fin(void);
int __init dbgaufs_init(void);
#else
AuStubVoid(dbgaufs_brs_del, struct super_block *sb, aufs_bindex_t bindex)
AuStubVoid(dbgaufs_brs_add, struct super_block *sb, aufs_bindex_t bindex)
AuStubVoid(dbgaufs_si_fin, struct au_sbinfo *sbinfo)
AuStubInt0(dbgaufs_si_init, struct au_sbinfo *sbinfo)
AuStubVoid(dbgaufs_fin, void)
AuStubInt0(__init dbgaufs_init, void)
#endif /* CONFIG_DEBUG_FS */

#endif /* __KERNEL__ */
#endif /* __DBGAUFS_H__ */


text:
local Index, parent = torch.class('nn.Index', 'nn.Module')

function Index:__init(dimension)
    parent.__init(self)
    self.dimension = dimension
    self.gradInput = {self.gradInput}
end

function Index:updateOutput(input)
    local t = input[1]
    local index = input[2]
    self.output:index(t, self.dimension, index)
    return self.output
end

function Index:updateGradInput(input, gradOutput)
    local t = input[1]
    local index = input[2]

    local gradInput = self.gradInput[1] -- no gradient for the index variable
    gradInput:resizeAs(t):zero()
    gradInput:indexAdd(self.dimension, index, gradOutput)
    return self.gradInput
end


text:
struct Good {
  int operator<=>(const Good&) const;

  bool operator<(const Good&) const = default;
  bool operator>(const Good&) const = default;
  friend bool operator<=(const Good&, const Good&) = default;
  friend bool operator>=(const Good&, const Good&) = default;
};

enum Bool : bool {};
struct Bad {
  bool &operator<(const Bad&) const = default; // expected-error {{return type for defaulted relational comparison operator must be 'bool', not 'bool &'}}
  const bool operator>(const Bad&) const = default; // expected-error {{return type for defaulted relational comparison operator must be 'bool', not 'const bool'}}
  friend Bool operator<=(const Bad&, const Bad&) = default; // expected-error {{return type for defaulted relational comparison operator must be 'bool', not 'Bool'}}
  friend int operator>=(const Bad&, const Bad&) = default; // expected-error {{return type for defaulted relational comparison operator must be 'bool', not 'int'}}
};

template<typename T> struct Ugly {
  T operator<(const Ugly&) const = default; // expected-error {{return type}}
  T operator>(const Ugly&) const = default; // expected-error {{return type}}
  friend T operator<=(const Ugly&, const Ugly&) = default; // expected-error {{return type}}
  friend T operator>=(const Ugly&, const Ugly&) = default; // expected-error {{return type}}
};
template struct Ugly<bool>;
template struct Ugly<int>; // expected-note {{in instantiation of}}


text:
<?php

namespace PPI\Framework\Console\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Yaml\Dumper;

/**
 * Outputs all the configuration processed by the Framework, after merging.
 *
 * @author      Vítor Brandão <vitor@ppi.io>
 */
class ConfigDebugCommand extends AbstractCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('config:debug')
            ->setDescription('Dumps the configuration in use')
            ->addOption('app-only', null, InputOption::VALUE_NONE, 'Show only the configuration set in the app/ directory')
            ->addOption('write-php', null, InputOption::VALUE_REQUIRED, 'Save the configuration in PHP format')
            ->addOption('write-yaml', null, InputOption::VALUE_REQUIRED, 'Save the configuration in YAML format')
            ->setHelp(<<<EOF
The <info>%command.name%</info> command dumps the configuration after being merged and processed
by the framework:

  <info>%command.full_name%</info>

If you only want to see the configuration defined in the app/ directory (excluding modules)
use the <info>--app-only</info> option. This is the "raw" configuration, not processed by the framework.

  <info>%command.full_name% --app-only</info>
EOF
            );
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $indentation = 4;

        if ($input->getOption('app-only')) {
            $message = "This is the configuration defined in the app/ directory (not processed):\n";
            $config  = $this->getServiceManager()->get('ApplicationConfig');
        } else {
            $message = "This is the configuration in use for your current setup (merged and processed):\n";
            $config  = $this->getServiceManager()->get('Config');
        }

        $files    = array();
        $contents = array();

        if (($files['php'] = $input->getOption('write-php'))) {
            $contents['php'] = "<?php\n\nreturn " . var_export($config, true) . ";\n\n?>\n";
        }

        if (($files['yaml'] = $input->getOption('write-yaml'))) {
            $dumper = new Dumper();
            $dumper->setIndentation($indentation);
            $contents['yaml'] = $dumper->dump($config, 6, 0, false, false);
        }

        if (empty($contents)) {
            $dumper = new Dumper();
            $dumper->setIndentation($indentation);
            $output->writeln($message);

            foreach ($config as $rootKey => $subConfig) {
                $output->writeln('<info>' . $rootKey . '</info>:');
                $output->writeln($dumper->dump($subConfig, 6, $indentation, false, false));
            }

            return;
        }

        foreach ($files as $format => $file) {
            $output->write('Saving configuration in <info>' . strtoupper($format) . '</info> format...');
            if ($fileExists = file_exists($file)) {
                if (!isset($dialog)) {
                    $dialog = $this->getHelperSet()->get('dialog');
                }
                if (!$dialog->askConfirmation($output,
                    " <question>File \"" . $file . "\" already exists. Proceed anyway?</question> ", false)) {
                    continue;
                }
            }

            file_put_contents($file, $contents[$format]);

            if (!$fileExists) {
                $output->writeln(' OK.');
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
                     debug="false">

  <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
    <param name="Target" value="System.out"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern"
             value="%d{dd MMM yyyy HH:mm:ss.SSS} - %25t - %-5p - %30c{1} - (%C{1}.java:%L) - %m%n"/>
    </layout>
  </appender>

  <appender name="fileAppender" class="org.apache.log4j.FileAppender">
    <param name="File" value="/tmp/debug.log"/>
    <param name="Append" value="false"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern"
             value="%d{dd MMM yyyy HH:mm:ss.SSS} - %25t - %-5p - %30c{1} - (%C{1}.java:%L) - %m%n"/>
    </layout>
  </appender>

  <appender name="asyncAppender" class="org.apache.log4j.AsyncAppender">
    <!-- appender-ref ref="consoleAppender" / -->
    <appender-ref ref="fileAppender"/>
  </appender>

  <!-- SSL is chatty logs -->
  <category name="com.thoughtworks.studios.platform.net.EasyX509TrustManager">
    <priority value="NONE"/>
  </category>

  <category name="org.apache.commons.httpclient">
    <priority value="INFO"/>
  </category>

  <root>
    <priority value="INFO"/>
    <appender-ref ref="consoleAppender"/>
    <appender-ref ref="fileAppender"/>
  </root>

</log4j:configuration>


text:
layout: page
title: Lozano Electronics Show
date: 2016-05-24
author: Rachel Lang
tags: weekly links, java
status: published
summary: Aliquam erat volutpat. Nam rutrum, neque.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 09/15/2019
  endDate: 09/19/2019
  ctyhocn: VSKTCHX
  groupCode: LES
published: true
---
Pellentesque sit amet neque lectus. Donec eu malesuada ligula. Praesent a sollicitudin neque. Donec sagittis tellus a mi mattis, et efficitur magna malesuada. In dictum aliquet mauris eget sodales. Nunc eleifend metus tortor, quis finibus turpis maximus nec. Suspendisse aliquam sed lacus eget sollicitudin.
Praesent et quam luctus elit ultricies feugiat. Curabitur eget eros arcu. Curabitur et molestie sem. Cras ac eros arcu. Vivamus ac sagittis erat. Morbi bibendum nec ex sed blandit. Aenean in diam ante. Nam tellus justo, rutrum sit amet ex in, congue pharetra sapien. Maecenas vulputate eros a suscipit gravida. Donec vel sapien non augue iaculis aliquet in ac felis.

* Pellentesque non odio sed nunc mollis pharetra ullamcorper sit amet tellus
* Aliquam ut nisl ut neque sollicitudin feugiat quis non lorem
* Phasellus vestibulum neque et est suscipit sagittis quis at mi
* Pellentesque in tortor sed dolor ornare congue eget molestie tortor
* Phasellus blandit metus at arcu tempus tincidunt
* Sed congue mi nec mattis viverra.

Nulla lectus magna, tincidunt nec ex a, suscipit egestas purus. Sed tristique gravida enim nec euismod. Aliquam convallis nisi ac dolor aliquet, ac finibus sapien venenatis. Quisque consectetur pharetra sapien, in rhoncus nibh euismod at. Proin rutrum ipsum sagittis orci lobortis, vitae blandit est maximus. Fusce quis consectetur lorem. Suspendisse justo ligula, venenatis ac congue id, semper eget metus.