text:
from __future__ import absolute_import

import six

from sentry.api.serializers import serialize
from sentry.models import EventUser, GroupTagValue, TagValue
from sentry.testutils import TestCase

class GroupTagValueSerializerTest(TestCase):
    def test_with_user(self):
        user = self.create_user()
        project = self.create_project()
        euser = EventUser.objects.create(
            project=project,
            email='foo@example.com',
        )
        tagvalue = TagValue.objects.create(
            project=project,
            key='sentry:user',
            value=euser.tag_value,
        )
        grouptagvalue = GroupTagValue.objects.create(
            project_id=project.id,
            group_id=self.create_group(project=project).id,
            key=tagvalue.key,
            value=tagvalue.value,
        )

        result = serialize(grouptagvalue, user)
        assert result['id'] == six.text_type(grouptagvalue.id)
        assert result['key'] == 'user'
        assert result['value'] == grouptagvalue.value
        assert result['name'] == euser.get_label()

    def test_with_no_tagvalue(self):
        user = self.create_user()
        project = self.create_project()
        grouptagvalue = GroupTagValue.objects.create(
            project_id=project.id,
            group_id=self.create_group(project=project).id,
            key='sentry:user',
            value='email:foo@example.com',
        )

        result = serialize(grouptagvalue, user)
        assert result['id'] == six.text_type(grouptagvalue.id)
        assert result['key'] == 'user'
        assert result['value'] == grouptagvalue.value
        assert result['name'] == grouptagvalue.value


text:
package org.docksidestage.postgresql.dbflute.bsentity;

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

import org.dbflute.dbmeta.DBMeta;
import org.dbflute.dbmeta.AbstractEntity;
import org.dbflute.dbmeta.accessory.DomainEntity;
import org.docksidestage.postgresql.dbflute.allcommon.DBMetaInstanceHandler;
import org.docksidestage.postgresql.dbflute.exentity.*;

/**
 * The entity of white_compound_pk as TABLE.

 *

 * [primary-key]
 *     pk_first_id, pk_second_id
 *
 * [column]
 *     pk_first_id, pk_second_id, pk_name
 *
 * [sequence]
 *
 *
 * [identity]
 *
 *
 * [version-no]
 *
 *
 * [foreign table]
 *
 *
 * [referrer table]
 *     white_compound_pk_ref
 *
 * [foreign property]
 *
 *
 * [referrer property]
 *     whiteCompoundPkRefList
 *
 * [get/set template]
 * /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
 * Integer pkFirstId = entity.getPkFirstId();
 * Integer pkSecondId = entity.getPkSecondId();
 * String pkName = entity.getPkName();
 * entity.setPkFirstId(pkFirstId);
 * entity.setPkSecondId(pkSecondId);
 * entity.setPkName(pkName);
 * = = = = = = = = = =/
 *

 * @author DBFlute(AutoGenerator)
 */
public abstract class BsWhiteCompoundPk extends AbstractEntity implements DomainEntity {

    // ===================================================================================
    //                                                                          Definition
    //                                                                          ==========
    /** The serial version UID for object serialization. (Default) */
    private static final long serialVersionUID = 1L;

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    /** pk_first_id: {PK, NotNull, int4(10)} */
    protected Integer _pkFirstId;

    /** pk_second_id: {PK, NotNull, int4(10)} */
    protected Integer _pkSecondId;

    /** pk_name: {NotNull, varchar(200)} */
    protected String _pkName;

    // ===================================================================================
    //                                                                             DB Meta
    //                                                                             =======
    /** {@inheritDoc} */
    public DBMeta asDBMeta() {
        return DBMetaInstanceHandler.findDBMeta(asTableDbName());
    }

    /** {@inheritDoc} */
    public String asTableDbName() {
        return "white_compound_pk";
    }

    // ===================================================================================
    //                                                                        Key Handling
    //                                                                        ============
    /** {@inheritDoc} */
    public boolean hasPrimaryKeyValue() {
        if (_pkFirstId == null) { return false; }
        if (_pkSecondId == null) { return false; }
        return true;
    }

    // ===================================================================================
    //                                                                    Foreign Property
    //                                                                    ================
    // ===================================================================================
    //                                                                   Referrer Property
    //                                                                   =================
    /** white_compound_pk_ref by ref_first_id, ref_second_id, named 'whiteCompoundPkRefList'. */
    protected List<WhiteCompoundPkRef> _whiteCompoundPkRefList;

    /**
     * [get] white_compound_pk_ref by ref_first_id, ref_second_id, named 'whiteCompoundPkRefList'.
     * @return The entity list of referrer property 'whiteCompoundPkRefList'. (NotNull: even if no loading, returns empty list)
     */
    public List<WhiteCompoundPkRef> getWhiteCompoundPkRefList() {
        if (_whiteCompoundPkRefList == null) { _whiteCompoundPkRefList = newReferrerList(); }
        return _whiteCompoundPkRefList;
    }

    /**
     * [set] white_compound_pk_ref by ref_first_id, ref_second_id, named 'whiteCompoundPkRefList'.
     * @param whiteCompoundPkRefList The entity list of referrer property 'whiteCompoundPkRefList'. (NullAllowed)
     */
    public void setWhiteCompoundPkRefList(List<WhiteCompoundPkRef> whiteCompoundPkRefList) {
        _whiteCompoundPkRefList = whiteCompoundPkRefList;
    }

    protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import
        return new ArrayList<ELEMENT>();
    }

    // ===================================================================================
    //                                                                      Basic Override
    //                                                                      ==============
    @Override
    protected boolean doEquals(Object obj) {
        if (obj instanceof BsWhiteCompoundPk) {
            BsWhiteCompoundPk other = (BsWhiteCompoundPk)obj;
            if (!xSV(_pkFirstId, other._pkFirstId)) { return false; }
            if (!xSV(_pkSecondId, other._pkSecondId)) { return false; }
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected int doHashCode(int initial) {
        int hs = initial;
        hs = xCH(hs, asTableDbName());
        hs = xCH(hs, _pkFirstId);
        hs = xCH(hs, _pkSecondId);
        return hs;
    }

    @Override
    protected String doBuildStringWithRelation(String li) {
        StringBuilder sb = new StringBuilder();
        if (_whiteCompoundPkRefList != null) { for (WhiteCompoundPkRef et : _whiteCompoundPkRefList)
        { if (et != null) { sb.append(li).append(xbRDS(et, "whiteCompoundPkRefList")); } } }
        return sb.toString();
    }

    @Override
    protected String doBuildColumnString(String dm) {
        StringBuilder sb = new StringBuilder();
        sb.append(dm).append(xfND(_pkFirstId));
        sb.append(dm).append(xfND(_pkSecondId));
        sb.append(dm).append(xfND(_pkName));
        if (sb.length() > dm.length()) {
            sb.delete(0, dm.length());
        }
        sb.insert(0, "{").append("}");
        return sb.toString();
    }

    @Override
    protected String doBuildRelationString(String dm) {
        StringBuilder sb = new StringBuilder();
        if (_whiteCompoundPkRefList != null && !_whiteCompoundPkRefList.isEmpty())
        { sb.append(dm).append("whiteCompoundPkRefList"); }
        if (sb.length() > dm.length()) {
            sb.delete(0, dm.length()).insert(0, "(").append(")");
        }
        return sb.toString();
    }

    @Override
    public WhiteCompoundPk clone() {
        return (WhiteCompoundPk)super.clone();
    }

    // ===================================================================================
    //                                                                            Accessor
    //                                                                            ========
    /**
     * [get] pk_first_id: {PK, NotNull, int4(10)}

     * @return The value of the column 'pk_first_id'. (basically NotNull if selected: for the constraint)
     */
    public Integer getPkFirstId() {
        checkSpecifiedProperty("pkFirstId");
        return _pkFirstId;
    }

    /**
     * [set] pk_first_id: {PK, NotNull, int4(10)}

     * @param pkFirstId The value of the column 'pk_first_id'. (basically NotNull if update: for the constraint)
     */
    public void setPkFirstId(Integer pkFirstId) {
        registerModifiedProperty("pkFirstId");
        _pkFirstId = pkFirstId;
    }

    /**
     * [get] pk_second_id: {PK, NotNull, int4(10)}

     * @return The value of the column 'pk_second_id'. (basically NotNull if selected: for the constraint)
     */
    public Integer getPkSecondId() {
        checkSpecifiedProperty("pkSecondId");
        return _pkSecondId;
    }

    /**
     * [set] pk_second_id: {PK, NotNull, int4(10)}

     * @param pkSecondId The value of the column 'pk_second_id'. (basically NotNull if update: for the constraint)
     */
    public void setPkSecondId(Integer pkSecondId) {
        registerModifiedProperty("pkSecondId");
        _pkSecondId = pkSecondId;
    }

    /**
     * [get] pk_name: {NotNull, varchar(200)}

     * @return The value of the column 'pk_name'. (basically NotNull if selected: for the constraint)
     */
    public String getPkName() {
        checkSpecifiedProperty("pkName");
        return _pkName;
    }

    /**
     * [set] pk_name: {NotNull, varchar(200)}

     * @param pkName The value of the column 'pk_name'. (basically NotNull if update: for the constraint)
     */
    public void setPkName(String pkName) {
        registerModifiedProperty("pkName");
        _pkName = pkName;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Text.RegularExpressions;
using System.Diagnostics;
using System;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI;
using Microsoft.Win32;
using WeifenLuo;
using System.Runtime.InteropServices;
using SoftLogik.Win.UI.Docking.Win32;

// *****************************************************************************
//
//  Copyright 2004, Weifen Luo
//  All rights reserved. The software and associated documentation
//  supplied hereunder are the proprietary information of Weifen Luo
//  and are supplied subject to licence terms.
//
//  WinFormsUI Library Version 1.0
// *****************************************************************************

namespace SoftLogik.Win
{
	namespace UI
	{
		namespace Docking
		{

			internal class User32
			{

				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool AnimateWindow(IntPtr hWnd, UInt32 dwTime, SoftLogik.Win.UI.Docking.Win32.FlagsAnimateWindow dwFlags);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool DragDetect(IntPtr hWnd, UI.Docking.Win32.POINT pt);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr GetSysColorBrush(int index);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool InvalidateRect(IntPtr hWnd, ref RECT rect, bool @erase);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr LoadCursor(IntPtr hInstance, UInt32 cursor);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr SetCursor(IntPtr hCursor);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr GetFocus();
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr SetFocus(IntPtr hWnd);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool ReleaseCapture();
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool WaitMessage();
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool TranslateMessage(ref MSG msg);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool DispatchMessage(ref MSG msg);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool PostMessage(IntPtr hWnd, int Msg, UInt32 wParam, UInt32 lParam);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern UInt32 SendMessage(IntPtr hWnd, int Msg, UInt32 wParam, UInt32 lParam);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern UInt32 SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool GetMessage(ref MSG msg, int hWnd, UInt32 wFilterMin, UInt32 wFilterMax);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool PeekMessage(ref MSG msg, int hWnd, UInt32 wFilterMin, UInt32 wFilterMax, UInt32 wFlag);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr BeginPaint(IntPtr hWnd, ref PAINTSTRUCT ps);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool EndPaint(IntPtr hWnd, ref PAINTSTRUCT ps);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr GetDC(IntPtr hWnd);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr GetWindowDC(IntPtr hWnd);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern int ShowWindow(IntPtr hWnd, short cmdShow);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool MoveWindow(IntPtr hWnd, int x, int y, int width, int height, bool repaint);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern int SetWindowPos(IntPtr hWnd, IntPtr hWndAfter, int X, int Y, int Width, int Height, SoftLogik.Win.UI.Docking.Win32.FlagsSetWindowPos flags);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref UI.Docking.Win32.POINT pptDst, ref UI.Docking.Win32.SIZE psize, IntPtr hdcSrc, ref UI.Docking.Win32.POINT pprSrc, int crKey, ref BLENDFUNCTION pblend, int dwFlags);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool ClientToScreen(IntPtr hWnd, ref UI.Docking.Win32.POINT pt);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool ScreenToClient(IntPtr hWnd, ref UI.Docking.Win32.POINT pt);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool TrackMouseEvent(ref TRACKMOUSEEVENTS tme);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool redraw);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern UInt16 GetKeyState(int virtKey);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr GetParent(IntPtr hWnd);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool DrawFocusRect(IntPtr hWnd, ref RECT rect);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool HideCaret(IntPtr hWnd);
				[DllImport("User32.dll", CharSet = CharSet.Auto)]public static  extern bool ShowCaret(IntPtr hWnd);
				[DllImport("user32.dll", CharSet = CharSet.Auto)]public static  extern bool SystemParametersInfo(SoftLogik.Win.UI.Docking.Win32.SystemParametersInfoActions uAction, UInt32 uParam, ref UInt32 lpvParam, UInt32 fuWinIni);
				[DllImport("user32.dll", CharSet = CharSet.Auto)]public static  extern IntPtr WindowFromPoint(UI.Docking.Win32.POINT point);
			}
		}
	}

}


text:
(function() {
    "use strict";

    function addPlayerBoundary (entity) {
        entity.on("update", function(e) {
            entity.pos.y = (entity.pos.y+640)%640;
            if(entity.pos.x<10) {
                entity.pos.x=10;
            } else if(entity.pos.x>950) {
                entity.pos.x=950;
            }
        });
    }

    /*********************************************************\
        MULTI EXPORT
    \*********************************************************/

    if (typeof exports === 'object') {
        module.exports = addPlayerBoundary;
    } else if (typeof define === 'function') {
        define(function() { return addPlayerBoundary; });
    } else if (typeof GrifGame === 'object') {
        GrifGame.addPlayerBoundary = addPlayerBoundary;
    } else {
        this.addPlayerBoundary = addPlayerBoundary;
    }
}).call(function() {
    return this || (typeof window !== 'undefined' ? window : global);
}());


text:
package org.redisson;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.redisson.api.RBlockingDeque;

public class RedissonPriorityBlockingDequeTest extends BaseTest {

    @Test(timeout = 3000)
    public void testShortPoll() throws InterruptedException {
        RBlockingDeque<Integer> queue = redisson.getPriorityBlockingDeque("queue:pollany");
        queue.pollLastAsync(500, TimeUnit.MILLISECONDS);
        queue.pollFirstAsync(10, TimeUnit.MICROSECONDS);
    }

    @Test
    public void testTakeFirst() throws InterruptedException {
        RBlockingDeque<Integer> deque = redisson.getPriorityBlockingDeque("queue:take");

        deque.add(1);
        deque.add(2);
        deque.add(3);
        deque.add(4);

        assertThat(deque.takeFirst()).isEqualTo(1);
        assertThat(deque.takeFirst()).isEqualTo(2);
        assertThat(deque.takeFirst()).isEqualTo(3);
        assertThat(deque.takeFirst()).isEqualTo(4);
        assertThat(deque.size()).isZero();
    }

    @Test
    public void testTakeLast() throws InterruptedException {
        RBlockingDeque<Integer> deque = redisson.getPriorityBlockingDeque("queue:take");

        deque.add(1);
        deque.add(2);
        deque.add(3);
        deque.add(4);

        assertThat(deque.takeLast()).isEqualTo(4);
        assertThat(deque.takeLast()).isEqualTo(3);
        assertThat(deque.takeLast()).isEqualTo(2);
        assertThat(deque.takeLast()).isEqualTo(1);
        assertThat(deque.size()).isZero();
    }

    @Test
    public void testTakeFirstAwait() throws InterruptedException {
        RBlockingDeque<Integer> deque = redisson.getPriorityBlockingDeque("queue:take");
        Executors.newSingleThreadScheduledExecutor().schedule(() -> {
            RBlockingDeque<Integer> deque1 = redisson.getBlockingDeque("queue:take");
            deque1.add(1);
            deque1.add(2);
            deque1.add(3);
            deque1.add(4);
        }, 10, TimeUnit.SECONDS);

        long s = System.currentTimeMillis();
        assertThat(deque.takeFirst()).isEqualTo(1);
        assertThat(System.currentTimeMillis() - s).isGreaterThan(9000);
        Thread.sleep(50);
        assertThat(deque.takeFirst()).isEqualTo(2);
        assertThat(deque.takeFirst()).isEqualTo(3);
        assertThat(deque.takeFirst()).isEqualTo(4);
    }

    @Test
    public void testTakeLastAwait() throws InterruptedException {
        RBlockingDeque<Integer> deque = redisson.getPriorityBlockingDeque("queue:take");
        Executors.newSingleThreadScheduledExecutor().schedule(() -> {
            RBlockingDeque<Integer> deque1 = redisson.getBlockingDeque("queue:take");
            deque1.add(1);
            deque1.add(2);
            deque1.add(3);
            deque1.add(4);
        }, 10, TimeUnit.SECONDS);

        long s = System.currentTimeMillis();
        assertThat(deque.takeLast()).isEqualTo(4);
        assertThat(System.currentTimeMillis() - s).isGreaterThan(9000);
        Thread.sleep(50);
        assertThat(deque.takeLast()).isEqualTo(3);
        assertThat(deque.takeLast()).isEqualTo(2);
        assertThat(deque.takeLast()).isEqualTo(1);
    }

    @Test
    public void testPollFirst() throws InterruptedException {
        RBlockingDeque<Integer> queue1 = redisson.getPriorityBlockingDeque("queue1");
        queue1.put(1);
        queue1.put(2);
        queue1.put(3);

        assertThat(queue1.pollFirst(2, TimeUnit.SECONDS)).isEqualTo(1);
        assertThat(queue1.pollFirst(2, TimeUnit.SECONDS)).isEqualTo(2);
        assertThat(queue1.pollFirst(2, TimeUnit.SECONDS)).isEqualTo(3);

        long s = System.currentTimeMillis();
        assertThat(queue1.pollFirst(5, TimeUnit.SECONDS)).isNull();
        assertThat(System.currentTimeMillis() - s).isGreaterThan(4900);
    }

    @Test
    public void testPollLast() throws InterruptedException {
        RBlockingDeque<Integer> queue1 = redisson.getPriorityBlockingDeque("queue1");
        queue1.add(3);
        queue1.add(1);
        queue1.add(2);

        assertThat(queue1.pollLast(2, TimeUnit.SECONDS)).isEqualTo(3);
        assertThat(queue1.pollLast(2, TimeUnit.SECONDS)).isEqualTo(2);
        assertThat(queue1.pollLast(2, TimeUnit.SECONDS)).isEqualTo(1);

        long s = System.currentTimeMillis();
        assertThat(queue1.pollLast(5, TimeUnit.SECONDS)).isNull();
        assertThat(System.currentTimeMillis() - s).isGreaterThanOrEqualTo(5000);
    }

}


text:
package org.jesterj.ingest.forkjoin;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.function.Function;

import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/*
 * Created with IntelliJ IDEA.
 * User: gus
 * Date: 9/12/16
 */
public class JesterJForkJoinTest {

  @Test
  public void testForkJoin() throws ExecutionException, InterruptedException {
    List<String> data = new ArrayList<>();
    data.add("foo");
    data.add("bar");
    data.add("baz");

    Thread thread = Thread.currentThread();
    ForkJoinPool forkJoinPool = new ForkJoinPool(2);
    forkJoinPool.submit(() ->
        //parallel task here, for example
        data.stream().parallel().map(new Function<String, Object>() {
          @Override
          public Object apply(String s) {
            assertFalse(Thread.currentThread().getClass() == NotSoInnocuousWorkerThread.class);
            return s.toUpperCase();
          }
        }).collect(toList())
    ).get();
    ForkJoinPool forkJoinPool2 = new ForkJoinPool(4, new JesterJForkJoinThreadFactory(), null, true);
    forkJoinPool2.submit(() ->
        //parallel task here, for example
        data.stream().parallel().map(new Function<String, Object>() {
          @Override
          public Object apply(String s) {
            Class<? extends Thread> threadClass = Thread.currentThread().getClass();
            System.out.println(threadClass);
            assertTrue(threadClass == NotSoInnocuousWorkerThread.class);
            return s.toUpperCase();
          }
        }).collect(toList())
    ).get();
  }
}


text:
using namespace boost::python;
using namespace sparse_block_matrix;

template<typename SBM>
void clearSBM(SBM * sbm) { sbm->clear(); }

template<typename SBM>
typename SBM::SparseMatrixBlock blockSBM(const SBM * sbm,int r, int c) {
  if(r < 0 || r >= sbm->bRows())
    throw std::runtime_error("Row index out of bounds");
  if(c < 0 || c >= sbm->bCols())
    throw std::runtime_error("Column index out of bounds");

  const typename SBM::SparseMatrixBlock * mat = sbm->block(r,c);
  if(mat)
    {
      return *mat;
    }
  else
    {
      typename SBM::SparseMatrixBlock rval;
      rval.resize(sbm->rowsOfBlock(r), sbm->colsOfBlock(c));
      rval.setZero();
      return rval;
    }
}

template<typename SBM>
void setBlockSBM(SBM * sbm, int r, int c, const typename SBM::SparseMatrixBlock & mat) {
  if(r < 0 || r >= sbm->bRows())
    throw std::runtime_error("Row index out of bounds");
  if(c < 0 || c >= sbm->bCols())
    throw std::runtime_error("Column index out of bounds");

  typename SBM::SparseMatrixBlock * blk = sbm->block(r,c,true);
  if(!blk)
    throw std::runtime_error("Unexpected error: block is null");

  *blk = mat;

}

template<typename SBM>
Eigen::MatrixXd toDenseSymmetric(SBM * sbm)
{
  //return sbm->toDense().selfadjointView<Eigen::Upper>();
  return sbm->toDense(). template selfadjointView<Eigen::Upper>();
}

template<typename SBM>
double at(SBM * sbm, int r, int c)
{
    return (*sbm)(r,c);
}

void exportSBM()
{
  typedef SparseBlockMatrix<Eigen::MatrixXd> mat_t;

  boost::python::class_< mat_t > ("SparseBlockMatrixXd", init<>())
    .def(init<const Eigen::VectorXi &, const Eigen::VectorXi &, bool>( ("SparseBlockMatrixXd(rbi, cbi, hasStorage)\n\nrbi:  a vector of ints containing the row layout of the blocks. The component i of the array should contain the index of the first row of the block i+1\ncbi:  a vector of ints containing the column layout of the blocks. The component i of the array should contain the index of the first column of the block i+1")) )
    .def("rows",&mat_t::rows)
    .def("cols",&mat_t::cols)
    .def("bRows",&mat_t::bRows)
    .def("bCols",&mat_t::bCols)
    .def("clear",&clearSBM<mat_t>)
    .def("clear",&mat_t::clear)
    .def("isBlockSet",&mat_t::isBlockSet)
    .def("getBlock",&blockSBM<mat_t>)
    .def("setBlock",&setBlockSBM<mat_t>)
    .def("rowsOfBlock",&mat_t::rowsOfBlock)
    .def("colsOfBlock",&mat_t::colsOfBlock)
    .def("rowBaseOfBlock",&mat_t::rowBaseOfBlock)
    .def("colBaseOfBlock",&mat_t::colBaseOfBlock)
    .def("nonZeros",&mat_t::nonZeros)
    .def("nonZeroBlocks",&mat_t::nonZeroBlocks)
    .def("clone", &mat_t::clone, return_value_policy<manage_new_object>())
    .def("toDense", &mat_t::toDense)
    .def("toDenseSymmetric", &toDenseSymmetric<mat_t>)
      .def("at", &at<mat_t>)
    // Still more to do here, but this is the easy stuff that will allow us to look
    // at one of these things in Python.
    ;

}


text:
<?php

namespace JekyllImporter;

use JekyllImporter\FileHandlerException;

/**
 * Class FileHandler
 *
 * @author Adriano Rosa (http://adrianorosa.com)
 * @link https://github.com/adrianorsouza/wordpress-jekyll-importer
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
 */
class FileHandler
{
    private $_result = [];

    /**
     * Write Files
     *
     * @param string
     * @throws JekyllImporter\FileHandlerException
     */
    public function write($filename, $content)
    {
        if ( !is_dir( dirname($filename) ) ) {
            throw new FileHandlerException(
                sprintf('Directory not found: %s', dirname($filename))
            );

            return false;
        }

        $success_message = ( !file_exists($filename) ) ? "Created new file --> %s" : "Updated file --> %s";

        if ( ! $handle = @fopen($filename, 'w')) {
            throw new FileHandlerException(
                sprintf('Unable to read a file %s due the file permissions', $filename)
            );

            return false;
        }

        flock($handle, LOCK_EX);

        if ( fwrite($handle, $content) === FALSE ) {
            throw new FileHandlerException(
                sprintf("Unable to write a file %s due the file permissions --> %s", $filename)
            );

            return false;
        }

        flock($handle, LOCK_UN);
        fclose($handle);

        $this->setOutput('success', sprintf($success_message, $filename));

        return $this;
    }

    /**
     * Clear directory Files
     *
     * @param string $path The directory to unlink files
     * @throws JekyllImporter\FileHandlerException
     */
    function clearDir($path)
    {
        $path = rtrim($path, '/\\');

        if (is_dir($path)) {
            if ($dh = opendir($path)) {

                while (($filename = readdir($dh)) !== false) {

                    if ( $filename !== '.' && $filename !== '..' ) {

                        if ( FALSE === @unlink( $path . DIRECTORY_SEPARATOR . $filename) ) {

                            throw new FileHandlerException(
                                sprintf('Permission Denied: Unable to unlink %s', $filename)
                            );
                            return false;
                        }
                    }
                }
                closedir($dh);
            }
        }
    }

    public function setOutput($type, $string = null)
    {
        if ( $type === 'success' ) {

            $message = sprintf("✔ %s", $string);
            $pretty = "\033[0;32m";

        } else {

            $message = sprintf("✗ Error %s", $string);
            $pretty = "\033[0;31m";
        }

        $message = $pretty . $message . "\033[0m" . PHP_EOL;

        $this->_result[][$type] = $message;

        return $this;
    }

    public function getOutput()
    {
        $output = '';
        $count = 0;

        foreach ($this->_result as $result) {

            if ( isset($result['success']) ) {
                $output .= $result['success'];
            } elseif ( isset($result['error']) ) {
                $count --;
                $output .= $result['error'];
            }

            $count++;
        }

        $output .= "------------------------------". PHP_EOL;
        $output .= $count . ' files has been created' . PHP_EOL;
        $output .= "------------------------------". PHP_EOL;
        return $output;
    }
}


text:
using System;
using System.Runtime.InteropServices;

internal partial class Interop
{
    internal partial class Kernel32
    {
        [DllImport(Libraries.Kernel32, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool GetSystemTimes(out ulong idleTime, out ulong kernelTime, out ulong userTime);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using stCore;
using stClient;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Text.RegularExpressions;

namespace stCoCClient
{
    public partial class ClientForm
    {
        private static object webwLock = null;
        private stClient.IrcClient Irc = null;
        private const string _sysNoticeTag = @"IRC System";

        #region CALLBACK

        private void _InitIrcCallBack()
        {

            #region USER MATHCH

            this.Irc.OnUserUpdate += (o, e) =>
            {
                if (e.UserList.Length > 0)
                {
                    foreach (string user in e.UserList)
                    {
                        if (user.Length == 0)
                        {
                            continue;
                        }
                        this.ChatUserListAdd(user);
                    }
                    this.ChatUserListSortColor();
                    this.SetChatUserListAutocomplete();
                }
            };
            this.Irc.OnUserJoined += (o, e) =>
            {
                if (!string.IsNullOrWhiteSpace(e.User))
                {
                    this.ChatUserListAdd(e.User);
                    if (!Properties.Settings.Default.IRCNoticeMessage)
                    {
                        lock (webwLock)
                        {
                            this.WBChat.Document.InvokeScript("MsgPrn",
                                new object[] {
                                    "msgnotice",
                                    e.User,
                                    e.Channel + " + " + e.User
                                }
                            );
                        }
                    }
                }
            };
            this.Irc.OnUserLeft += (o, e) =>
            {
                if (!string.IsNullOrWhiteSpace(e.User))
                {
                    this.ChatUserListDel(e.User);
                    if (!Properties.Settings.Default.IRCNoticeMessage)
                    {
                        lock (webwLock)
                        {
                            this.WBChat.Document.InvokeScript("MsgPrn",
                                new object[] {
                                    "msgnotice",
                                    e.User,
                                    e.Channel + " - " + e.User
                                }
                            );
                        }
                    }
                }
            };
            this.Irc.OnUserKick += (o, e) =>
            {
                if (!string.IsNullOrWhiteSpace(e.User))
                {
                    this.ChatUserListDel(e.User);
                    if (!Properties.Settings.Default.IRCNoticeMessage)
                    {
                        lock (webwLock)
                        {
                            this.WBChat.Document.InvokeScript("MsgPrn",
                                new object[] {
                                    "msgnotice",
                                    e.User,
                                    e.Channel + " KICK " + e.User + " : " + e.Message
                                }
                            );
                        }
                    }
                }
            };
            this.Irc.OnUserNickChange += (o, e) =>
            {
                string Unew = ((string.IsNullOrWhiteSpace(e.New)) ? String.Empty : e.New),
                       Uold = ((string.IsNullOrWhiteSpace(e.Old)) ? String.Empty : e.Old);

                this.ChatUserListAdd(Unew);
                this.ChatUserListDel(Uold);

                if (!Properties.Settings.Default.IRCNoticeMessage)
                {
                    lock (webwLock)
                    {
                        this.WBChat.Document.InvokeScript("MsgPrn",
                            new object[] {
                                    "msgnotice",
                                    Unew,
                                    "NICK Change: " + Uold + " -> " + Unew
                                }
                        );
                    }
                }
            };

            #endregion

            #region CHANNEL/SERVER MESSAGE

            this.Irc.OnMessageServer += (o, e) =>
            {
                if (string.IsNullOrWhiteSpace(e.Result))
                {
                    return;
                }
                if (Properties.Settings.Default.IRCServerMessage)
                {
                    lock (webwLock)
                    {
                        this.WBChat.Document.InvokeScript("MsgPrn",
                            new object[] {
                                "msgserver",
                                "",
                                e.Result.TrimEnd(new char [] { '\n', '\r', ' '})
                            }
                        );
                    }
                }
            };
            this.Irc.OnMessageChannel += (o, e) =>
            {
                if (string.IsNullOrWhiteSpace(e.Message))
                {
                    return;
                }
                lock (webwLock)
                {
                    this.WBChat.Document.InvokeScript("MsgPrn",
                        new object[] {
                            "msguser",
                            e.From,
                            this._IRCChatToHTML(e.Message)
                        }
                    );
                }
                if (this.isMinimized)
                {
                    this.notifyIconMain_Balloon(
                        e.Message,
                        string.Format(
                            Properties.Resources.fmtIRCBallonTitle,
                            e.From,
                            ""
                        ),
                        ToolTipIcon.None,
                        3000
                    );
                }
            };
            this.Irc.OnMessagePrivate += (o, e) =>
            {
                if (string.IsNullOrWhiteSpace(e.Message))
                {
                    return;
                }
                if (Properties.Settings.Default.IRCPrivateMessage)
                {
                    lock (webwLock)
                    {
                        this.WBChat.Document.InvokeScript("MsgPrn",
                            new object[] {
                                "msgpriv",
                                e.From,
                                this._IRCChatToHTML(e.Message)
                            }
                        );
                    }
                    if (this.isMinimized)
                    {
                        this.notifyIconMain_Balloon(
                            e.Message,
                            string.Format(
                                Properties.Resources.fmtIRCBallonTitle,
                                Properties.Resources.txtIRCForYouMessage,
                                e.From
                            ),
                            ToolTipIcon.None,
                            3000
                        );
                    }
                }
            };
            this.Irc.OnMessageNotice += (o, e) =>
            {
                if (string.IsNullOrWhiteSpace(e.Message))
                {
                    return;
                }
                if (Properties.Settings.Default.IRCNoticeMessage)
                {
                    lock (webwLock)
                    {
                        this.WBChat.Document.InvokeScript("MsgPrn",
                            new object[] {
                                "msgnotice",
                                e.From,
                                e.Message
                            }
                        );
                    }
                }
            };
            #endregion

            #region CHANNEL/SERVER

            this.Irc.OnConnect += (o, e) =>
            {
                this.Irc.JoinChannel(Properties.Settings.Default.IRCChannel);
                lock (webwLock)
                {
                    this.WBChat.Document.InvokeScript("MsgPrn",
                        new object[] {
                            "msgnotice",
                            Properties.Settings.Default.IRCServer,
                            Properties.Settings.Default.IRCChannel
                        }
                    );
                }
                this.FBChatConnect.Text = Properties.Resources.txtIRCDisConnectButton;
                this.isIrcJoin = true;
            };
            this.Irc.OnExceptionThrown += (o, e) =>
            {
                if ((e.Exception == null) || (string.IsNullOrWhiteSpace(e.Exception.Message)))
                {
                    return;
                }
                lock (webwLock)
                {
                    this.WBChat.Document.InvokeScript("MsgPrn",
                        new object[] {
                            "msgnotice",
                            _sysNoticeTag,
                            ((string.IsNullOrWhiteSpace(e.SocketError)) ? "" : "[" + e.SocketError + "]" +
                            ((e.Count > 0) ? "/" + e.Count.ToString() + " " : "") + e.Exception.Message)
                        }
                    );
                }
                if (e.Fatal)
                {
                    this.isIrcJoin = false;
                    this.FBChatConnectSetDisconnected();
                }
            };

            #endregion

            #endregion
        }
    }
}


text:
<?php

namespace Mpwarfw\Component\Request;

class Request
{

    private $get;
    private $post;
    private $cookie;
    private $session;
    public $server;
    private $params;

    public function __construct($get, $post, $cookie, $session, $server)
    {
        $this->get = $get;
        $this->post = $post;
        $this->cookie = $cookie;
        $this->session = $session;
        $this->server = $server;
    }

    public static function create()
    {
        session_start();
        return new self($_GET,$_POST,$_COOKIE,$_SESSION, $_SERVER);
    }

    public function setParams($params)
    {
        $this->params = $params;
    }

    public function getPath()
    {
        $url_segments = explode("/", parse_url($this->server['PATH_INFO'],PHP_URL_PATH));

        if(count($url_segments) > 0){
            return $url_segments[ 1 ];
        }
        return 'index';
    }

    public function getParams()
    {
        $url_segments = explode("/", parse_url($this->server['PATH_INFO'],PHP_URL_PATH));

        $params = [];
        if(count($url_segments) > 2){
            for ($param_index = 2; $param_index < count($url_segments); $param_index++){
                $params[] = $url_segments[ $param_index ];
            }
        }
        return $params;
    }
}


text:
package com.smartdevicelink.test.proxy;

import com.smartdevicelink.proxy.RPCMessage;
import com.smartdevicelink.proxy.rpc.Alert;
import com.smartdevicelink.proxy.rpc.ChangeRegistration;
import com.smartdevicelink.proxy.rpc.Choice;
import com.smartdevicelink.proxy.rpc.DisplayCapabilities;
import com.smartdevicelink.proxy.rpc.GetDTCsResponse;
import com.smartdevicelink.proxy.rpc.Image;
import com.smartdevicelink.proxy.rpc.TTSChunk;
import com.smartdevicelink.proxy.rpc.enums.Language;
import com.smartdevicelink.proxy.rpc.enums.MediaClockFormat;
import com.smartdevicelink.test.TestValues;
import com.smartdevicelink.test.Validator;

import junit.framework.TestCase;

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

/**
 * Created by austinkirk on 6/8/17.
 */

public class RPCMessageTests extends TestCase {
    RPCMessage testMessage = new RPCMessage("TestFunction");

    private static final String TAG = "RPC Struct Tests";

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void testGeneralGettersAndSetters() {
        String testKey = TestValues.GENERAL_STRING;
        Integer testInt = TestValues.GENERAL_INT;

        testMessage.setParameters(testKey, testInt);
        assertEquals(TestValues.MATCH, testInt, testMessage.getParameters(testKey));

        testMessage.setParameters(testKey, null);
        assertNull(testMessage.getParameters(testKey));
    }

    public void testCommonObjectGetters() {
        String stringKey = "String";
        String testString = TestValues.GENERAL_STRING;
        testMessage.setParameters(stringKey, testString);

        assertEquals(TestValues.MATCH, testMessage.getString(stringKey), testString);

        String intKey = "Integer";
        Integer testInt = TestValues.GENERAL_INT;
        testMessage.setParameters(intKey, testInt);

        assertEquals(TestValues.MATCH, testMessage.getInteger(intKey), testInt);

        String doubleKey = "Double";
        Double testDouble = TestValues.GENERAL_DOUBLE;
        testMessage.setParameters(doubleKey, testDouble);

        assertEquals(TestValues.MATCH, testMessage.getDouble(doubleKey), testDouble);

        String booleanKey = "Boolean";
        Boolean testBoolean = TestValues.GENERAL_BOOLEAN;
        testMessage.setParameters(booleanKey, testBoolean);

        assertEquals(TestValues.MATCH, testMessage.getBoolean(booleanKey), testBoolean);

        String longKey = "Long";
        Long testLong = TestValues.GENERAL_LONG;
        testMessage.setParameters(longKey, testLong);

        assertEquals(TestValues.MATCH, testMessage.getLong(longKey), testLong);

        testMessage.setParameters(longKey, testInt);

        assertEquals(TestValues.MATCH, testMessage.getLong(longKey), new Long(testInt.longValue()));

        testMessage.setParameters(longKey, testDouble);
        assertNull(testMessage.getLong(longKey));
    }

    public void testGetObject() {
        String keyIsEmpty = "EMPTY";
        assertNull(testMessage.getObject(Integer.class, keyIsEmpty));

        String keyLanguage = ChangeRegistration.KEY_LANGUAGE;
        Language language = TestValues.GENERAL_LANGUAGE;
        testMessage.setParameters(keyLanguage, language);
        assertEquals(TestValues.MATCH, language, testMessage.getObject(Language.class, keyLanguage));

        String languageString = language.toString();
        testMessage.setParameters(keyLanguage, languageString);
        assertEquals(TestValues.MATCH, language, testMessage.getObject(Language.class, keyLanguage));

        String keyImage = Choice.KEY_IMAGE;
        Image testImage = TestValues.GENERAL_IMAGE;
        testMessage.setParameters(keyImage, testImage.getStore());
        assertTrue(Validator.validateImage(testImage, (Image) testMessage.getObject(Image.class, keyImage)));

        String keyDTCs = GetDTCsResponse.KEY_DTC;
        List<String> testDTCs = TestValues.GENERAL_STRING_LIST;
        testMessage.setParameters(keyDTCs, testDTCs);
        assertEquals(TestValues.MATCH, testDTCs, testMessage.getObject(String.class, keyDTCs));

        String keyTTSchunks = Alert.KEY_TTS_CHUNKS;
        List<TTSChunk> testTTSchunks = TestValues.GENERAL_TTSCHUNK_LIST;
        testMessage.setParameters(keyTTSchunks, testTTSchunks);
        assertEquals(TestValues.MATCH, testTTSchunks, testMessage.getObject(TTSChunk.class, keyTTSchunks));

        List<Hashtable<String, Object>> testListTTSchunks = new ArrayList<>();
        for (TTSChunk ttsChunk : testTTSchunks) {
            testListTTSchunks.add(ttsChunk.getStore());
        }
        testMessage.setParameters(keyTTSchunks, testListTTSchunks);
        List<TTSChunk> underTest = (List<TTSChunk>) testMessage.getObject(TTSChunk.class, keyTTSchunks);
        assertTrue(Validator.validateTtsChunks(testTTSchunks, underTest));

        String keyMediaClockFormats = DisplayCapabilities.KEY_MEDIA_CLOCK_FORMATS;
        List<MediaClockFormat> testMediaClockFormats = TestValues.GENERAL_MEDIACLOCKFORMAT_LIST;
        testMessage.setParameters(keyMediaClockFormats, testMediaClockFormats);
        assertEquals(TestValues.MATCH, testMediaClockFormats, testMessage.getObject(MediaClockFormat.class, keyMediaClockFormats));

        List<String> testListMediaClockFormats = new ArrayList<>();
        for (MediaClockFormat mcFormat : testMediaClockFormats) {
            testListMediaClockFormats.add(mcFormat.toString());
        }
        testMessage.setParameters(keyMediaClockFormats, testListMediaClockFormats);
        assertEquals(TestValues.MATCH, testMediaClockFormats, testMessage.getObject(MediaClockFormat.class, keyMediaClockFormats));

        assertNull(testMessage.getObject(Image.class, keyLanguage)); // Test incorrect class
    }
}


text:
"""Output and/or upload a TestRun or MfgEvent proto for mfg-inspector.com.
"""

import json
import logging
import threading
import time
import zlib

import httplib2
import oauth2client.client

from openhtf.output import callbacks
from openhtf.output.proto import test_runs_converter

from openhtf.output.proto import guzzle_pb2

class UploadFailedError(Exception):
  """Raised when an upload to mfg-inspector fails."""

class InvalidTestRunError(Exception):
  """Raised if test run is invalid."""

def _send_mfg_inspector_request(envelope_data, credentials, destination_url):
  """Send upload http request.  Intended to be run in retry loop."""
  logging.info('Uploading result...')
  http = httplib2.Http()

  if credentials.access_token_expired:
    credentials.refresh(http)
  credentials.authorize(http)

  resp, content = http.request(destination_url, 'POST', envelope_data)

  try:
    result = json.loads(content)
  except Exception:
    logging.debug('Upload failed with response %s: %s', resp, content)
    raise UploadFailedError(resp, content)

  if resp.status != 200:
    logging.debug('Upload failed: %s', result)
    raise UploadFailedError(result['error'], result)

  return result

def send_mfg_inspector_data(inspector_proto, credentials, destination_url):
  """Upload MfgEvent to steam_engine."""
  envelope = guzzle_pb2.TestRunEnvelope()
  envelope.payload = zlib.compress(inspector_proto.SerializeToString())
  envelope.payload_type = guzzle_pb2.COMPRESSED_MFG_EVENT
  envelope_data = envelope.SerializeToString()

  for _ in xrange(5):
    try:
      result = _send_mfg_inspector_request(
          envelope_data, credentials, destination_url)
      return result
    except UploadFailedError:
      time.sleep(1)

  logging.critical(
      'Could not upload to mfg-inspector after 5 attempts. Giving up.')

  return {}

class _MemStorage(oauth2client.client.Storage):
  # pylint: disable=invalid-name
  """Helper Storage class that keeps credentials in memory."""

  def __init__(self):
    self._lock = threading.Lock()
    self._credentials = None

  def acquire_lock(self):
    self._lock.acquire(True)

  def release_lock(self):
    self._lock.release()

  def locked_get(self):
    return self._credentials

  def locked_put(self, credentials):
    self._credentials = credentials

class MfgInspector(object):
  """Interface to convert a TestRun to a mfg-inspector compatible proto.

  Instances of this class are typically used to create callbacks that are
  compatible with the OpenHTF output callbacks.

  Typical usage:
  interface = mfg_inspector.MfgInspector.from_json().set_converter(
    my_custom_converter)
  my_tester.add_output_callbacks(interface.save_to_disk(), interface.upload())

  **Important** the conversion of the TestRecord to protofbuf as specified in
  the _converter callable attribute only occurs once and the resulting protobuf
  is cached in memory on the instance.

  The upload callback will upload to mfg-inspector.com using the given
  username and authentication key (which should be the key data itself, not a
  filename or file).

  In typical productin setups, we *first* save the protobuf to disk then attempt
  to upload the protobuf to mfg-inspector.  In the event of a network outage,
  the result of the test run is available on disk and a separate process can
  retry the upload when network is available.
  """

  TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
  SCOPE_CODE_URI = 'https://www.googleapis.com/auth/glass.infra.quantum_upload'
  DESTINATION_URL = ('https://clients2.google.com/factoryfactory/'
                     'uploads/quantum_upload/?json')

  # These attributes control format of callback and what actions are undertaken
  # when called.  These should either be set by a subclass or via configure.

  # _converter is a callable that can be set either via set_converter method
  # or by defining a _converter @staticmethod on subclasses.
  _converter = None

  # A default filename pattern can be specified on subclasses for use when
  # saving to disk via save_to_disk.
  _default_filename_pattern = None

  def __init__(self, user=None, keydata=None,
               token_uri=TOKEN_URI, destination_url=DESTINATION_URL):
    self.user = user
    self.keydata = keydata
    self.token_uri = token_uri
    self.destination_url = destination_url

    if user and keydata:
      self.credentials = oauth2client.client.SignedJwtAssertionCredentials(
          service_account_name=self.user,
          private_key=self.keydata,
          scope=self.SCOPE_CODE_URI,
          user_agent='OpenHTF Guzzle Upload Client',
          token_uri=self.token_uri)
      self.credentials.set_store(_MemStorage())
    else:
      self.credentials = None

    self.upload_result = None

    self._cached_proto = None

  @classmethod
  def from_json(cls, json_data):
    """Create an uploader given (parsed) JSON data.

    Note that this is a JSON-formatted key file downloaded from Google when
    the service account key is created, *NOT* a json-encoded
    oauth2client.client.SignedJwtAssertionCredentials object.

    Args:
      json_data: Dict containing the loaded JSON key data.

    Returns:
      a MfgInspectorCallback with credentials.
    """
    return cls(user=json_data['client_email'],
               keydata=json_data['private_key'],
               token_uri=json_data['token_uri'])

  def _convert(self, test_record_obj):
    """Convert and cache a test record to a mfg-inspector proto."""

    if self._cached_proto is None:
      self._cached_proto = self._converter(test_record_obj)

    return self._cached_proto

  def save_to_disk(self, filename_pattern=None):
    """Returns a callback to convert test record to proto and save to disk."""
    if not self._converter:
      raise RuntimeError(
          'Must set _converter on subclass or via set_converter before calling '
          'save_to_disk.')

    pattern = filename_pattern or self._default_filename_pattern
    if not pattern:
      raise RuntimeError(
          'Must specify provide a filename_pattern or set a '
          '_default_filename_pattern on subclass.')

    def save_to_disk_callback(test_record_obj):
      proto = self._convert(test_record_obj)
      output_to_file = callbacks.OutputToFile(pattern)

      with output_to_file.open_output_file(test_record_obj) as outfile:
        outfile.write(proto.SerializeToString())

    return save_to_disk_callback

  def upload(self):
    """Returns a callback to convert a test record to a proto and upload."""
    if not self._converter:
      raise RuntimeError(
          'Must set _converter on subclass or via set_converter before calling '
          'upload.')

    if not self.credentials:
      raise RuntimeError('Must provide credentials to use upload callback.')

    def upload_callback(test_record_obj):
      proto = self._convert(test_record_obj)
      self.upload_result = send_mfg_inspector_data(
          proto, self.credentials, self.destination_url)

    return upload_callback

  def set_converter(self, converter):
    """Set converter callable to convert a OpenHTF tester_record to a proto.

    Args:
      converter: a callable that accepts an OpenHTF TestRecord and returns a
        manufacturing-inspector compatible protobuf.

    Returns:
      self to make this call chainable.
    """
    assert callable(converter), 'Converter must be callable.'

    self._converter = converter

    return self

# LEGACY / DEPRECATED
class UploadToMfgInspector(MfgInspector):
  """Generate a mfg-inspector TestRun proto and upload it.

  LEGACY / DEPRECATED
  This class is provided only for legacy reasons and may be deleted in future.
  Please replace usage by configuring a MfgInspectorCallback directly. For
  example:
  test.add_output_callbacks(
    mfg_inspector.MfgInspectorCallback.from_json(**json_data).set_converter(
      test_runs_converter.test_run_from_test_record).upload()
  )
  """

  @staticmethod
  def _converter(test_record_obj):
    return test_runs_converter.test_run_from_test_record(test_record_obj)

  def __call__(self, test_record_obj):  # pylint: disable=invalid-name
    upload_callback = self.upload()
    upload_callback(test_record_obj)


text:
/**
 * Created by asimz on 12/06/2016.
 */
/* eslint-disable no-var*/
/* eslint-disable-line no-undef*/

// Sets Node environment variable to test
process.env.NODE_ENV = 'test';

// Register babel so that it will transpile code from ES6 to ES5
require('babel-register')();

// Disables Webpack-specific features that Mocha doesn't understand.
require.extensions['.css'] = function () {return null;};
require.extensions['.png'] = function () {return null;};
require.extensions['.jpg'] = function () {return null;};

//Requires jsdom so we can test via an in-memory DOM in Node
var jsdom = require('jsdom').jsdom;

//Sets up global vars that mimic a browser.
var exposedProperties = ['window', 'navigator', 'document'];

global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
    if (typeof global[property] === 'undefined') {
        exposedProperties.push(property);
        global[property] = document.defaultView[property];
    }
});

global.navigator = {
    userAgent: 'node.js'
};

documentRef = document;


text:
namespace JavaEEMVCGenerator
{
    partial class Form2
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.textBoxOutputDir = new System.Windows.Forms.TextBox();
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.buttonBrowse = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.textBoxPackage = new System.Windows.Forms.TextBox();
            this.buttonGenerate = new System.Windows.Forms.Button();
            this.buttonClose = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // richTextBox1
            //
            this.richTextBox1.Location = new System.Drawing.Point(-3, 145);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(467, 115);
            this.richTextBox1.TabIndex = 0;
            this.richTextBox1.Text = "";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(8, 21);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(55, 13);
            this.label1.TabIndex = 2;
            this.label1.Text = "Output Dir";
            //
            // textBoxOutputDir
            //
            this.textBoxOutputDir.Location = new System.Drawing.Point(108, 18);
            this.textBoxOutputDir.Name = "textBoxOutputDir";
            this.textBoxOutputDir.Size = new System.Drawing.Size(140, 20);
            this.textBoxOutputDir.TabIndex = 3;
            this.textBoxOutputDir.Text = "c:\\";
            //
            // buttonBrowse
            //
            this.buttonBrowse.Location = new System.Drawing.Point(254, 16);
            this.buttonBrowse.Name = "buttonBrowse";
            this.buttonBrowse.Size = new System.Drawing.Size(59, 22);
            this.buttonBrowse.TabIndex = 4;
            this.buttonBrowse.Text = "Browse";
            this.buttonBrowse.UseVisualStyleBackColor = true;
            this.buttonBrowse.Click += new System.EventHandler(this.buttonBrowse_Click);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(8, 59);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(84, 13);
            this.label2.TabIndex = 5;
            this.label2.Text = "Package Name:";
            //
            // textBoxPackage
            //
            this.textBoxPackage.Location = new System.Drawing.Point(108, 56);
            this.textBoxPackage.Name = "textBoxPackage";
            this.textBoxPackage.Size = new System.Drawing.Size(140, 20);
            this.textBoxPackage.TabIndex = 6;
            this.textBoxPackage.Text = "myproject";
            //
            // buttonGenerate
            //
            this.buttonGenerate.Location = new System.Drawing.Point(17, 95);
            this.buttonGenerate.Name = "buttonGenerate";
            this.buttonGenerate.Size = new System.Drawing.Size(124, 35);
            this.buttonGenerate.TabIndex = 7;
            this.buttonGenerate.Text = "Generate Code Files";
            this.buttonGenerate.UseVisualStyleBackColor = true;
            this.buttonGenerate.Click += new System.EventHandler(this.buttonGenerate_Click);
            //
            // buttonClose
            //
            this.buttonClose.Location = new System.Drawing.Point(373, 107);
            this.buttonClose.Name = "buttonClose";
            this.buttonClose.Size = new System.Drawing.Size(75, 23);
            this.buttonClose.TabIndex = 8;
            this.buttonClose.Text = "Close";
            this.buttonClose.UseVisualStyleBackColor = true;
            this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
            //
            // Form2
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(460, 263);
            this.Controls.Add(this.buttonClose);
            this.Controls.Add(this.buttonGenerate);
            this.Controls.Add(this.textBoxPackage);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.buttonBrowse);
            this.Controls.Add(this.textBoxOutputDir);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.richTextBox1);
            this.Name = "Form2";
            this.Text = "Generate Code";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBoxOutputDir;
        private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
        private System.Windows.Forms.Button buttonBrowse;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox textBoxPackage;
        private System.Windows.Forms.Button buttonGenerate;
        private System.Windows.Forms.Button buttonClose;
    }
}


text:
First, what are constant pairs?  The term "constant pair" refers
to a capability of zprint where, when formatting a list, it will
search backwards from end end of a list, looking at every second element
from the last (i.e., second from last, fourth from last, etc.) to see
if it is a "constant".  If it is, then all of the contiguous elements
that have constants in those positions are formatted as "pairs".

Some examples would be helpful.

First an example from code using Seesaw, a Clojure library for building
user interfaces using Java Swing:

```clojure
(zprint dialogf {:parse-string? true :list {:constant-pair? false}})

; This is what you get with normal formatting, without constant pairs

(dialog
  :parent
  top-frame
  :title
  "Loading and Saving Data"
  :content
  (mig-panel
    :items
    [["To load data from a file, press:"]
     [(action :name
              "Load"
              :handler
              (fn [x]
                (choose-file :type
                             :open
                             :success-fn
                             load-from-file
                             :dir
                             (clojure.java.io/file cwd)))) "wrap"]
     [same-box "wrap"]
     [(label :text
             "To save data as it is entered, press:"
             :id
             :save-label
             :class
             :save)]
     [(button :class
              :save
              :id
              :save-button
              :action
              (action :name
                      "Save"
                      :handler
                      (fn [x]
                        (choose-file :type
                                     :save
                                     :success-fn
                                     save-to-file
                                     :dir
                                     (clojure.java.io/file cwd))))) "wrap"]])
  :visible?
  false)

; This is what you get with the default zprint formatting, which recognizes
; constant pairs.  Quite a difference!

(zprint dialogf {:parse-string? true})

(dialog :parent top-frame
        :title "Loading and Saving Data"
        :content
          (mig-panel
            :items
            [["To load data from a file, press:"]
             [(action :name "Load"
                      :handler (fn [x]
                                 (choose-file :type :open
                                              :success-fn load-from-file
                                              :dir (clojure.java.io/file cwd))))
              "wrap"] [same-box "wrap"]
             [(label :text "To save data as it is entered, press:"
                     :id :save-label
                     :class :save)]
             [(button :class :save
                      :id :save-button
                      :action (action :name "Save"
                                      :handler (fn [x]
                                                 (choose-file
                                                   :type :save
                                                   :success-fn save-to-file
                                                   :dir (clojure.java.io/file
                                                          cwd))))) "wrap"]])
        :visible? false)
```
Constant pairing also makes Clojure specs much more legible:
```clojure
; First, without constant pairs, it looks like normal lisp formatting,
; which isn't great in this situation

(zprint spec {:parse-string? true :list {:constant-pair? false}})

(s/def ::line-seq
  (s/nilable (s/coll-of (s/or :number
                              number?
                              :range
                              (s/coll-of number? :kind sequential?))
                        :kind
                        sequential?)))

; Now, with constant pair recognition (the default),it looks much better:

(zprint spec {:parse-string? true})

(s/def ::line-seq
  (s/nilable (s/coll-of (s/or :number number?
                              :range (s/coll-of number? :kind sequential?))
                        :kind sequential?)))
```
Constant pairs are only recognized in lists.  There are two basic controls
for constant pairs:

  * `{:list {:constant-pair? true}}` will enable (or disable them) altogether.

  * `{:list {:constant-pair-min 4}}` is the minimum number of non-whitespace
elements required to exist before constant-pairs at the end of a list
are rendered differently.

You can also control what is considered a "constant" for constant pairing.

By default, a "constant" is keyword, string, number, or true or false.
You can define a `:constant-pair-fn` which, when given an element, will return
non-nil or nil to control whether or not that element is considered a
"constant".

Solely for the purposes of illustration (i.e., this is not how the
default form of constant pairing is implemented), here is a `:constant-pair-fn`
which mimics the default behavior:

```clojure
{:list {:constant-pair-fn
          #(or (keyword %) (string %) (number? %) (= true %) (= false %))}}
```
You can define such a function yourself, in order to allow additional items to
be treated as pairs and be controlled by the constant pairing options in
`:list`.

The function takes one argument:

`{:list {:constant-pair-fn (fn [element] ...)}}`

See [this discussion](./optionfns.md) for more information
on user-defined functions and using `sci`.

Here is an example of where this might be useful, also note the use of
`:next-inner` to restrict the use of `:constant-pair-fn` to just the
top level of `m/app`:

```clojure

(def mapp6
"(m/app :get  (m/app middle1 middle2 middle3\n                    [route] handler\n\t\t    ; How do comments work?\n                    [route] \n        (handler this is \"a\" test \"this\" is \"only a\" test) \n\t\t    )\n       ; How do comments work here?\n       :post (m/app \n                    [route] handler\n                    [route] ; What about comments here?\n\t\t    handler))")

; Let's  see what happens if we just use the default configuration.
; The narrow width is to force constant pairing on the second handler
; of the :get

(czprint mapp6 {:parse-string? true :width 55})

(m/app :get (m/app middle1
                   middle2
                   middle3
                   [route]
                   handler
                   ; How do comments work?
                   [route]
                   (handler this
                            is
                            "a" test
                            "this" is
                            "only a" test))
       ; How do comments work here?
       :post (m/app [route]
                    handler
                    [route] ; What about comments here?
                    handler))

; This is ok, but it would be nice to pair the handlers up with the routes
; Since they fall at the end of the expressions, sounds like we could use
; constant-pairing to force the pair behavior.

; Let's see what we can do if we define our own function to determine
; what constant-pairing will consdier a "constant"

(zprint
  mapp6
  {:parse-string? true,
   :fn-map {"app" [:none
                   {:list {:constant-pair-min 1,
                           :constant-pair-fn #(or (vector? %) (keyword? %))},
                    :next-inner {:list {:constant-pair-fn nil,
                                        :constant-pair-min 4}}}]},
   :width 55})

(m/app :get (m/app middle1
                   middle2
                   middle3
                   [route] handler
                   ; How do comments work?
                   [route] (handler this
                                    is
                                    "a" test
                                    "this" is
                                    "only a" test))
       ; How do comments work here?
       :post (m/app [route] handler
                    [route] ; What about comments here?
                      handler))

; Much nicer.  Note that we had to define both keywords and vectors as
; "constants", to preserve the keyword constant-pairing.
; Note also the use of :next-inner to restore constant-pairing to its
; default behavior down inside of expressions contained in `m/app`.
```
There is another (and better) approach to restoring the constant pairing
configuation inside of the expressions contained in `m/app` - use
`:next-inner-restore`.  This integrates
better with any existing configuration for constant pairing in that it
doesn't reset it to a specific value for the contained expressions. Instead
it restores the previous values, whatever they were.

To illustrate this, let's see what happens if we don't restore the constant
pairing configuration:

```
(zprint
  mapp6
  {:parse-string? true,
   :fn-map {"app" [:none
                   {:list {:constant-pair-min 1,
                           :constant-pair-fn #(or (vector? %) (keyword? %))}}]}
   :width 55})
(m/app :get (m/app middle1
                   middle2
                   middle3
                   [route] handler
                   ; How do comments work?
                   [route] (handler this
                                    is
                                    "a"
                                    test
                                    "this"
                                    is
                                    "only a"
                                    test))
       ; How do comments work here?
       :post (m/app [route] handler
                    [route] ; What about comments here?
                      handler))
```

Note how the `(handler this is "a" test "this" is "only a" test)` doesn't
pair up the constants with the things following them.

Now, when we restore the constant pairing configuration, we see that
constant pairing works as usual in the expressions contained in `m/app`:

```
(zprint
  mapp6
  {:parse-string? true,
   :fn-map {"app" [:none
                   {:list {:constant-pair-min 1,
                           :constant-pair-fn #(or (vector? %) (keyword? %))},
                    :next-inner-restore [[:list :constant-pair-min]
                                         [:list :constant-pair-fn]]}]},
   :width 55})
(m/app :get (m/app middle1
                   middle2
                   middle3
                   [route] handler
                   ; How do comments work?
                   [route] (handler this
                                    is
                                    "a" test
                                    "this" is
                                    "only a" test))
       ; How do comments work here?
       :post (m/app [route] handler
                    [route] ; What about comments here?
                      handler))
```
Using `:next-inner-restore` allows any existing
constant pairing configuration to return for the inner expressions of
`m/app`.

## Specifying Functions in Option Maps

Typically, the user-defined function are specified in an options
map (often defining a new `:style`) which appears in a `.zprintrc`
file.  When `.zprintrc` files are read-in, they are read using
`sci`, the small Clojure interpreter.  Thus, any user-defined
functions are defined using a large subset of the available Clojure
function, specifically excepting any functions that can be used to
operate outside of the sandbox provided by the `sci` interpreter.

See [this discussion](./optionfns.md) for more information
on user-defined functions and using `sci`.


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- Include ToolBar here -->
    <include layout="@layout/toolbar" />

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


text:
from argparse import ArgumentParser

# Dealing with relative import
if __name__ == "__main__" and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
    from infrastructure import Infrastructure
else:
    from ..infrastructure import Infrastructure

class Iampolicies(Infrastructure):
	def __init__(self):
		super(Iampolicies, self).__init__(environment='', deployment='', region='us-east-1', zone='')
		self.create_security_groups()
		self.stack_name = "iam-policies"

parser = ArgumentParser(description='Deploy iam policies to an AWS CloudFormation environment.')

def main(parser):
	args, unknown = parser.parse_known_args()
	infrastructure = Iampolicies()
	infrastructure.deploy()

if __name__ == '__main__':
	main(parser)


text:
SIFloatingCollection is a component that provides logic similar to Apple Music genres selection.

SIFloatingCollection component uses SpriteKit for simulate physics similar to Apple Music genres selection. It's customizable, so you can create any floating shapes contained any other SKNode instances.

![Preview](http://media.giphy.com/media/3oEdv8UHKz9l788J4Q/giphy.gif)

## Installation for Swift 1.x

####[CocoaPods](http://cocoapods.org)
```ruby
pod 'SIFloatingCollectionSwift'
```

## Installation for Swift 2 (Xcode 7 beta X) users

Download sources manually from swift_2 branch


text:
<?php
/**
 * Created by PhpStorm.
 * User: yosefderay
 * Date: 5/10/14
 * Time: 11:46 PM
 */

namespace Yjv\ReportRendering\Tests\Event;

use Yjv\ReportRendering\Event\ReportEvent;

class ReportEventTest extends \PHPUnit_Framework_TestCase
{
    protected $report;
    protected $event;

    public function setUp()
    {
        $this->report = \Mockery::mock('Yjv\ReportRendering\Report\ReportInterface');
        $this->event = new ReportEvent($this->report);
    }

    public function testGettersSetters()
    {
        $this->assertSame($this->report, $this->event->getReport());
    }

}


text:
package play.learn.java.design.extension_object;

public interface SoldierExtension extends UnitExtension {

	void soldierReady();

}


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <!--
    <parameters>
        <parameter key="dnsee_tutorial.example.class">Dnsee\TutorialBundle\Example</parameter>
    </parameters>

    <services>
        <service id="dnsee_tutorial.example" class="%dnsee_tutorial.example.class%">
            <argument type="service" id="service_id" />
            <argument>plain_value</argument>
            <argument>%parameter_name%</argument>
        </service>
    </services>
    -->
</container>


text:
describe('Camera', function () {
	it('should create a new Camera', function () {
		var camera = new Camera;

		expect(camera);
	})

	it('should have a Vector3d as a position', function () {
		var camera = new Camera;

		expect(camera.position()).toEqual(new Vector3d);
	})

	it('should have a Vector2d as viewport', function () {
		var camera = new Camera(new Vector3d, new Vector2d(640, 480))

		expect(camera.viewport).toEqual([640, 480]);

		var camera = new Camera(new Vector3d, 640);
		expect(camera.viewport).toBeUndefined();
	})

	it('should have a FOV', function () {
		var camera = new Camera(new Vector3d, new Vector2d(640, 480), [45, 45]);

		expect(camera.fov).toEqual([45, 45]);
	})

	it('should convert Vector3d to Vector2d', function () {
		var camera = new Camera(new Vector3d, new Vector2d(640, 480), [45, 45]),
				vector2d = new Vector2d();

		expect(camera.project(new Vector3d(30, 34, 12))).toEqual(vector2d);
	})

})


text:
namespace Abp.MultiTenancy
{
    public interface ITenantResolveContributor
    {
        int? ResolveTenantId();
    }
}