text:
import { t } from '@superset-ui/core';

import {
  FETCH_ALL_SLICES_FAILED,
  FETCH_ALL_SLICES_STARTED,
  SET_ALL_SLICES,
} from '../actions/sliceEntities';

export const initSliceEntities = {
  slices: {},
  isLoading: true,
  errorMessage: null,
  lastUpdated: 0,
};

export default function sliceEntitiesReducer(
  state = initSliceEntities,
  action,
) {
  const actionHandlers = {
    [FETCH_ALL_SLICES_STARTED]() {
      return {
        ...state,
        isLoading: true,
      };
    },
    [SET_ALL_SLICES]() {
      return {
        ...state,
        isLoading: false,
        slices: { ...state.slices, ...action.payload.slices },
        lastUpdated: new Date().getTime(),
      };
    },
    [FETCH_ALL_SLICES_FAILED]() {
      return {
        ...state,
        isLoading: false,
        lastUpdated: new Date().getTime(),
        errorMessage:
          action.payload.error || t('Could not fetch all saved charts'),
      };
    },
  };

  if (action.type in actionHandlers) {
    return actionHandlers[action.type]();
  }
  return state;
}


text:
package com.foxykeep.datadroid.workers;

import java.util.HashMap;

import ru.igarin.base.provider.PoCHelper;
import ru.igarin.base.service.IServiceWorker;
import ru.igarin.base.service.exception.ConnectionException;
import ru.igarin.base.service.exception.CustomRequestException;
import ru.igarin.base.service.exception.DataException;
import ru.igarin.base.service.network.NetworkConnection;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;

import com.foxykeep.datadroid.config.RestConst;
import com.foxykeep.datadroid.config.ThisProvider;
import com.foxykeep.datadroid.data.Phone;
import com.foxykeep.datadroid.data.PhoneRequestParams;
import com.foxykeep.datadroid.dto.PhoneFromServer;
import com.google.gson.Gson;

/**
 * Created by igarin on 8/19/13.
 */
public class WorkerAddPhoneList implements IServiceWorker {
	@Override
	public Bundle doWork(Context context, Parcelable intentData)
			throws ConnectionException, DataException, CustomRequestException {

		PhoneRequestParams param = (PhoneRequestParams) intentData;
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(RestConst.URL_PROPERTY_USER_UDID, param.userId);

		Cursor c = PoCHelper.init(ThisProvider.class).setContext(context)
				.setClass(Phone.class).setWhere("id = " + param.phoneId)
				.executeQuery();
		c.moveToFirst();
		Phone phone = (Phone) PoCHelper.getFromCursor(Phone.class, c);

		params.put(RestConst.URL_PROPERTY_NAME, phone.name);
		params.put(RestConst.URL_PROPERTY_MANUFACTURER, phone.manufacturer);
		params.put(RestConst.URL_PROPERTY_ANDROID_VERSION, phone.androidVersion);
		params.put(RestConst.URL_PROPERTY_SCREEN_SIZE,
				String.valueOf(phone.screenSize));
		params.put(RestConst.URL_PROPERTY_PRICE, String.valueOf(phone.price));

		NetworkConnection networkConnection = new NetworkConnection(context,
				RestConst.ROOT_URL_ADD_EDIT);
		networkConnection.setParameters(params);

		NetworkConnection.ConnectionResult result = networkConnection.execute();

		PhoneFromServer serverResponse = new Gson().fromJson(result.body,
				PhoneFromServer.class);
		ContentValues values = PoCHelper
				.getContentValuesImpl(serverResponse.phone);

		PoCHelper.init(ThisProvider.class).setContext(context)
				.setClass(Phone.class).setValues(values)
				.setWhere("id" + " = " + serverResponse.phone.id)
				.executeUpdate();

		return null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include "../../include/fxedit/fxet_stub.h"
#include "../../include/fxedit/fx_edit.h"
#include "../../include/fxedit/fxet_edit.h"

CFX_ByteString GetPDFWordString(IFX_Edit_FontMap * pFontMap, FX_INT32 nFontIndex, FX_WORD Word, FX_WORD SubWord)
{
	ASSERT (pFontMap != NULL);

	CFX_ByteString sWord;

	if (CPDF_Font * pPDFFont = pFontMap->GetPDFFont(nFontIndex))
	{
		if (SubWord > 0)
		{
			Word = SubWord;
		}
		else
		{
			FX_DWORD dwCharCode = -1;

			if (pPDFFont->IsUnicodeCompatible())
				dwCharCode = pPDFFont->CharCodeFromUnicode(Word);
			else
				dwCharCode = pFontMap->CharCodeFromUnicode(nFontIndex, Word);

			if (dwCharCode > 0 )
			{
				pPDFFont->AppendChar(sWord, dwCharCode);
				return sWord;
			}
		}

		pPDFFont->AppendChar(sWord, Word);
	}

	return sWord;
}

static CFX_ByteString GetWordRenderString(const CFX_ByteString & strWords)
{
	if (strWords.GetLength() > 0)
		return PDF_EncodeString(strWords) + " Tj\n";

	return "";
}

static CFX_ByteString GetFontSetString(IFX_Edit_FontMap * pFontMap, FX_INT32 nFontIndex, FX_FLOAT fFontSize)
{
	CFX_ByteTextBuf sRet;

	if (pFontMap)
	{
		CFX_ByteString sFontAlias = pFontMap->GetPDFFontAlias(nFontIndex);

		if (sFontAlias.GetLength() > 0 && fFontSize > 0 )
			sRet << "/" << sFontAlias << " " << fFontSize << " Tf\n";
	}

	return sRet.GetByteString();
}

CFX_ByteString IFX_Edit::GetEditAppearanceStream(IFX_Edit* pEdit, const CPDF_Point & ptOffset,
												 const CPVT_WordRange * pRange /* = NULL*/, FX_BOOL bContinuous/* = TRUE*/, FX_WORD SubWord/* = 0*/)
{
	CFX_ByteTextBuf sEditStream, sWords;

	CPDF_Point ptOld(0.0f,0.0f),ptNew(0.0f,0.0f);
	FX_INT32 nCurFontIndex = -1;

	if (IFX_Edit_Iterator* pIterator = pEdit->GetIterator())
	{
		if (pRange)
			pIterator->SetAt(pRange->BeginPos);
		else
			pIterator->SetAt(0);

		CPVT_WordPlace oldplace;

		while (pIterator->NextWord())
		{
			CPVT_WordPlace place = pIterator->GetAt();

			if (pRange && place.WordCmp(pRange->EndPos) > 0) break;

			if (bContinuous)
			{
				if (place.LineCmp(oldplace) != 0)
				{
					if (sWords.GetSize() > 0)
					{
						sEditStream << GetWordRenderString(sWords.GetByteString());
						sWords.Clear();
					}

					CPVT_Word word;
					if (pIterator->GetWord(word))
					{
						ptNew = CPDF_Point(word.ptWord.x + ptOffset.x, word.ptWord.y + ptOffset.y);
					}
					else
					{
						CPVT_Line line;
						pIterator->GetLine(line);
						ptNew = CPDF_Point(line.ptLine.x + ptOffset.x, line.ptLine.y + ptOffset.y);
					}

					if (ptNew.x != ptOld.x || ptNew.y != ptOld.y)
					{
						sEditStream << ptNew.x - ptOld.x << " " << ptNew.y - ptOld.y << " Td\n";

						ptOld = ptNew;
					}
				}

				CPVT_Word word;
				if (pIterator->GetWord(word))
				{
					if (word.nFontIndex != nCurFontIndex)
					{
						if (sWords.GetSize() > 0)
						{
							sEditStream << GetWordRenderString(sWords.GetByteString());
							sWords.Clear();
						}
						sEditStream << GetFontSetString(pEdit->GetFontMap(),word.nFontIndex,word.fFontSize);
						nCurFontIndex = word.nFontIndex;
					}

					sWords << GetPDFWordString(pEdit->GetFontMap(),nCurFontIndex,word.Word,SubWord);
				}

				oldplace = place;
			}
			else
			{
				CPVT_Word word;
				if (pIterator->GetWord(word))
				{
					ptNew = CPDF_Point(word.ptWord.x + ptOffset.x, word.ptWord.y + ptOffset.y);

					if (ptNew.x != ptOld.x || ptNew.y != ptOld.y)
					{
						sEditStream << ptNew.x - ptOld.x << " " << ptNew.y - ptOld.y << " Td\n";
						ptOld = ptNew;
					}

					if (word.nFontIndex != nCurFontIndex)
					{
						sEditStream << GetFontSetString(pEdit->GetFontMap(),word.nFontIndex,word.fFontSize);
						nCurFontIndex = word.nFontIndex;
					}

					sEditStream << GetWordRenderString(GetPDFWordString(pEdit->GetFontMap(),nCurFontIndex,word.Word,SubWord));
				}
			}
		}

		if (sWords.GetSize() > 0)
		{
			sEditStream << GetWordRenderString(sWords.GetByteString());
			sWords.Clear();
		}
	}

	CFX_ByteTextBuf sAppStream;
	if (sEditStream.GetSize() > 0)
	{
		FX_INT32 nHorzScale = pEdit->GetHorzScale();
		if (nHorzScale != 100)
		{
			sAppStream << nHorzScale << " Tz\n";
		}

		FX_FLOAT fCharSpace = pEdit->GetCharSpace();
		if (!FX_EDIT_IsFloatZero(fCharSpace))
		{
			sAppStream << fCharSpace << " Tc\n";
		}

		sAppStream << sEditStream;
	}

	return sAppStream.GetByteString();
}

CFX_ByteString IFX_Edit::GetSelectAppearanceStream(IFX_Edit* pEdit, const CPDF_Point & ptOffset,
							const CPVT_WordRange * pRange /*= NULL*/)
{
	CFX_ByteTextBuf sRet;

	if (pRange && pRange->IsExist())
	{
		if (IFX_Edit_Iterator* pIterator = pEdit->GetIterator())
		{
			pIterator->SetAt(pRange->BeginPos);

			while (pIterator->NextWord())
			{
				CPVT_WordPlace place = pIterator->GetAt();

				if (pRange && place.WordCmp(pRange->EndPos) > 0) break;

				CPVT_Word word;
				CPVT_Line line;
				if (pIterator->GetWord(word) && pIterator->GetLine(line))
				{
					//CPDF_Rect rcWordSel = CPDF_Rect(word.ptWord.x,line.ptLine.y + line.fLineDescent,
					//		word.ptWord.x+word.fWidth,line.ptLine.y + line.fLineAscent);

					sRet << word.ptWord.x + ptOffset.x << " " << line.ptLine.y + line.fLineDescent
						<< " " << word.fWidth << " " << line.fLineAscent - line.fLineDescent << " re\nf\n";
				}
			}
		}
	}

	return sRet.GetByteString();
}


text:
package org.zalando.logbook;

import javax.annotation.Nullable;
import java.util.function.Predicate;

public final class MockbookFactory implements LogbookFactory {

    @Override
    public Logbook create(
            @Nullable final Predicate<HttpRequest> condition,
            @Nullable final CorrelationId correlationId,
            @Nullable final QueryFilter queryFilter,
            @Nullable final PathFilter pathFilter,
            @Nullable final HeaderFilter headerFilter,
            @Nullable final BodyFilter bodyFilter,
            @Nullable final RequestFilter requestFilter,
            @Nullable final ResponseFilter responseFilter,
            @Nullable final Strategy strategy,
            @Nullable final Sink sink) {

        return new Mockbook(
                condition,
                correlationId,
                queryFilter,
                pathFilter,
                headerFilter,
                bodyFilter,
                requestFilter,
                responseFilter,
                strategy,
                sink);
    }

}


text:
var DefaultDMProvider = require("../../../../lib/provider/dm/default"),
    DM     = require("../../../../lib/dm"),
    Async  = require("../../../../lib/async"),
    Chance = require("chance"),
    chai   = require("chai"),
    sinon  = require("sinon"),
    RSVP   = require("rsvp"),
    chance;

expect = chai.expect;
chance = new Chance;

describe("DefaultDMProvider", function() {
    var provider, dm, async;

    beforeEach(function() {
        dm = Object.create(DM.prototype);

        async = Object.create(Async.prototype);
        sinon.stub(async, "resolve", function(obj) {
            return RSVP.Promise.resolve(obj);
        });

        provider = new DefaultDMProvider(dm, async);
    });

    describe("#get", function() {

        it("should return promise", function() {
            expect(provider.get()).to.be.instanceOf(RSVP.Promise);
        });

        it("should return reference to dm", function(done) {
            provider.get()
                .then(function(result) {
                    expect(result).equal(dm);
                })
                .then(done, done);
        });

    });

});


text:
'use strict';

describe('ProAct', function () {
  it ('exists in the global object', function () {
    expect(ProAct).not.toBe(undefined);
    expect(ProAct).not.toBe(null);
    expect(typeof(ProAct)).toBe('object');
  });

  describe('#prob', function () {
    it ('exists in the namespace', function () {
      expect(ProAct.prob).not.toBe(undefined);
      expect(ProAct.prob).not.toBe(null);
      expect(typeof(ProAct.prob)).toBe('function');
    });

    it ('turns normal js object into ProAct Object (object with properties)', function () {
      var obj = {
        a: [1, 2, 3],
        b: function () {
          return a.length;
        }
      };

      ProAct.prob(obj);
      expect(obj.__pro__).not.toBe(undefined);
      expect(obj.__pro__).not.toBe(null);
      expect(typeof(obj.__pro__)).toBe('object');
    });

    it ('creates fully reactive ProAct.Arrays from simple arrays', function () {
      var array = ProAct.prob([1, 2, 3, 4, 5]),
          joined = array.pjoin('-');

      expect(ProAct.ArrayUtils.isProArray(array)).toBe(true);
      expect(joined.v).toEqual('1-2-3-4-5');

      array[2] = 30;
      expect(joined.v).toEqual('1-2-30-4-5');
    });

    describe('meta & dsl', function () {
      it ('uses property metadata to configure its properties', function () {
        var stream = ProAct.stream(),
            proObj = ProAct.prob({
              counter: 0,
              renderCounter: function () {
                return 'Hey, we have ' + this.counter + ' counts';
              },
              counterPow: function () {
                return this.counter * this.counter;
              }
            },
            {
              counter: ['<<($1)', stream],
              renderCounter: ['map($1)', function (v) {
                return v.replace('-', '');
              }],
              counterPow: 'noprop'
            });

        stream.trigger(-1);
        expect(proObj.counter).toEqual(-1);
        expect(proObj.renderCounter).toEqual('Hey, we have ' + 1 + ' counts');

        expect(typeof(proObj.counterPow)).toEqual('function');
        expect(proObj.counterPow()).toEqual(1);
      });
    });
  });

});


text:
//
//  GTLMapsEngineRaster.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Google Maps Engine API (mapsengine/v1)
// Description:
//   The Google Maps Engine API allows developers to store and query geospatial
//   vector and raster data.
// Documentation:
//   https://developers.google.com/maps-engine/
// Classes:
//   GTLMapsEngineRaster (0 custom class methods, 16 custom properties)

#import "GTLMapsEngineRaster.h"

#import "GTLMapsEngineAcquisitionTime.h"
#import "GTLMapsEngineFile.h"

// ----------------------------------------------------------------------------
//
//   GTLMapsEngineRaster
//

@implementation GTLMapsEngineRaster
@dynamic acquisitionTime, attribution, bbox, creationTime, descriptionProperty,
         draftAccessList, ETag, files, identifier, lastModifiedTime, maskType,
         name, processingStatus, projectId, rasterType, tags;

+ (NSDictionary *)propertyToJSONKeyMap {
  NSDictionary *map =
    [NSDictionary dictionaryWithObjectsAndKeys:
      @"description", @"descriptionProperty",
      @"etag", @"ETag",
      @"id", @"identifier",
      nil];
  return map;
}

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map =
    [NSDictionary dictionaryWithObjectsAndKeys:
      [NSNumber class], @"bbox",
      [GTLMapsEngineFile class], @"files",
      [NSString class], @"tags",
      nil];
  return map;
}

@end


text:
package org.scijava.script;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.scijava.Context;
import org.scijava.ItemIO;
import org.scijava.ItemVisibility;
import org.scijava.MenuPath;
import org.scijava.Priority;
import org.scijava.log.LogService;
import org.scijava.module.ModuleItem;
import org.scijava.plugin.Plugin;
import org.scijava.test.TestUtils;
import org.scijava.util.DigestUtils;
import org.scijava.util.FileUtils;
import org.scijava.widget.WidgetStyle;

/**
 * Tests {@link ScriptInfo}.
 *
 * @author Curtis Rueden
 * @author Mark Hiner
 */
public class ScriptInfoTest {

	private Context context;
	private ScriptService scriptService;

	// -- Test setup --

	@Before
	public void setUp() {
		context = new Context();
		scriptService = context.service(ScriptService.class);
	}

	@After
	public void tearDown() {
		context.dispose();
	}

	// -- Tests --

	/** Tests script identifiers. */
	@Test
	public void testGetIdentifier() {
		final String name = "strategerize";

		final String namedPath = "victory.bsizes";
		final String named = "" + //
			"#@script(name = '" + name + "')\n" + //
			"zxywvutsrqponmlkjihgfdcba\n";

		final String unnamedPath = "alphabet.bsizes";
		final String unnamed = "" + //
			"ABCDEFGHIJKLMNOPQRSTUVWXYZ\n" + //
			"0123456789\n";

		// Test named, with explicit path.
		assertEquals("script:" + name, id(namedPath, named));

		// Test named, and no path given.
		assertEquals("script:" + name, id(null, named));

		// Test unnamed, with explicit path.
		assertEquals("script:" + unnamedPath, id(unnamedPath, unnamed));

		// Test unnamed, and no path given.
		final String hex = DigestUtils.bestHex(unnamed);
		assertEquals("script:<" + hex + ">", id(null, unnamed));
	}

	/** Tests whether new-style parameter syntax are parsed correctly. */
	@Test
	public void testNewStyle() throws Exception {
		final String script = "" + //
			"##########\n" + //
			"# Inputs #\n" + //
			"##########\n" + //
			"#@input int stuff\n" + //
			"#@input int things\n" + //
			"\n" + //
			"###########\n" + //
			"# Credits #\n" + //
			"###########\n" + //
			"Brought to you by:\n" + //
			"person@example.com\n" + //
			"\n" + //
			"###########\n" + //
			"# Outputs #\n" + //
			"###########\n" + //
			"#@output String blackHoles\n" +
			"#@output String revelations\n" +
			"\n" + //
			"THE END!\n";
		final ScriptModule scriptModule =
			scriptService.run("newStyle.bsizes", script, true).get();

		final String expectedProcessed = script.replaceAll("#@.*", "");
		final String actualProcessed = scriptModule.getInfo().getProcessedScript();
		assertEquals(expectedProcessed, actualProcessed);

		final Object output = scriptModule.getReturnValue();

		if (output == null) fail("null result");
		else if (!(output instanceof Integer)) {
			fail("result is a " + output.getClass().getName());
		}
		else assertEquals(4, ((Integer) output).intValue());
	}

	/**
	 * Tests that the return value is appended as an extra output when no
	 * explicit outputs were declared.
	 */
	@Test
	public void testReturnValueAppended() throws Exception {
		final String script = "" + //
			"% @LogService log\n" + //
			"% @int value\n";
		final ScriptModule scriptModule =
			scriptService.run("include-return-value.bsizes", script, true).get();

		final Map<String, Object> outputs = scriptModule.getOutputs();
		assertEquals(1, outputs.size());
		assertTrue(outputs.containsKey(ScriptModule.RETURN_VALUE));
	}

	/**
	 * Tests that the return value is not appended as an extra output
	 * when explicit outputs were declared.
	 */
	@Test
	public void testReturnValueExcluded() throws Exception {
		final String script = "" + //
			"% @LogService log\n" + //
			"% @OUTPUT int value\n";
		final ScriptModule scriptModule =
			scriptService.run("exclude-return-value.bsizes", script, true).get();

		final Map<String, Object> outputs = scriptModule.getOutputs();
		assertEquals(1, outputs.size());
		assertTrue(outputs.containsKey("value"));
		assertFalse(outputs.containsKey(ScriptModule.RETURN_VALUE));
	}

	/**
	 * Ensures parameters are parsed correctly from scripts, even in the presence
	 * of noise like e-mail addresses.
	 */
	@Test
	public void testNoisyParameters() throws Exception {
		final String script = "" + //
			"% @LogService log\n" + //
			"% @OUTPUT Integer output" + //
			"% kraken@blah.net\n";
		final ScriptModule scriptModule =
			scriptService.run("hello.bsizes", script, true).get();

		final Object output = scriptModule.getReturnValue();

		if (output == null) fail("null result");
		else if (!(output instanceof Integer)) {
			fail("result is a " + output.getClass().getName());
		}
		else assertEquals(3, ((Integer) output).intValue());
	}

	/** Tests {@link ScriptInfo#getVersion()}. */
	@Test
	public void testVersion() throws IOException {
		final String script = "" + //
			"% @LogService log\n" + //
			"% @OUTPUT int output";

		// write script to a temporary directory on disk
		final File tmpDir = TestUtils.createTemporaryDirectory("script-info-test-");
		final String path = "hello.bsizes";
		final File scriptFile = new File(tmpDir, path);
		FileUtils.writeFile(scriptFile, DigestUtils.bytes(script));

		// verify that the version is correct
		final ScriptInfo info = new ScriptInfo(context, scriptFile);
		final String version = info.getVersion();
		final String sha1 = "28f4a2880d604774ac5d604d35f431047a087c9e";
		assertTrue(version.matches("^" + sha1 + "$"));

		// clean up the temporary directory
		FileUtils.deleteRecursively(tmpDir);
	}

	/**
	 * Tests {@link ScriptInfo} parameter declarations, including
	 * {@link ScriptInfo#inputs()}, {@link ScriptInfo#outputs()},
	 * {@link ScriptInfo#getInput(String)} and
	 * {@link ScriptInfo#getOutput(String)}.
	 */
	@Test
	public void testParameters() {
		final String script = "" + //
			"#@ LogService (required = false) log\n" + //
			"#@ int (label=\"Slider Value\", softMin=5, softMax=15, " + //
			"stepSize=3, value=11, style=\" slidEr,\") sliderValue\n" + //
			"#@ String (persist = false, family='Carnivora', " + //
			"choices={'quick brown fox', 'lazy dog'}) animal\n" + //
			"#@ Double (autoFill = false) notAutoFilled\n" + //
			"#@ String (visibility=MESSAGE) msg\n" + //
			"#@BOTH java.lang.StringBuilder buffer";

		final ScriptInfo info =
			new ScriptInfo(context, "params.bsizes", new StringReader(script));

		final List<?> noChoices = Collections.emptyList();

		final ModuleItem<?> log = info.getInput("log");
		assertItem("log", LogService.class, null, ItemIO.INPUT, false, true, null,
			null, null, null, null, null, null, null, noChoices, log);

		final ModuleItem<?> sliderValue = info.getInput("sliderValue");
		assertItem("sliderValue", int.class, "Slider Value", ItemIO.INPUT, true,
			true, null, " slidEr,", 11, null, null, 5, 15, 3.0, noChoices, sliderValue);
		assertTrue("Case-insensitive trimmed style", WidgetStyle.isStyle(sliderValue, "slider"));

		final ModuleItem<?> animal = info.getInput("animal");
		final List<String> animalChoices = //
			Arrays.asList("quick brown fox", "lazy dog");
		assertItem("animal", String.class, null, ItemIO.INPUT, true, false,
			null, null, null, null, null, null, null, null, animalChoices, animal);
		assertEquals(animal.get("family"), "Carnivora"); // test custom attribute

		final ModuleItem<?> notAutoFilled = info.getInput("notAutoFilled");
		assertFalse(notAutoFilled.isAutoFill());

		final ModuleItem<?> msg = info.getInput("msg");
		assertSame(ItemVisibility.MESSAGE, msg.getVisibility());

		final ModuleItem<?> buffer = info.getOutput("buffer");
		assertItem("buffer", StringBuilder.class, null, ItemIO.BOTH, true, true,
			null, null, null, null, null, null, null, null, noChoices, buffer);

		int inputCount = 0;
		final ModuleItem<?>[] inputs = { log, sliderValue, animal, notAutoFilled, msg, buffer };
		for (final ModuleItem<?> inItem : info.inputs()) {
			assertSame(inputs[inputCount++], inItem);
		}

		int outputCount = 0;
		final ModuleItem<?>[] outputs = { buffer };
		for (final ModuleItem<?> outItem : info.outputs()) {
			assertSame(outputs[outputCount++], outItem);
		}
	}

	/** Tests {@code #@script} directives. */
	@Test
	public void testScriptDirective() {
		final String script = "" + //
			"#@script(name = \"my_script\"" + //
			", label = \"My Script\"" + //
			", description = \"What a great script.\"" + //
			", menuPath = \"Plugins > Do All The Things\"" + //
			", menuRoot = \"special\"" + //
			", iconPath = \"/path/to/myIcon.png\"" + //
			", priority = \"extremely-high\"" + //
			", headless = true" + //
			", foo = \"bar\"" + //
			")\n" +
			"WOOT\n";

		ScriptInfo info = null;
		info =
			new ScriptInfo(context, "scriptHeader.bsizes", new StringReader(script));
		info.inputs(); // HACK: Force lazy initialization.

		assertEquals("my_script", info.getName());
		assertEquals("My Script", info.getLabel());
		assertEquals("What a great script.", info.getDescription());
		final MenuPath menuPath = info.getMenuPath();
		assertEquals(2, menuPath.size());
		assertEquals("Plugins", menuPath.get(0).getName());
		assertEquals("Do All The Things", menuPath.get(1).getName());
		assertEquals("/path/to/myIcon.png", info.getIconPath());
		assertEquals(Priority.EXTREMELY_HIGH, info.getPriority(), 0.0);
		assertTrue(info.canRunHeadless());
		assertEquals("bar", info.get("foo"));
	}

	/**
	 * Ensures the ScriptInfos Reader can be reused for multiple executions of the
	 * script.
	 */
	@Test
	public void testReaderSanity() throws Exception {
		final String script = "" + //
			"% @LogService log\n" + //
			"% @OUTPUT Integer output";

		final ScriptInfo info =
			new ScriptInfo(context, "hello.bsizes", new StringReader(script));
		final BufferedReader reader1 = info.getReader();
		final BufferedReader reader2 = info.getReader();

		assertEquals("Readers are not independent.", reader1.read(), reader2.read());
	}

	// -- Helper methods --

	private String id(final String path, final String script) {
		final ScriptInfo info = //
			new ScriptInfo(context, path, new StringReader(script));
		info.inputs(); // NB: Force parameter parsing.
		return info.getIdentifier();
	}

	private void assertItem(final String name, final Class<?> type,
		final String label, final ItemIO ioType, final boolean required,
		final boolean persist, final String persistKey, final String style,
		final Object value, final Object min, final Object max,
		final Object softMin, final Object softMax, final Number stepSize,
		final List<?> choices, final ModuleItem<?> item)
	{
		assertEquals(name, item.getName());
		assertSame(type, item.getType());
		assertEquals(label, item.getLabel());
		assertSame(ioType, item.getIOType());
		assertEquals(required, item.isRequired());
		assertEquals(persist, item.isPersisted());
		assertEquals(persistKey, item.getPersistKey());
		assertEquals(style, item.getWidgetStyle());
		assertEquals(value, item.getDefaultValue());
		assertEquals(min, item.getMinimumValue());
		assertEquals(max, item.getMaximumValue());
		assertEquals(softMin, item.getSoftMinimum());
		assertEquals(softMax, item.getSoftMaximum());
		assertEquals(stepSize, item.getStepSize());
		assertEquals(choices, item.getChoices());
	}

	@Plugin(type = ScriptLanguage.class)
	public static class BindingSizes extends AbstractScriptLanguage {

		@Override
		public ScriptEngine getScriptEngine() {
			return new BindingSizesEngine();
		}

		@Override
		public List<String> getNames() {
			return Arrays.asList("BindingSizes");
		}

		@Override
		public List<String> getExtensions() {
			return Arrays.asList("bsizes");
		}
	}

	// -- Test script language --

	private static class BindingSizesEngine extends AbstractScriptEngine {

		{
			engineScopeBindings = new BindingSizesBindings();
		}

		@Override
		public Object eval(final String script) throws ScriptException {
			return eval(new StringReader(script));
		}

		@Override
		public Object eval(final Reader reader) throws ScriptException {
			final Bindings bindings = getBindings(ScriptContext.ENGINE_SCOPE);
			return bindings.size();
		}
	}

	private static class BindingSizesBindings extends HashMap<String, Object>
		implements Bindings
	{
		// NB: No implementation needed.
	}

}


text:
<?php
/*
* Test Suite
*
*/

error_reporting(E_ALL);
ini_set("display_errors", 1);
chdir(dirname(__FILE__));

$moduleFolder = getcwd()."/../../module";
echo "
";
	// Project Unit Tests
	echo "
Project Unit Tests
";
	$command = "phpunit -c ".$moduleFolder."/Application/tests/phpunit.xml";
	system($command);

	// Module Unit Tests
	echo "
Module Unit Tests
";
	$module = dir($moduleFolder);
	while (false !== ($entry = $module->read())) {
		if((strncmp($entry, ".", 1)) && ($entry != "Application")) {
			$phpunit = $moduleFolder."/".$entry."/tests/phpunit.xml";
			if(file_exists($phpunit)) {
				$command = "cd ".$moduleFolder."/".$entry."/tests; phpunit";
				echo "
$entry
";
				system($command);
			}
		}
	}
	$module->close();
echo "
";


text:
from meetup_wrapper import meetup
from datetime import datetime
from unittest import TestCase
from unittest.mock import patch
import json

class TestMeetupClient(TestCase):

    def test_connection(self):
        """ Integration test """
        client = meetup.MeetupClient()
        http_response = client.get_response(group_urlname='Buenos-Aires-Python-Meetup')
        self.assertEqual(http_response.status, 200)

    @patch('meetup_wrapper.meetup.MeetupClient')
    def test_events(self, mock_get):
        with open('tests/resources/response.json') as response_file:
            mock_get.return_value.get_events.return_value = json.loads(response_file.read())

            client = meetup.MeetupClient()
            json_response = client.get_events(group_urlname='Buenos-Aires-Python-Meetup')

            self.assertEqual('Charlas, Mates y Sprints!', json_response.get('results')[0].get('name'))
            self.assertEqual('http://www.meetup.com/Buenos-Aires-Python-Meetup/events/222357366/',
                             json_response.get('results')[0].get('event_url'))
            self.assertEqual("""
Vuelve el Buenos Aires Python Meetup. En esta oportunidad vamos a juntarnos todo un Sábado."""
                            """
Por la mañana vamos a tener charlas, al mediodía cortamos para charlar entre nosotros, comer algo, tomar unos """
                            """mates y por la tarde sprints! A programar hasta que nos inviten a retirarnos.

\n\n\nDetalle de las charlas: """
                            """"""
                            """"""
                            """http://listas.python.org.ar/pipermail/pyar/2015-May/034610.html

Los esperamos!
""",
                            json_response.get('results')[0].get('description'))

            self.assertEqual('222357366', json_response.get('results')[0].get('id'))
            start = json_response.get('results')[0].get('time')
            duration = json_response.get('results')[0].get('duration')
            self.assertEqual(1432990800000, start)
            self.assertEqual(28800000, duration)
            self.assertEqual(datetime(2015, 5, 30, 10), datetime.fromtimestamp(start / 1000))
            self.assertEqual(datetime(2015, 5, 30, 18), datetime.fromtimestamp((start + duration) / 1000))

if __name__ == '__main__':
    unittest.main()


text:
<resources>
    <string name="app_name">Safer</string>
</resources>


text:
warning:     "This is a dynamically generated file. Do not edit manually."
layout:      "default"
title:       "avoid-tx-origin | Solhint"
---

# avoid-tx-origin
![Recommended Badge](https://img.shields.io/badge/-Recommended-brightgreen)
![Category Badge](https://img.shields.io/badge/-Security%20Rules-informational)
![Default Severity Badge warn](https://img.shields.io/badge/Default%20Severity-warn-yellow)
> The {"extends": "solhint:recommended"} property in a configuration file enables this rule.

## Description
Avoid to use tx.origin.

## Options
This rule accepts a string option of rule severity. Must be one of "error", "warn", "off". Default to warn.

### Example Config
```json
{
  "rules": {
    "avoid-tx-origin": "warn"
  }
}
```

## Examples
This rule does not have examples.

## Version
This rule was introduced in [Solhint 1.1.5](https://github.com/protofire/solhint/tree/v1.1.5)

## Resources
- [Rule source](https://github.com/protofire/solhint/tree/master/lib/rules/security/avoid-tx-origin.js)
- [Document source](https://github.com/protofire/solhint/tree/master/docs/rules/security/avoid-tx-origin.md)
- [Test cases](https://github.com/protofire/solhint/tree/master/test/rules/security/avoid-tx-origin.js)


text:
<?php
/**
 * WooCommerce Cart Functions
 *
 * Functions for cart specific things.
 *
 * @author   WooThemes
 * @category Core
 * @package  WooCommerce/Functions
 * @version  2.5.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * Prevent password protected products being added to the cart.
 *
 * @param  bool $passed
 * @param  int $product_id
 * @return bool
 */
function wc_protected_product_add_to_cart( $passed, $product_id ) {
	if ( post_password_required( $product_id ) ) {
		$passed = false;
		wc_add_notice( __( 'This product is protected and cannot be purchased.', 'woocommerce' ), 'error' );
	}
	return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'wc_protected_product_add_to_cart', 10, 2 );

/**
 * Clears the cart session when called.
 */
function wc_empty_cart() {
	if ( ! isset( WC()->cart ) || '' === WC()->cart ) {
		WC()->cart = new WC_Cart();
	}
	WC()->cart->empty_cart( false );
}

/**
 * Load the persistent cart.
 *
 * @param string $user_login
 * @param WP_User $user
 * @deprecated 2.3
 */
function wc_load_persistent_cart( $user_login, $user ) {
	if ( ! $user || ! ( $saved_cart = get_user_meta( $user->ID, '_woocommerce_persistent_cart', true ) ) ) {
		return;
	}

	if ( empty( WC()->session->cart ) || ! is_array( WC()->session->cart ) || 0 === sizeof( WC()->session->cart ) ) {
		WC()->session->cart = $saved_cart['cart'];
	}
}

/**
 * Add to cart messages.
 *
 * @access public
 * @param int|array $product_id
 */
function wc_add_to_cart_message( $product_id ) {
	$titles = array();

	if ( is_array( $product_id ) ) {
		foreach ( $product_id as $id ) {
			$titles[] = get_the_title( $id );
		}
	} else {
		$titles[] = get_the_title( $product_id );
	}

	$titles     = array_filter( $titles );
	$added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', sizeof( $titles ), 'woocommerce' ), wc_format_list_of_items( $titles ) );

	// Output success messages
	if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
		$return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wp_get_referer() ? wp_get_referer() : home_url() );
		$message   = sprintf( '%s %s', esc_url( $return_to ), esc_html__( 'Continue Shopping', 'woocommerce' ), esc_html( $added_text ) );
	} else {
		$message   = sprintf( '%s %s', esc_url( wc_get_page_permalink( 'cart' ) ), esc_html__( 'View Cart', 'woocommerce' ), esc_html( $added_text ) );
	}

	wc_add_notice( apply_filters( 'wc_add_to_cart_message', $message, $product_id ) );
}

/**
 * Comma separate a list of item names, and replace final comma with 'and'
 * @param  array $items
 * @return string
 */
function wc_format_list_of_items( $items ) {
	$item_string = '';

	foreach ( $items as $key => $item ) {
		$item_string .= sprintf( _x( '“%s”', 'Item name in quotes', 'woocommerce' ), strip_tags( $item ) );

		if ( $key + 2 === sizeof( $items ) ) {
			$item_string .= ' ' . __( 'and', 'woocommerce' ) . ' ';
		} elseif ( $key + 1 !== sizeof( $items ) ) {
			$item_string .= ', ';
		}
	}

	return $item_string;
}

/**
 * Clear cart after payment.
 *
 * @access public
 */
function wc_clear_cart_after_payment() {
	global $wp;

	if ( ! empty( $wp->query_vars['order-received'] ) ) {

		$order_id  = absint( $wp->query_vars['order-received'] );
		$order_key = isset( $_GET['key'] ) ? wc_clean( $_GET['key'] ) : '';

		if ( $order_id > 0 ) {
			$order = wc_get_order( $order_id );

			if ( $order->order_key === $order_key ) {
				WC()->cart->empty_cart();
			}
		}
	}

	if ( WC()->session->order_awaiting_payment > 0 ) {
		$order = wc_get_order( WC()->session->order_awaiting_payment );

		if ( $order && $order->id > 0 ) {
			// If the order has not failed, or is not pending, the order must have gone through
			if ( ! $order->has_status( array( 'failed', 'pending', 'cancelled' ) ) ) {
				WC()->cart->empty_cart();
			}
		}
	}
}
add_action( 'get_header', 'wc_clear_cart_after_payment' );

/**
 * Get the subtotal.
 *
 * @access public
 * @return string
 */
function wc_cart_totals_subtotal_html() {
	echo WC()->cart->get_cart_subtotal();
}

/**
 * Get shipping methods.
 *
 * @access public
 */
function wc_cart_totals_shipping_html() {
	$packages = WC()->shipping->get_packages();

	foreach ( $packages as $i => $package ) {
		$chosen_method = isset( WC()->session->chosen_shipping_methods[ $i ] ) ? WC()->session->chosen_shipping_methods[ $i ] : '';
		$product_names = array();

		if ( sizeof( $packages ) > 1 ) {
			foreach ( $package['contents'] as $item_id => $values ) {
				$product_names[] = $values['data']->get_title() . ' ×' . $values['quantity'];
			}
		}

		wc_get_template( 'cart/cart-shipping.php', array(
			'package'              => $package,
			'available_methods'    => $package['rates'],
			'show_package_details' => sizeof( $packages ) > 1,
			'package_details'      => implode( ', ', $product_names ),
			'package_name'         => apply_filters( 'woocommerce_shipping_package_name', sprintf( _n( 'Shipping', 'Shipping %d', ( $i + 1 ), 'woocommerce' ), ( $i + 1 ) ), $i, $package ),
			'index'                => $i,
			'chosen_method'        => $chosen_method
		) );
	}
}

/**
 * Get taxes total.
 *
 * @access public
 */
function wc_cart_totals_taxes_total_html() {
	echo apply_filters( 'woocommerce_cart_totals_taxes_total_html', wc_price( WC()->cart->get_taxes_total() ) );
}

/**
 * Get a coupon label.
 *
 * @access public
 * @param string $coupon
 */
function wc_cart_totals_coupon_label( $coupon ) {
	if ( is_string( $coupon ) )
		$coupon = new WC_Coupon( $coupon );

	echo apply_filters( 'woocommerce_cart_totals_coupon_label', esc_html( __( 'Coupon:', 'woocommerce' ) . ' ' . $coupon->code ), $coupon );
}

/**
 * Get a coupon value.
 *
 * @access public
 * @param string $coupon
 */
function wc_cart_totals_coupon_html( $coupon ) {
	if ( is_string( $coupon ) ) {
		$coupon = new WC_Coupon( $coupon );
	}

	$value  = array();

	if ( $amount = WC()->cart->get_coupon_discount_amount( $coupon->code, WC()->cart->display_cart_ex_tax ) ) {
		$discount_html = '-' . wc_price( $amount );
	} else {
		$discount_html = '';
	}

	$value[] = apply_filters( 'woocommerce_coupon_discount_amount_html', $discount_html, $coupon );

	if ( $coupon->enable_free_shipping() ) {
		$value[] = __( 'Free shipping coupon', 'woocommerce' );
	}

	// get rid of empty array elements
	$value = array_filter( $value );
	$value = implode( ', ', $value ) . ' code ), defined( 'WOOCOMMERCE_CHECKOUT' ) ? wc_get_checkout_url() : wc_get_cart_url() ) ) . '" class="woocommerce-remove-coupon" data-coupon="' . esc_attr( $coupon->code ) . '">' . __( '[Remove]', 'woocommerce' ) . '';

	echo apply_filters( 'woocommerce_cart_totals_coupon_html', $value, $coupon );
}

/**
 * Get order total html including inc tax if needed.
 *
 * @access public
 */
function wc_cart_totals_order_total_html() {
	$value = '' . WC()->cart->get_total() . ' ';

	// If prices are tax inclusive, show taxes here
	if ( wc_tax_enabled() && WC()->cart->tax_display_cart == 'incl' ) {
		$tax_string_array = array();

		if ( get_option( 'woocommerce_tax_total_display' ) == 'itemized' ) {
			foreach ( WC()->cart->get_tax_totals() as $code => $tax )
				$tax_string_array[] = sprintf( '%s %s', $tax->formatted_amount, $tax->label );
		} else {
			$tax_string_array[] = sprintf( '%s %s', wc_price( WC()->cart->get_taxes_total( true, true ) ), WC()->countries->tax_or_vat() );
		}

		if ( ! empty( $tax_string_array ) ) {
			$taxable_address = WC()->customer->get_taxable_address();
			$estimated_text  = WC()->customer->is_customer_outside_base() && ! WC()->customer->has_calculated_shipping()
				? sprintf( ' ' . __( 'estimated for %s', 'woocommerce' ), WC()->countries->estimated_for_prefix( $taxable_address[0] ) . WC()->countries->countries[ $taxable_address[0] ] )
				: '';
			$value .= '' . sprintf( __( '(includes %s)', 'woocommerce' ), implode( ', ', $tax_string_array ) . $estimated_text ) . '';
		}
	}

	echo apply_filters( 'woocommerce_cart_totals_order_total_html', $value );
}

/**
 * Get the fee value.
 *
 * @param object $fee
 */
function wc_cart_totals_fee_html( $fee ) {
	$cart_totals_fee_html = ( 'excl' == WC()->cart->tax_display_cart ) ? wc_price( $fee->amount ) : wc_price( $fee->amount + $fee->tax );

	echo apply_filters( 'woocommerce_cart_totals_fee_html', $cart_totals_fee_html, $fee );
}

/**
 * Get a shipping methods full label including price.
 * @param  WC_Shipping_Rate $method
 * @return string
 */
function wc_cart_totals_shipping_method_label( $method ) {
	$label = $method->get_label();

	if ( $method->cost > 0 ) {
		if ( WC()->cart->tax_display_cart == 'excl' ) {
			$label .= ': ' . wc_price( $method->cost );
			if ( $method->get_shipping_tax() > 0 && WC()->cart->prices_include_tax ) {
				$label .= ' ' . WC()->countries->ex_tax_or_vat() . '';
			}
		} else {
			$label .= ': ' . wc_price( $method->cost + $method->get_shipping_tax() );
			if ( $method->get_shipping_tax() > 0 && ! WC()->cart->prices_include_tax ) {
				$label .= ' ' . WC()->countries->inc_tax_or_vat() . '';
			}
		}
	} elseif ( $method->id !== 'free_shipping' ) {
		$label .= ' (' . __( 'Free', 'woocommerce' ) . ')';
	}

	return apply_filters( 'woocommerce_cart_shipping_method_full_label', $label, $method );
}

/**
 * Round discount.
 *
 * @param  float $value
 * @param  int $precision
 * @return float
 */
function wc_cart_round_discount( $value, $precision ) {
	if ( version_compare( PHP_VERSION, '5.3.0', '>=' ) ) {
		return round( $value, $precision, WC_DISCOUNT_ROUNDING_MODE );
	} else {
		return round( $value, $precision );
	}
}


text:
<?php

namespace DB;

//! Simple cursor implementation
abstract class Cursor extends \Magic implements \IteratorAggregate {

	//@{ Error messages
	const
		E_Field='Undefined field %s';
	//@}

	protected
		//! Query results
		$query=array(),
		//! Current position
		$ptr=0,
		//! Event listeners
		$trigger=array();

	/**
	*	Return database type
	*	@return string
	**/
	abstract function dbtype();

	/**
	*	Return field names
	*	@return array
	**/
	abstract function fields();

	/**
	*	Return fields of mapper object as an associative array
	*	@return array
	*	@param $obj object
	**/
	abstract function cast($obj=NULL);

	/**
	*	Return records (array of mapper objects) that match criteria
	*	@return array
	*	@param $filter string|array
	*	@param $options array
	*	@param $ttl int
	**/
	abstract function find($filter=NULL,array $options=NULL,$ttl=0);

	/**
	*	Count records that match criteria
	*	@return int
	*	@param $filter array
	*	@param $ttl int
	**/
	abstract function count($filter=NULL,$ttl=0);

	/**
	*	Insert new record
	*	@return array
	**/
	abstract function insert();

	/**
	*	Update current record
	*	@return array
	**/
	abstract function update();

	/**
	*	Hydrate mapper object using hive array variable
	*	@return NULL
	*	@param $var array|string
	*	@param $func callback
	**/
	abstract function copyfrom($var,$func=NULL);

	/**
	*	Populate hive array variable with mapper fields
	*	@return NULL
	*	@param $key string
	**/
	abstract function copyto($key);

	/**
	*	Get cursor's equivalent external iterator
	*	Causes a fatal error in PHP 5.3.5if uncommented
	*	return ArrayIterator
	**/
	abstract function getiterator();

	/**
	*	Return TRUE if current cursor position is not mapped to any record
	*	@return bool
	**/
	function dry() {
		return empty($this->query[$this->ptr]);
	}

	/**
	*	Return first record (mapper object) that matches criteria
	*	@return \DB\Cursor|FALSE
	*	@param $filter string|array
	*	@param $options array
	*	@param $ttl int
	**/
	function findone($filter=NULL,array $options=NULL,$ttl=0) {
		if (!$options)
			$options=array();
		// Override limit
		$options['limit']=1;
		return ($data=$this->find($filter,$options,$ttl))?$data[0]:FALSE;
	}

	/**
	*	Return array containing subset of records matching criteria,
	*	total number of records in superset, specified limit, number of
	*	subsets available, and actual subset position
	*	@return array
	*	@param $pos int
	*	@param $size int
	*	@param $filter string|array
	*	@param $options array
	*	@param $ttl int
	**/
	function paginate(
		$pos=0,$size=10,$filter=NULL,array $options=NULL,$ttl=0) {
		$total=$this->count($filter,$ttl);
		$count=ceil($total/$size);
		$pos=max(0,min($pos,$count-1));
		return array(
			'subset'=>$this->find($filter,
				array_merge(
					$options?:array(),
					array('limit'=>$size,'offset'=>$pos*$size)
				),
				$ttl
			),
			'total'=>$total,
			'limit'=>$size,
			'count'=>$count,
			'pos'=>$pos<$count?$pos:0
		);
	}

	/**
	*	Map to first record that matches criteria
	*	@return array|FALSE
	*	@param $filter string|array
	*	@param $options array
	*	@param $ttl int
	**/
	function load($filter=NULL,array $options=NULL,$ttl=0) {
		return ($this->query=$this->find($filter,$options,$ttl)) &&
			$this->skip(0)?$this->query[$this->ptr=0]:FALSE;
	}

	/**
	*	Return the count of records loaded
	*	@return int
	**/
	function loaded() {
		return count($this->query);
	}

	/**
	*	Map to first record in cursor
	*	@return mixed
	**/
	function first() {
		return $this->skip(-$this->ptr);
	}

	/**
	*	Map to last record in cursor
	*	@return mixed
	**/
	function last() {
		return $this->skip(($ofs=count($this->query)-$this->ptr)?$ofs-1:0);
	}

	/**
	*	Map to nth record relative to current cursor position
	*	@return mixed
	*	@param $ofs int
	**/
	function skip($ofs=1) {
		$this->ptr+=$ofs;
		return $this->ptr>-1 && $this->ptr<count($this->query)?
			$this->query[$this->ptr]:FALSE;
	}

	/**
	*	Map next record
	*	@return mixed
	**/
	function next() {
		return $this->skip();
	}

	/**
	*	Map previous record
	*	@return mixed
	**/
	function prev() {
		return $this->skip(-1);
	}

	/**
	 * Return whether current iterator position is valid.
	 */
	function valid() {
		return !$this->dry();
	}

	/**
	*	Save mapped record
	*	@return mixed
	**/
	function save() {
		return $this->query?$this->update():$this->insert();
	}

	/**
	*	Delete current record
	*	@return int|bool
	**/
	function erase() {
		$this->query=array_slice($this->query,0,$this->ptr,TRUE)+
			array_slice($this->query,$this->ptr,NULL,TRUE);
		$this->skip(0);
	}

	/**
	*	Define onload trigger
	*	@return callback
	*	@param $func callback
	**/
	function onload($func) {
		return $this->trigger['load']=$func;
	}

	/**
	*	Define beforeinsert trigger
	*	@return callback
	*	@param $func callback
	**/
	function beforeinsert($func) {
		return $this->trigger['beforeinsert']=$func;
	}

	/**
	*	Define afterinsert trigger
	*	@return callback
	*	@param $func callback
	**/
	function afterinsert($func) {
		return $this->trigger['afterinsert']=$func;
	}

	/**
	*	Define oninsert trigger
	*	@return callback
	*	@param $func callback
	**/
	function oninsert($func) {
		return $this->afterinsert($func);
	}

	/**
	*	Define beforeupdate trigger
	*	@return callback
	*	@param $func callback
	**/
	function beforeupdate($func) {
		return $this->trigger['beforeupdate']=$func;
	}

	/**
	*	Define afterupdate trigger
	*	@return callback
	*	@param $func callback
	**/
	function afterupdate($func) {
		return $this->trigger['afterupdate']=$func;
	}

	/**
	*	Define onupdate trigger
	*	@return callback
	*	@param $func callback
	**/
	function onupdate($func) {
		return $this->afterupdate($func);
	}

	/**
	*	Define beforesave trigger
	*	@return callback
	*	@param $func callback
	**/
	function beforesave($func) {
		$this->trigger['beforeinsert']=$func;
		$this->trigger['beforeupdate']=$func;
		return $func;
	}

	/**
	*	Define aftersave trigger
	*	@return callback
	*	@param $func callback
	**/
	function aftersave($func) {
		$this->trigger['afterinsert']=$func;
		$this->trigger['afterupdate']=$func;
		return $func;
	}

	/**
	*	Define onsave trigger
	*	@return callback
	*	@param $func callback
	**/
	function onsave($func) {
		return $this->aftersave($func);
	}

	/**
	*	Define beforeerase trigger
	*	@return callback
	*	@param $func callback
	**/
	function beforeerase($func) {
		return $this->trigger['beforeerase']=$func;
	}

	/**
	*	Define aftererase trigger
	*	@return callback
	*	@param $func callback
	**/
	function aftererase($func) {
		return $this->trigger['aftererase']=$func;
	}

	/**
	*	Define onerase trigger
	*	@return callback
	*	@param $func callback
	**/
	function onerase($func) {
		return $this->aftererase($func);
	}

	/**
	*	Reset cursor
	*	@return NULL
	**/
	function reset() {
		$this->query=array();
		$this->ptr=0;
	}

}


text:
package im.hch.datareceiver.jobs;

import java.net.MalformedURLException;
import java.net.URL;

public class CurlJob extends CommandJob {

    @Override
    public String getCommand(Object[] args) {
        if (!validArgs(args)) {
            return null;
        }

        String command = "curl " + (String)args[0];
        return command;
    }

    @Override
    public boolean validArgs(Object[] args) {
        if (args == null || args.length == 0) {
            return false;
        }

        try {
            URL url = new URL((String) args[0]);
            return true;
        } catch (MalformedURLException ex) {
            appendExecLog("Wrong URL: " + args[0]);
            return false;
        }
    }
}


text: © Runestake 2015


text:
package backend.flowNetwork.transformations

import akka.actor.Props
import backend.flowNetwork.{FlowNode, TargetableFlow}
import backend.flowTypes.FlowObject

object FlowMultiplier {
  var nodeType = "Multiplier"
  def props(id:Long, name: String,  x: Int, y: Int): Props = Props(new FlowMultiplier(id, name, x, y))
}

/**
 * Duplicates incoming messages a configurable amount of times to the target.
 * @note Does not generate unique IDs for message copies.
 *
 * @param id Unique numeric ID of this actor
 * @param name Display name for this actor
 * @param x X coordinate on screen
 * @param y Y coordinate on screen
 */
class FlowMultiplier(id: Long, name: String,  x: Int, y: Int)
  extends FlowNode(id, name, FlowMultiplier.nodeType, x, y, 1, 1) with TargetableFlow {

  var factor: Int = 2

  addConfigSetters({
    case ("factor", f) =>
      factor = f.toInt
      log.info(s"Updating multiplier factor to '$f'")
  })

  addConfigMapGetters(() => Map(
    "factor" -> factor.toString,
    "display" -> "factor"
  ))

  override def active: Receive = {
    case o: FlowObject =>
      for (i <- 1 to factor) target ! o //FIXME: This will duplicate UIDs which should be a big nono. We don't really care at the moment
  }
}


text:
using System;
using Shuttle.Core.Data;
using Shuttle.Process.Custom.Server.Domain;

namespace Shuttle.ProcessManagement
{
    public interface IOrderProcessQueryFactory
    {
        IQuery Add(OrderProcess orderProcess);
        IQuery AddItem(OrderProcessItem orderProcessItem, Guid id);
        IQuery AddStatus(OrderProcessStatus status, Guid id);
        IQuery Get(Guid id);
        IQuery GetItems(Guid id);
        IQuery GetStatuses(Guid id);
        IQuery Remove(Guid id);
        IQuery SaveOrderId(Guid orderId, Guid id);
        IQuery SaveInvoiceId(Guid invoiceId, Guid id);
    }
}


text:
using DecisionTree.Models;
using DecisionTree.Models.Paths;

namespace DecisionTree.ViewModels.Headers
{
    public class RootPathHeader : PathHeader
    {
        private readonly Root _root;

        public RootPathHeader(Root root, Selection selection) :
            base(selection)
        {
            _root = root;
        }

        public override Path Path => _root;
    }
}


text:
package crm

import (
	. "aliyun-openapi-go-sdk/core"
)

type DeleteLabelRequest struct {
	RpcRequest
	PK          string
	LabelName   string
	LabelSeries string
}

func (r *DeleteLabelRequest) SetPK(value string) {
	r.PK = value
	r.QueryParams.Set("PK", value)
}
func (r *DeleteLabelRequest) GetPK() string {
	return r.PK
}
func (r *DeleteLabelRequest) SetLabelName(value string) {
	r.LabelName = value
	r.QueryParams.Set("LabelName", value)
}
func (r *DeleteLabelRequest) GetLabelName() string {
	return r.LabelName
}
func (r *DeleteLabelRequest) SetLabelSeries(value string) {
	r.LabelSeries = value
	r.QueryParams.Set("LabelSeries", value)
}
func (r *DeleteLabelRequest) GetLabelSeries() string {
	return r.LabelSeries
}

func (r *DeleteLabelRequest) Init() {
	r.RpcRequest.Init()
	r.SetVersion(Version)
	r.SetAction("DeleteLabel")
	r.SetProduct(Product)
}

type DeleteLabelResponse struct {
	Result string `xml:"Result" json:"Result"`
}

func DeleteLabel(req *DeleteLabelRequest, accessId, accessSecret string) (*DeleteLabelResponse, error) {
	var pResponse DeleteLabelResponse
	body, err := ApiHttpRequest(accessId, accessSecret, req)
	if err != nil {
		return nil, err
	}
	ApiUnmarshalResponse(req.GetFormat(), body, &pResponse)
	return &pResponse, err
}


text:
@implementation NSThread (Blocks)

- (void)runBlock:(void (^)())block
{
    block();
}

- (void)performBlock:(void (^)())block
{
    [self performBlock:block waitUntilDone:NO];
}

- (void)performBlock:(void (^)())block waitUntilDone:(BOOL)wait
{
    if ([[NSThread currentThread] isEqualTo:self] && wait)
        block();
    else
        [self performSelector:@selector(runBlock:) onThread:self withObject:[[block copy] autorelease] waitUntilDone:wait];
}

@end


text:
package boundaryh

//replacer:ignore
// TODO replace windows path separator
//go:generate go run $GOPATH\src\github.com\apaxa-go\generator\replacer\main.go -- $GOFILE

// sSequence rules:
// 	        CR LF        => Sep
// 	      (CR | LF)      => Sep
//	         Sep         => Sep
// 	X (Extend | Format)* => X (where X is not Sep)

//replacer:replace
//replacer:old InRunes	[]rune	runes
//replacer:new InString	string	s
//replacer:new ""		[]byte	bytes

// Then looking end of sentence at custom position it may be required to parse some runes before.
// First of all going back to beginning of SB5 group is required.
// Moreover, custom position may be in the middle (Close or Sp) of (possible) SB11.
// Or if custom point is ATerm then class of previous SB5 group required for SB7 checking.
// Returns position at which it is safe to begin analysis.
func sForwardSafePositionInRunes(runes []rune, pos int) (r int) {
	if pos == 0 {
		return 0
	}

	pos = toNextRuneInRunes(runes, pos) // TODO make name similar
	c, pos := sLastSequenceInRunes(runes[:pos])
	if pos == 0 {
		return 0
	}
	r = pos

	switch c {
	case sClassSp, sClassClose: // in the middle of possible SB11
	case sClassATerm: // possible SB7 - require <prevClass>
		if pos > 0 {
			_, pos = sLastSequenceInRunes(runes[:pos])
		}
		return pos
	default:
		return
	}

	for c == sClassSp && pos > 0 {
		c, pos = sLastSequenceInRunes(runes[:pos])
	}
	for c == sClassClose && pos > 0 {
		c, pos = sLastSequenceInRunes(runes[:pos])
	}
	switch c {
	case sClassATerm, sClassSTerm:
		return pos
	default:
		return // Not SB11 sequence
	}
}

func sBackwardSafePositionInRunes(runes []rune, pos int) int {
	pos = toNextRuneInRunes(runes, pos)
	_, pos = sLastSequenceInRunes(runes[:pos])
	return pos
}

// Computes first sSequence.
// Returns:
// 	"c"   - sSequence class (see "sSequence rules").
// 	"pos" - point to first rune of next sequence (in other words "pos" is length of current sSequence).
func sFirstSequenceInRunes(runes []rune) (c sClass, pos int) {
	l := len(runes)
	if l == 0 {
		c = sClassOther
		return
	}

	if runes[0] == crRune { // SB4
		if l > 1 && runes[1] == lfRune { // SB3
			return sClassSep, 2
		}
		return sClassSep, 1
	}

	if runes[0] == lfRune { // SB4
		return sClassSep, 1
	}

	c, pos = sFirstClassInRunes(runes)

	if c == sClassSep { // SB4
		return
	}

	for pos < len(runes) { // SB5
		c0, delta := sFirstClassInRunes(runes[pos:])
		if !c0.isSkip() {
			break
		}
		pos += delta
	}

	return
}

// Computes last sSequence.
// Analogue to sFirstSequenceInRunes.
// "pos" points to first rune in sequence.
func sLastSequenceInRunes(runes []rune) (c sClass, pos int) {
	l := len(runes)
	if l == 0 {
		c = sClassOther
		return
	}

	pos = l - 1
	if runes[pos] == lfRune { // SB4
		c = sClassSep
		if pos > 0 && runes[pos-1] == crRune { // SB3
			pos--
		}
		return
	}

	if runes[pos] == crRune { // SB4
		c = sClassSep
		return
	}

	c, pos = sLastClassInRunes(runes)
	if !c.isSkip() {
		return
	}

	for pos > 0 { // SB5
		newC, pos1 := sLastClassInRunes(runes[:pos])
		if newC == sClassSep || runes[pos-1] == crRune || runes[pos-1] == lfRune { // SB4
			//pos++
			return
		}
		c = newC
		pos = pos1
		if !newC.isSkip() {
			return
		}
	}
	return c, 0
}

// Computes required classes and possible positions for continue after founded ATerm or STerm.
func sParseAfterSATermInRunes(runes []rune) (closeSp bool, nextClass sClass, pos1, pos2 int) {
	l := len(runes)
	for pos1 < l {
		if c, delta := sFirstSequenceInRunes(runes[pos1:]); c == sClassClose {
			closeSp = true
			pos1 += delta
		} else {
			break
		}
	}
	for pos1 < l {
		if c, delta := sFirstSequenceInRunes(runes[pos1:]); c == sClassSp {
			closeSp = true
			pos1 += delta
		} else {
			break
		}
	}
	nextClass, delta := sFirstSequenceInRunes(runes[pos1:])
	pos2 = pos1 + delta
	return
}

// newL0 used as l0 by parent function. It used only if stop==false and is undefined if stop==true.
//
//  Break?  |  <l0>   ATerm Close* Sp* <lastClass>        | Ruler
//   yes    |         ATerm Close* Sp* ParaSep            | SB11
//   no     |         ATerm -      -   Numeric            | SB6
//   no     | Upper   ATerm -      -   Upper              | SB7
//   no     | Lower   ATerm -      -   Upper              | SB7
//   no     |         ATerm Close* Sp* Lower              | SB8
//   no     |         ATerm Close* Sp* isSB8+       Lower | SB8
//   no     |         ATerm Close* Sp* SContinue          | SB8a
//   no     |         ATerm Close* Sp* ATerm              | SB8a
//   no     |         ATerm Close* Sp* STerm              | SB8a
//   yes    |         ATerm Close* Sp*                    | SB11
func sDecideAtATermInRunes(l0 sClass, runes []rune) (stop bool, pos int, newL0 sClass) {
	closeSp, newL0, pos1, pos := sParseAfterSATermInRunes(runes)
	switch {
	case newL0 == sClassSep: // SB11
		stop = true
	case !closeSp && newL0 == sClassNumeric: // SB6
	case (l0 == sClassUpper || l0 == sClassLower) && !closeSp && newL0 == sClassUpper: // SB7
	case newL0 == sClassSContinue || newL0 == sClassATerm || newL0 == sClassSTerm: // SB8a
	case newL0 == sClassLower: // SB8 (part 1)
	case newL0.isSB8(): // SB8 (part 2)
		for pos < len(runes) {
			var deltaI int
			newL0, deltaI = sFirstSequenceInRunes(runes[pos:])
			pos += deltaI
			if newL0 == sClassLower {
				return
			}
			if !newL0.isSB8() {
				break
			}
		}
		stop = true
		pos = pos1
	default: // SB11
		stop = true
		pos = pos1
	}
	return
}

// newL0 used as l0 by parent function. It used only if stop==false and is undefined if stop==true.
//
//  Break?  | STerm Close* Sp* some-type? | Ruler
//   yes    | STerm Close* Sp* ParaSep    | SB11
//   no     | STerm Close* Sp* SContinue  | SB8a
//   no     | STerm Close* Sp* ATerm      | SB8a
//   no     | STerm Close* Sp* STerm      | SB8a
//   yes    | STerm Close* Sp*            | SB11
func sDecideAtSTermInRunes(runes []rune) (stop bool, pos int, newL0 sClass) {
	_, newL0, i1, pos := sParseAfterSATermInRunes(runes)
	switch newL0 {
	case sClassSep: // SB11
		stop = true
	case sClassSContinue, sClassATerm, sClassSTerm: // SB8a
	default:
		stop = true // SB11
		pos = i1
	}
	return
}

// SentenceEndInRunes computes sentence which contains pos-th rune.
// Returns (index of sentence's last rune)+1.
// In other words, returns first sentence's boundary on the right of pos-th rune.
func SentenceEndInRunes(runes []rune, pos int) int {
	l := len(runes)
	if pos < 0 || pos >= l {
		return InvalidPos
	}
	if pos == l-1 {
		return l
	}

	pos = sForwardSafePositionInRunes(runes, pos) // go backward to analysis-safe position

	l1 := sClassOther
	for pos < l {
		l0, deltaPos := sFirstSequenceInRunes(runes[pos:])
		pos += deltaPos

		if pos >= l { // end of runes
			return l
		}

		switch l0 {
		case sClassSep: // SB4
			return pos
		case sClassATerm:
			stop, deltaPos, newL0 := sDecideAtATermInRunes(l1, runes[pos:])
			pos += deltaPos
			if stop {
				return pos
			}
			l1 = newL0
		case sClassSTerm:
			stop, deltaPos, newL0 := sDecideAtSTermInRunes(runes[pos:])
			pos += deltaPos
			if stop {
				return pos
			}
			l1 = newL0
		default:
			l1 = l0
		}
	}
	return l
}

// SentenceBeginInRunes computes sentence which contains pos-th rune.
// Returns sentence's first rune index.
// In other words, returns first sentence's boundary on the left of pos-th rune.
func SentenceBeginInRunes(runes []rune, pos int) int {
	l := len(runes)
	if pos < 0 || pos >= l {
		return InvalidPos
	}
	if pos == 0 {
		return 0
	}

	origPos := pos
	pos = sBackwardSafePositionInRunes(runes, pos)
	//_, pos = sLastSequenceInRunes(runes[:pos+1])
	for pos > 0 {
		c, newPos := sLastSequenceInRunes(runes[:pos])
		switch c {
		case sClassSep:
			return pos
		case sClassATerm:
			l0, _ := sLastSequenceInRunes(runes[:newPos])
			stop, deltaI, _ := sDecideAtATermInRunes(l0, runes[pos:])
			if stop && pos+deltaI <= origPos { // avoid cases with passed "pos" in the middle of SB11 (in such cases boundary may be founded on the right side instead of left).
				return pos + deltaI
			}
		case sClassSTerm:
			stop, deltaI, _ := sDecideAtSTermInRunes(runes[pos:])
			if stop && pos+deltaI <= origPos { // avoid cases with passed "pos" in the middle of SB11 (in such cases boundary may be founded on the right side instead of left).
				return pos + deltaI
			}
		}
		pos = newPos
	}
	return 0
}

// SentenceAtInRunes computes sentence which contains pos-th rune and return their boundary.
// Sentence may retrieved by "runes[r.From:r.To]".
func SentenceAtInRunes(runes []rune, pos int) Boundary {
	return Boundary{SentenceBeginInRunes(runes, pos), SentenceEndInRunes(runes, pos)}
}

// LastSentenceInRunes computes last sentence.
// Returns index of sentence's first rune.
// Last sentence may retrieved by "runes[r:]".
func LastSentenceInRunes(runes []rune) int {
	return SentenceBeginInRunes(runes, len(runes)-1)
}

// FirstSentenceInRunes computes first sentence.
// Returns (index of sentence's last rune)+1.
// Result also may be treated as length of the first sentence.
// First sentence may retrieved by "runes[:r]".
func FirstSentenceInRunes(runes []rune) int {
	return SentenceEndInRunes(runes, 0)
}

// SentencesInRunes computes all sentences and returns theirs boundaries.
func SentencesInRunes(runes []rune) (boundaries []Boundary) {
	boundaries = make([]Boundary, 0, len(runes)) // TODO memory efficient
	for i := 0; i < len(runes); {
		length := FirstSentenceInRunes(runes[i:])
		boundaries = append(boundaries, Boundary{i, i + length})
		i += length
	}
	return
}

// SentenceBreaksInRunes computes all sentences and returns all breaks.
func SentenceBreaksInRunes(runes []rune) (breaks []int) {
	l := len(runes)
	if l == 0 {
		return
	}
	breaks = make([]int, 1, len(runes)) // TODO memory efficient
	breaks[0] = 0
	for pos := 0; pos < l; {
		length := FirstSentenceInRunes(runes[pos:])
		pos += length
		breaks = append(breaks, pos)
	}
	return
}


text:
package org.geogit.api;

public class GlobalContextBuilder {

    public static ContextBuilder builder = new ContextBuilder();

}


text:
package unused.to.us.harha.jpath;

import unused.to.us.harha.jpath.util.Logger;

public class Main
{

	// Program window's title String
	public static final String TITLE   = "Path Tracer | 1 = raytracer, 2 = pathtracer, wasd = move";

	// Main EPSILON value, used for floating point value comparison
	public static final float  EPSILON = 1e-3f;

	// Main Display object
	private static Display     display;

	// Main Engine object
	private static Engine      engine;

	// Main Logger object
	public static final Logger LOG     = new Logger(Main.class.getName());

	/*
	 * Main method
	 */
	public static void main(String[] args)
	{
		// Load an existing config file or create one with default values
		Config.initConfig();

		// Create a display object to draw things on
		display = new Display(Config.window_width, Config.window_height, Config.window_scale, TITLE);
		display.create();

		// Create an engine object
		engine = new Engine(display);
		engine.start();
	}

}


text:
package water;
import java.util.concurrent.Future;

import water.DTask;

/**
 * Push the given key to the remote node
 *
 * @author
 * @version 1.0
 */

public class TaskPutKey extends DTask<TaskPutKey> {
  Key _key;
  Value _val;
  boolean _dontCache; // delete cached value on the sender's side?
  transient Value _xval;
  transient Key _xkey;

  static void put( H2ONode h2o, Key key, Value val, Futures fs, boolean dontCache) {
    Future f = RPC.call(h2o,new TaskPutKey(key,val,dontCache));
    if( fs != null ) fs.add(f);
  }

  protected TaskPutKey( Key key, Value val ) { this(key,val,false);}
  protected TaskPutKey( Key key, Value val, boolean removeCache ) { _xkey = _key = key; _xval = _val = val; _dontCache = removeCache;}

  @Override public void dinvoke( H2ONode sender ) {
    assert _key.home() || _val==null; // Only PUT to home for keys, or remote invalidation from home
    Paxos.lockCloud();
    // Initialize Value for having a single known replica (the sender)
    if( _val != null ) _val.initReplicaHome(sender,_key);
    // Spin, until we update something.
    Value old = H2O.raw_get(_key); // Raw-get: do not lazy-manifest if overwriting
    while( H2O.putIfMatch(_key,_val,old) != old )
      old = H2O.raw_get(_key);  // Repeat until we update something.
    // Invalidate remote caches.  Block, so that all invalidates are done
    // before we return to the remote caller.
    if( _key.home() && old != null )
      old.lockAndInvalidate(sender,new Futures()).blockForPending();
    // No return result
    _key = null;
    _val = null;
    tryComplete();
  }
  @Override public void compute2() { throw H2O.unimpl(); }

  // Received an ACK
  @Override public void onAck() {
    // remove local cache but NOT in case it is already on disk
    // (ie memory can be reclaimed and we assume we have plenty of disk space)
    if( _dontCache && !_xval.isPersisted() ) H2O.putIfMatch(_xkey, null, _xval);
    if( _xval != null ) _xval.completeRemotePut();
  }
  @Override public byte priority() {
    return H2O.PUT_KEY_PRIORITY;
  }
}


text:
from .mixins import ResourceMixin

class ProductStatus(object):

    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)

    def __repr__(self):
        return '<ProductStatus %s: %s>' % (
            self.productId, self.title
        )

    def get_internal_id(self):
        return self.productId.split(':')[-1]

    def has_issue_level(self, level):
        if hasattr(self, 'dataQualityIssues'):
            for issue in self.dataQualityIssues:
                if issue['severity'] == level:
                    return True
        return False

    @property
    def should_be_removed(self):
        return self.has_issue_level('critical')

class ProductStatusManager(ResourceMixin):
    scope = 'productstatuses'
    resource_class = ProductStatus
    single_resource_id = 'productId'

    def remove_critical_issues(self):
        """
        Iterator through all statuses and remove products
        which has severity of critical
        """
        for status in self.list():
            if status.should_be_removed:
                self.manager.products.delete(
                    status.get_internal_id()
                )


text:
import {NodeContext} from './preboot.interfaces';
import {getNodeKeyForPreboot} from './get-node-key';

describe('UNIT TEST get-node-key', function() {
  describe('getNodeKeyForPreboot()', function() {
    it('should generate a default name', function() {
      const nodeContext = <NodeContext>{
        root: {
          serverNode: {},
          clientNode: {},
        },
        node: {}
      };
      const expected = 'unknown';
      const actual = getNodeKeyForPreboot(nodeContext);
      expect(actual).toEqual(expected);
    });

    it('should generate a name for a deeply nested element', function() {

      const node = document.createElement('foo');
      const serverNode = document.createElement('div');
      const emptyNode = document.createElement('div');
      const levelTwo = document.createElement('div');
      const levelThree = document.createElement('div');

      levelThree.appendChild(emptyNode.cloneNode());
      levelThree.appendChild(emptyNode.cloneNode());
      levelThree.appendChild(emptyNode.cloneNode());
      levelThree.appendChild(node);

      levelTwo.appendChild(emptyNode.cloneNode());
      levelTwo.appendChild(levelThree);

      serverNode.appendChild(emptyNode.cloneNode());
      serverNode.appendChild(emptyNode.cloneNode());
      serverNode.appendChild(levelTwo);

      const nodeContext = {
        root: {
          serverNode,
          clientNode: emptyNode
        },
        node
      };

      const expected = 'FOO_s3_s2_s4';
      const actual = getNodeKeyForPreboot(nodeContext);
      expect(actual).toEqual(expected);
    });
  });
});


text:
require 'test_helper'

class Admin::RepositoriesHelperTest < ActionView::TestCase
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.tfoxy</groupId>
    <artifactId>resizable-label</artifactId>
    <version>1.0.0</version>
    <name>Resizable Label</name>
    <description>JLabel that is automatically resized to fit its text</description>
    <url>https://github.com/tfoxy/resizable-label</url>

    <issueManagement>
        <url>https://github.com/tfoxy/resizable-label/issues</url>
        <system>GitHub Issues</system>
    </issueManagement>

    <licenses>
        <license>
            <name>MIT License</name>
            <url>http://www.opensource.org/licenses/mit-license.php</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <scm>
        <connection>scm:git:git@github.com:tfoxy/resizable-label.git</connection>
        <developerConnection>scm:git:git@github.com:tfoxy/resizable-label.git</developerConnection>
        <url>scm:git:git@github.com:tfoxy/resizable-label.git</url>
        <tag>HEAD</tag>
    </scm>

    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <developers>
        <developer>
            <email>tomas.c.fox@gmail.com</email>
            <name>Tomás Fox</name>
            <url>https://github.com/tfoxy</url>
            <id>tfoxy</id>
        </developer>
    </developers>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.2.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.9.1</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-gpg-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <id>sign-artifacts</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>sign</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
                <version>1.6.3</version>
                <extensions>true</extensions>
                <configuration>
                    <serverId>ossrh</serverId>
                    <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                    <autoReleaseAfterClose>true</autoReleaseAfterClose>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
"use strict";

var _ = require("underscore");
var Graph = require("../../graph");

module.exports.redirect = function (graph, from, to) {
  var edges = from.inEdges.slice(0);

  _.each(edges, function (edge) {
    graph.addEdge(
      new Graph.Edge(edge.source, to, edge.value)
    );

    graph.removeEdge(edge);
  });
};


text:
namespace JSON
{
    std::string js_stringify(std::string const& name, std::nullptr_t ptr, StringificationOptions const& options)
    {
        switch (options.ptr_behaviour)
        {
            case (PointerHandling::IGNORE):
            {
                return {};
            }
            case (PointerHandling::DEREFERENCE):
            {
                throw NullptrException{};
            }
            case (PointerHandling::ADDRESS):
            {
                std::stringstream sstr;
                WRITE_NAME(sstr);
                APPLY_IO_MANIPULATERS(sstr);
                sstr << reinterpret_cast <uint_of_size<sizeof(void*)>::type> (ptr);
                return sstr.str();
            }
            default:
                return {};
        }
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/file.h>
#include <string.h>
#include "acodes.h"
#include "acqparms.h"
#include "abort.h"

extern int bgflag;

#define MAXSTRING	32

typedef struct ipalist {
struct ipalist	*nextitem;
int		index;
char		label[MAXSTRING];
double          value;
double          units;
int             min;
int             max;
int             type;
int             scale;
int             device;
codeint         counter;
} ipaList;

static ipaList *ipalisthead = NULL;

add_to_ipalist(label, value, units, min, max, type, scale, counter, device)
char           *label;
double          value;
double          units;
int             min;
int             max;
int             type;
int             scale;
int             device;
codeint         counter;
{
 ipaList *newipa, *curipa;
 int i;

   if (ipalisthead == NULL)
   {
	newipa = (ipaList *) malloc(sizeof(ipaList));
	if (newipa != NULL)
	   ipalisthead = newipa;
	else
	{
           abort_message("add_to_ipalist: Unable to create new item.\n");
	}
	newipa->index=0;
   }
   else
   {
	i = 1;
	curipa = ipalisthead;
	while(curipa->nextitem != NULL)
	{
	   i++;
	   curipa = curipa->nextitem;
	}
	newipa = (ipaList *) malloc(sizeof(ipaList));
	if (newipa != NULL)
	   curipa->nextitem = newipa;
	else
	{
           abort_message("add_to_ipalist: Unable to create new item.\n");
	}
	newipa->index=i;
   }
   strcpy(newipa->label,label);
   newipa->value = value;
   newipa->units = units;
   newipa->min = min;
   newipa->max = max;
   newipa->type = type;
   newipa->scale = scale;
   newipa->device = device;
   newipa->counter = counter;
   newipa->nextitem = NULL;

}

insertIPAcode(counter)
codeint counter;
{
   counter = counter*2;
   putcode(IPACODE);
   putcode(counter);
}

change_ipalocation(oldcounter,newcounter)
codeint	oldcounter,newcounter;
{
 ipaList *curipa;
   if (ipalisthead == NULL)
	return;

   curipa = ipalisthead;
   while((curipa->nextitem != NULL) && (curipa->counter != oldcounter))
   {
	curipa = curipa->nextitem;
   }
   if (curipa->counter == oldcounter)
   {
	curipa->counter = newcounter;
	if (bgflag)
	  fprintf(stderr,"change_ipalocation: oldcounter: %d newcounter: %d\n",
				oldcounter,newcounter);
   }
   else
   {
	if (bgflag)
	  fprintf(stderr,"Error oldcounter: %d \n",oldcounter);
   }
}

flush_ipalist(acqifile)
FILE *acqifile;
{
 ipaList *curipa;
   curipa = ipalisthead;
   while(curipa != NULL)
   {
	fprintf(acqifile,"%6s %g %g %d %d %d %d %d %d\n",
		curipa->label,
		curipa->value,
		curipa->units,
		curipa->min,
		curipa->max,
		curipa->type,
		curipa->scale,
		curipa->counter,
		curipa->device);
	curipa = curipa->nextitem;
   }
   close(acqifile);

}


text:
package voogasalad_GucciGames.helpers;

import java.util.HashMap;
import java.util.Map;

import javafx.scene.image.Image;
import javafx.scene.image.PixelReader;
import javafx.scene.paint.Color;

public class ImageAverager implements ResourceDatabase<Color> {

	private Map<String, Color> myImageMap;
	private ResourceManager myManager;

	public ImageAverager(ResourceManager resourceManager) {
		myManager = resourceManager;
		myImageMap = new HashMap<>();
	}

	@Override
	public Color request(String URI) {
		if (!myImageMap.containsKey(URI)) {
			myImageMap.put(URI, average(URI));
		}
		return myImageMap.get(URI);
	}

	private Color average(String URI) {
		Image source = myManager.getImage(URI);
		PixelReader reader = source.getPixelReader();
		double red = 0, green = 0, blue = 0;
		double count = 1;
		for (int x = 0; x < source.getWidth(); x++) {
			for (int y = 0; y < source.getHeight(); y++) {
				Color currentColor = reader.getColor(x, y);
				red = (red * count + currentColor.getRed()) / (count + 1);
				blue = (blue * count + currentColor.getBlue()) / (count + 1);
				green = (green * count + currentColor.getGreen()) / (count + 1);
				count++;
			}
		}
		return new Color(red, green, blue, 1.0);
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Overview (HttpComponents Client 4.1.3 API)
</TITLE>

<META NAME="keywords" CONTENT="Overview, HttpComponents Client 4.1.3 API">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

Packages

org.apache.http.annotation

org.apache.http.auth

org.apache.http.auth.params

org.apache.http.client

org.apache.http.client.cache

org.apache.http.client.entity

org.apache.http.client.methods

org.apache.http.client.params

org.apache.http.client.protocol

org.apache.http.client.utils

org.apache.http.conn

org.apache.http.conn.params

org.apache.http.conn.routing

org.apache.http.conn.scheme

org.apache.http.conn.ssl

org.apache.http.conn.util

org.apache.http.cookie

org.apache.http.cookie.params

org.apache.http.entity.mime

org.apache.http.entity.mime.content

org.apache.http.impl.auth

org.apache.http.impl.client

org.apache.http.impl.client.cache

org.apache.http.impl.client.cache.ehcache

org.apache.http.impl.client.cache.memcached

org.apache.http.impl.conn

org.apache.http.impl.conn.tsccm

org.apache.http.impl.cookie


text:
adminMenu.push({
  route: 'upload',
  label: 'Upload',
  description: '' // optional
});

// ------------------------------------------------------------------------------------------- //
// ------------------------------------------ Zones ------------------------------------------ //
// ------------------------------------------------------------------------------------------- //

// add templates to the hero zone (before posts list)
//heroModules.push({
//  template: 'customHero',
//  order: 99
//});

// add templates to the footer (after posts list)
//footerModules.push({
//  template: 'customFooter',
//  order: 99
//});

// ------------------------------------------------------------------------------------------- //
// ------------------------------------------ Posts ------------------------------------------ //
// ------------------------------------------------------------------------------------------- //

// add templates to the post items
//postModules.push({
//  template: 'customModule',
//  order: 99
//});

// add templates to the post heading zone
//postHeading.push({
//  template: 'customHeading',
//  order: 99
//});

// add templates to the post meta zone
//postMeta.push({
//  template: 'customMeta',
//  order: 99
//});

// ------------------------------------------------------------------------------------------- //
// -------------------------------------- User Profiles -------------------------------------- //
// ------------------------------------------------------------------------------------------- //

//userProfileDisplay.push({
//  template: 'customTemplate',
//  order: 99
//});

//userProfileEdit.push({
//  template: 'customTemplate',
//  order: 99
//});