text:
namespace edb
{

class ReverseAnimation : public ICommand
{
public:
	ReverseAnimation() {}

	//
	// interface ICommand
	//
	virtual std::string Command() const override;
	virtual std::string Description() const override;
	virtual std::string Usage() const override;
	virtual int Run(int argc, char *argv[]) override;

	static ICommand* Create() { return new ReverseAnimation(); }

private:
	void Trigger(const std::string& dir) const;

}; // ReverseAnimation

}

#endif // _EASYDB_REVERSE_ANIMATION_H_


text:
using System;
using System.Collections.Generic;
using System.IO;
using Xunit;

namespace DlibDotNet.Tests.ImageProcessing
{

    public class FrontalFaceDetectorTest : TestBase
    {

        private FrontalFaceDetector _FrontalFaceDetector;

        public FrontalFaceDetectorTest()
        {
            this._FrontalFaceDetector = Dlib.GetFrontalFaceDetector();
        }

        [Fact]
        public void DetectFace()
        {
            if (this._FrontalFaceDetector == null)
                Assert.True(false, "ShapePredictor is not initialized!!");

            var faceDetector = this._FrontalFaceDetector;

            var path = this.GetDataFile("2008_001322.jpg");
            var image = Dlib.LoadImage<RgbPixel>(path.FullName);

            //Interpolation.PyramidUp(image);

            var dets = faceDetector.Operator(image);
            Assert.Equal(dets.Length, 3);

            foreach (var r in dets)
                Dlib.DrawRectangle(image, r, new RgbPixel { Green = 255 });

            Dlib.SaveBmp(image, Path.Combine(this.GetOutDir(this.GetType().Name), "DetectFace.bmp"));

            this.DisposeAndCheckDisposedState(faceDetector);
            this.DisposeAndCheckDisposedState(image);
        }

        [Fact]
        public void DetectFace2()
        {
            if (this._FrontalFaceDetector == null)
                Assert.True(false, "ShapePredictor is not initialized!!");

            var faceDetector = this._FrontalFaceDetector;

            const string testName = "DetectFace2";
            var path = this.GetDataFile("Lenna_mini.bmp");

            var tests = new[]
            {
                new { Type = ImageTypes.BgrPixel,      ExpectResult = true},
                new { Type = ImageTypes.RgbPixel,      ExpectResult = true},
                new { Type = ImageTypes.UInt8,         ExpectResult = true},
                new { Type = ImageTypes.UInt16,        ExpectResult = true},
                new { Type = ImageTypes.UInt32,        ExpectResult = true},
                new { Type = ImageTypes.Int8,          ExpectResult = true},
                new { Type = ImageTypes.Int16,         ExpectResult = true},
                new { Type = ImageTypes.Int32,         ExpectResult = true},
                new { Type = ImageTypes.HsiPixel,      ExpectResult = true},
                new { Type = ImageTypes.LabPixel,      ExpectResult = true},
                new { Type = ImageTypes.Float,         ExpectResult = true},
                new { Type = ImageTypes.Double,        ExpectResult = true},
                new { Type = ImageTypes.RgbAlphaPixel, ExpectResult = false}
            };

            foreach (var input in tests)
            {
                var expectResult = input.ExpectResult;
                var imageObj = DlibTest.LoadImageHelp(input.Type, path);
                Rectangle[] dets = null;

                var outputImageAction = new Func<bool, Rectangle[]>(expect =>
                {
                    dets = faceDetector.Operator(imageObj);
                    return dets;
                });

                var successAction = new Action<Rectangle[]>(image =>
                {
                    // This test does NOT check whether output image and detect face area are correct
                    //Dlib.SaveJpeg(image, $"{Path.Combine(this.GetOutDir(type, testName), $"2008_001322_{input.Type}.jpg")}");
                });

                var failAction = new Action(() =>
                {
                    Assert.True(false, $"{testName} should throw exception for InputType: {input.Type}.");
                });

                var finallyAction = new Action(() =>
                {
                    this.DisposeAndCheckDisposedState(imageObj);
                });

                var exceptionAction = new Action(() =>
                {
                    Console.WriteLine($"Failed to execute {testName} to InputType: {input.Type}.");
                });

                DoTest(outputImageAction, expectResult, successAction, finallyAction, failAction, exceptionAction);
            }
        }

        [Fact]
        public void DetectFace3()
        {
            if (this._FrontalFaceDetector == null)
                Assert.True(false, "ShapePredictor is not initialized!!");

            var faceDetector = this._FrontalFaceDetector;

            const string testName = "DetectFace3";
            var path = this.GetDataFile("Lenna_mini.bmp");

            var tests = new[]
            {
                new { Type = MatrixElementTypes.RgbPixel,      ExpectResult = true},
                new { Type = MatrixElementTypes.UInt8,         ExpectResult = true},
                new { Type = MatrixElementTypes.UInt16,        ExpectResult = true},
                new { Type = MatrixElementTypes.UInt32,        ExpectResult = true},
                new { Type = MatrixElementTypes.Int8,          ExpectResult = true},
                new { Type = MatrixElementTypes.Int16,         ExpectResult = true},
                new { Type = MatrixElementTypes.Int32,         ExpectResult = true},
                new { Type = MatrixElementTypes.HsiPixel,      ExpectResult = true},
                new { Type = MatrixElementTypes.LabPixel,      ExpectResult = true},
                new { Type = MatrixElementTypes.Float,         ExpectResult = true},
                new { Type = MatrixElementTypes.Double,        ExpectResult = true},
                new { Type = MatrixElementTypes.RgbAlphaPixel, ExpectResult = false}
            };

            foreach (var input in tests)
            {
                var expectResult = input.ExpectResult;
                var imageObj = DlibTest.LoadImageAsMatrixHelp(input.Type, path);
                Rectangle[] dets = null;

                var outputImageAction = new Func<bool, Rectangle[]>(expect =>
                {
                    dets = faceDetector.Operator(imageObj);
                    return dets;
                });

                var successAction = new Action<Rectangle[]>(image =>
                {
                    // This test does NOT check whether output image and detect face area are correct
                    //Dlib.SaveJpeg(image, $"{Path.Combine(this.GetOutDir(type, testName), $"2008_001322_{input.Type}.jpg")}");
                });

                var failAction = new Action(() =>
                {
                    Assert.True(false, $"{testName} should throw exception for InputType: {input.Type}.");
                });

                var finallyAction = new Action(() =>
                {
                    this.DisposeAndCheckDisposedState(imageObj);
                });

                var exceptionAction = new Action(() =>
                {
                    Console.WriteLine($"Failed to execute {testName} to InputType: {input.Type}.");
                });

                DoTest(outputImageAction, expectResult, successAction, finallyAction, failAction, exceptionAction);
            }
        }

        [Fact]
        public void DetectFaceRectDetection()
        {
            if (this._FrontalFaceDetector == null)
                Assert.True(false, "ShapePredictor is not initialized!!");

            var faceDetector = this._FrontalFaceDetector;

            const string testName = nameof(DetectFaceRectDetection);
            var path = this.GetDataFile("Lenna.bmp");

            var tests = new[]
            {
                new { Type = MatrixElementTypes.RgbPixel,      ExpectResult = true},
                new { Type = MatrixElementTypes.UInt8,         ExpectResult = true},
                new { Type = MatrixElementTypes.UInt16,        ExpectResult = true},
                new { Type = MatrixElementTypes.UInt32,        ExpectResult = true},
                new { Type = MatrixElementTypes.Int8,          ExpectResult = true},
                new { Type = MatrixElementTypes.Int16,         ExpectResult = true},
                new { Type = MatrixElementTypes.Int32,         ExpectResult = true},
                new { Type = MatrixElementTypes.HsiPixel,      ExpectResult = true},
                new { Type = MatrixElementTypes.LabPixel,      ExpectResult = true},
                new { Type = MatrixElementTypes.Float,         ExpectResult = true},
                new { Type = MatrixElementTypes.Double,        ExpectResult = true},
                new { Type = MatrixElementTypes.RgbAlphaPixel, ExpectResult = false}
            };

            foreach (var input in tests)
            {
                var expectResult = input.ExpectResult;
                var imageObj = DlibTest.LoadImageAsMatrixHelp(input.Type, path);
                IEnumerable<RectDetection> result = null;

                var outputImageAction = new Func<bool, IEnumerable<RectDetection>>(expect =>
                {
                    faceDetector.Operator(imageObj, out var detections);
                    result = detections;
                    return detections;
                });

                var successAction = new Action<IEnumerable<RectDetection>>(detections =>
                {
                    // This test does NOT check whether output image and detect face area are correct
                    //Dlib.SaveJpeg(image, $"{Path.Combine(this.GetOutDir(type, testName), $"2008_001322_{input.Type}.jpg")}");
                    Console.WriteLine($"{input.Type}");
                    foreach (var d in detections)
                    {
                        var rect = d.Rect;
                        Console.WriteLine($"\tDetectionConfidence: {d.DetectionConfidence}, WeightIndex: {d.WeightIndex}, Rect: \n\t\tLeft: {rect.Left}, Top: {rect.Top}, Right: {rect.Right}, Bottom: {rect.Bottom}");
                    }
                });

                var failAction = new Action(() =>
                {
                    Assert.True(false, $"{testName} should throw exception for InputType: {input.Type}.");
                });

                var finallyAction = new Action(() =>
                {
                    this.DisposeAndCheckDisposedState(imageObj);
                    if (result != null)
                        this.DisposeAndCheckDisposedStates(result);
                });

                var exceptionAction = new Action(() =>
                {
                    Console.WriteLine($"Failed to execute {testName} to InputType: {input.Type}.");
                });

                DoTest(outputImageAction, expectResult, successAction, finallyAction, failAction, exceptionAction);
            }
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace WakeboardUK2018.Models
{
    public class Media
    {
        public int MediaId { get; set; }
        [Required]
        public string Title { get; set; }
        [Required]
        public string Uri { get; set; }
        public string Photographer { get; set; }
        public ICollection<MediaCompetitor> MediaCompetitors { get; set; }
        public int MediaTypeId { get; set; }
        public MediaType MediaType { get; set; }
    }

    public class MediaCompetitor
    {
        public int MediaId { get; set; }
        public Media Media { get; set; }
        public int CompetitorId { get; set; }
        public Competitor Competitor { get; set; }
    }
}


text:
package com.be55.android.ferecauth;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;

public class ConfigActivity extends PreferenceActivity {
	private Intent authServiceIntent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.prefs);

		CheckBoxPreference exec_autoauth = (CheckBoxPreference) findPreference("exec_autoauth");

		authServiceIntent = new Intent(getApplicationContext(),
				FerecAuthService.class);

		exec_autoauth
				.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {

						if (((Boolean) newValue).booleanValue()) {
							// Start service
							startService(authServiceIntent);
						} else {
							// Stop service
							stopService(authServiceIntent);
						}

						return true;
					}
				});
	}

	@Override
	protected void onResume() {
		super.onResume();

		getPreferenceScreen().getSharedPreferences()
				.registerOnSharedPreferenceChangeListener(listener);
	}

	@Override
	protected void onPause() {
		super.onPause();
		getPreferenceScreen().getSharedPreferences()
				.unregisterOnSharedPreferenceChangeListener(listener);
	}

	private SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
		public void onSharedPreferenceChanged(
				SharedPreferences sharedPreferences, String key) {

			if (!key.equals("exec_autoauth")) {
				if (sharedPreferences.getBoolean("exec_autoauth", false)) {
					// Restart service
					stopService(authServiceIntent);
					startService(authServiceIntent);
				}
			}
		}
	};
}


text:
BEGIN_INANITY_AUDIO

class AlDevice;

/// Base OpenAL player class.
class AlPlayer : public Player3D
{
protected:
	ptr<AlDevice> device;
	ALuint sourceName;

public:
	AlPlayer(ptr<AlDevice> device);
	~AlPlayer();

	//** Player's methods.
	void SetVolume(float volume);
	void SetPanning(float pan);
	void SetPitch(float pitch);

	//** Player3D's methods
	void SetPosition(const Math::vec3& position);
	void SetDirection(const Math::vec3& direction);
	void SetVelocity(const Math::vec3& velocity);
};

END_INANITY_AUDIO

#endif


text:
<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>

	<artifactId>sfm-map</artifactId>
  <version>8.2.4-SNAPSHOT</version>
	<packaging>bundle</packaging>

	<parent>
		<groupId>org.simpleflatmapper</groupId>
		<artifactId>sfm-parent</artifactId>
		<version>8.2.4-SNAPSHOT</version>
	</parent>

	<name>sfm-map</name>
	<description>Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.</description>

	<developers>
		<developer>
			<id>arnaudroger</id>
			<name>Arnaud Roger</name>
			<email>arnaud.roger@gmail.com</email>
		</developer>
	</developers>

	<licenses>
		<license>
			<name>The MIT License (MIT)</name>
			<url>http://opensource.org/licenses/MIT</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<dependencies>
		<dependency>
			<groupId>org.simpleflatmapper</groupId>
			<artifactId>sfm-reflect</artifactId>
			<version>8.2.4-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.simpleflatmapper</groupId>
			<artifactId>sfm-test</artifactId>
			<version>8.2.4-SNAPSHOT</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.simpleflatmapper</groupId>
			<artifactId>sfm-tuples</artifactId>
			<version>8.2.4-SNAPSHOT</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.simpleflatmapper</groupId>
			<artifactId>sfm-converter-joda-time</artifactId>
			<version>8.2.4-SNAPSHOT</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.eclipse.collections</groupId>
			<artifactId>eclipse-collections</artifactId>
			<version>7.1.2</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>18.0</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Export-Package>
                            org.simpleflatmapper.map,
                            org.simpleflatmapper.map.property,
                            org.simpleflatmapper.map.property.joda,
                            org.simpleflatmapper.map.property.time,
                            org.simpleflatmapper.map.context,
                            org.simpleflatmapper.map.error,
                            org.simpleflatmapper.map.fieldmapper,
                            org.simpleflatmapper.map.mapper,
                            org.simpleflatmapper.map.setter,
                            org.simpleflatmapper.map.getter
                        </Export-Package>
						<Import-Package>
							org.simpleflatmapper.ow2asm.*,
							org.simpleflatmapper.reflect.*,
							org.simpleflatmapper.tuple;resolution:=optional,
							org.simpleflatmapper.util.*,
							org.simpleflatmapper.converter.*
						</Import-Package>
					</instructions>
					<archive>
						<manifestEntries>
							<Automatic-Module-Name>org.simpleflatmapper.map</Automatic-Module-Name>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.4</version>
				<executions>
					<execution>
						<goals>
							<goal>test-jar</goal>
						</goals>
						<configuration>
							<archive>
								<manifestEntries>
									<Automatic-Module-Name>org.simpleflatmapper.map.test</Automatic-Module-Name>
								</manifestEntries>
							</archive>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.pitest</groupId>
				<artifactId>pitest-maven</artifactId>
				<version>1.1.9</version>
				<configuration>
					<targetClasses>
						<param>org.simpleflatmapper.*</param>
					</targetClasses>
					<targetTests>
						<param>org.simpleflatmapper.*</param>
					</targetTests>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<profiles>
		<profile>
			<id>travis</id>
			<activation>
				<property>
					<name>env.TRAVIS</name>
					<value>true</value>
				</property>
			</activation>
			<build>
				<plugins>
					<plugin>
						<groupId>org.jacoco</groupId>
						<artifactId>jacoco-maven-plugin</artifactId>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<id>jdk16</id>
			<activation>
				<jdk>1.6</jdk>
			</activation>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-compiler-plugin</artifactId>
					</plugin>
					<plugin>
						<groupId>com.google.code.maven-replacer-plugin</groupId>
						<artifactId>replacer</artifactId>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<id>jdk17</id>
			<activation>
				<jdk>1.7</jdk>
			</activation>
			<dependencies>
				<dependency>
					<groupId>com.boundary</groupId>
					<artifactId>fasttuple-core</artifactId>
					<version>0.1</version>
					<optional>true</optional>
					<scope>test</scope>
				</dependency>
			</dependencies>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-compiler-plugin</artifactId>
					</plugin>
					<plugin>
						<groupId>com.google.code.maven-replacer-plugin</groupId>
						<artifactId>replacer</artifactId>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<id>jdk18</id>
			<activation>
				<jdk>1.8</jdk>
			</activation>

			<dependencies>
				<dependency>
					<groupId>org.jooq</groupId>
					<artifactId>jool</artifactId>
					<version>0.9.12</version>
					<optional>true</optional>
					<scope>test</scope>
				</dependency>
				<dependency>
					<groupId>com.boundary</groupId>
					<artifactId>fasttuple-core</artifactId>
					<version>0.1</version>
					<optional>true</optional>
					<scope>test</scope>
				</dependency>
			</dependencies>
		</profile>

		<profile>
			<id>jdk19</id>
			<activation>
				<jdk>[9,12]</jdk>
			</activation>
			<dependencies>
				<dependency>
					<groupId>org.jooq</groupId>
					<artifactId>jool</artifactId>
					<version>0.9.12</version>
					<optional>true</optional>
					<scope>test</scope>
				</dependency>
				<dependency>
					<groupId>com.boundary</groupId>
					<artifactId>fasttuple-core</artifactId>
					<version>0.1</version>
					<optional>true</optional>
					<scope>test</scope>
				</dependency>
			</dependencies>

			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-surefire-plugin</artifactId>
						<configuration>
							<argLine>--add-opens java.base/java.lang=ALL-UNNAMED --add-exports=org.simpleflatmapper.map/org.simpleflatmapper.test.map.issue=org.simpleflatmapper.reflect --add-exports=org.simpleflatmapper.map/org.simpleflatmapper.test.map.mapper=org.simpleflatmapper.reflect --add-exports=org.simpleflatmapper.map/org.simpleflatmapper.test.map.impl=org.simpleflatmapper.reflect</argLine>
						</configuration>
					</plugin>
				</plugins>

			</build>
		</profile>

	</profiles>
</project>


text:
package org.lantern.state;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;

import java.io.File;

import org.apache.commons.lang.SystemUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.lantern.CountryService;
import org.lantern.TestUtils;
import org.lantern.TestingUtils;
import org.lantern.privacy.LocalCipherProvider;

import com.google.common.io.Files;

public class ModelIoTest {

    private static File testFile;

    @BeforeClass
    public static void setup() throws Exception {
        testFile = new File(Files.createTempDir(), "modelTest");
        testFile.delete();
        testFile.deleteOnExit();
    }

    @Test
    public void testModelIo() throws Exception {
        final File dir = testFile.getParentFile();
        if (!dir.exists()) {
            assertTrue("Could not make temp directory!", dir.mkdirs());
        }
        assertTrue("Can't write to test directory!", dir.canWrite());
        CountryService countryService = TestUtils.getCountryService();
        ModelIo io = new ModelIo(testFile, TestUtils.getEncryptedFileService(),
                countryService, TestingUtils.newCommandLine(),
                mock(LocalCipherProvider.class));

        Model model = io.get();

        final String id = model.getNodeId();
        SystemData system = model.getSystem();
        Connectivity connectivity = model.getConnectivity();
        assertEquals("", connectivity.getIp());

        if ("en".equalsIgnoreCase(SystemUtils.USER_LANGUAGE)) {
            assertEquals("en", system.getLang());
        }

        final String testId = "test-client-id";
        final Settings set = model.getSettings();
        final String existingId = set.getClientID();
        assertNotEquals("IDs should not be equal", testId, existingId);
        set.setClientID(testId);
        io.write();

        io = new ModelIo(testFile, TestUtils.getEncryptedFileService(),
                countryService, TestingUtils.newCommandLine(),
                mock(LocalCipherProvider.class));
        final Model model2 = io.get();
        system = model2.getSystem();
        connectivity = model2.getConnectivity();
        final String tok = model2.getSettings().getClientID();
        assertEquals(testId, tok);

        // The user's IP address should not persist to disk
        assertEquals("", connectivity.getIp());

        assertEquals("ID should persist across sessions",
            id, model.getNodeId());

    }

}


text:
package mx.org.cedn.avisosconagua.engine.processors;

import com.mongodb.BasicDBObject;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mx.org.cedn.avisosconagua.engine.Processor;
import mx.org.cedn.avisosconagua.mongo.CAPFileGenerator;
import mx.org.cedn.avisosconagua.mongo.MongoInterface;
import mx.org.cedn.avisosconagua.util.Utils;

/**
 * Workflow processor to generate the CAP XML for the generated advice.
 * @author serch
 */
public class Generate implements Processor {
    private static final String ADVICE_ID = "internalId";

    @Override
    public void invokeForm(HttpServletRequest request, HttpServletResponse response, BasicDBObject data, String[] parts) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String adviceID = (String)request.getSession(true).getAttribute(ADVICE_ID);
        CAPFileGenerator capFile = new CAPFileGenerator(adviceID);
        capFile.generate();
        if (capFile.isOK()){
            request.setAttribute("capURL", capFile.getLink());
        }
// MAPS74 - no html generation
//        HtmlZipGenerator htmlFile = new HtmlZipGenerator(adviceID);
//        htmlFile.generate();
//        if (htmlFile.isOK()){
//            request.setAttribute("htmlUrl",htmlFile.getLink());
//        }
        BasicDBObject aviso = MongoInterface.getInstance().getAdvice(adviceID);
        BasicDBObject init = (BasicDBObject) aviso.get("init");
        BasicDBObject capInfo = (BasicDBObject) aviso.get("capInfo");
        BasicDBObject precapture = (BasicDBObject) aviso.get("precapture");
        String previous = precapture!=null?precapture.getString("previousIssue"):null;
        String titulo = Utils.getTituloBoletinHtml(aviso.getString(MongoInterface.ADVICE_TYPE), init.getString("eventCoastDistance"));
        String title = capInfo.getString("issueDate")+" "+capInfo.getString("issueTime")+ " - " + capInfo.getString("issueNumber")   + " "+titulo;
        //
        request.setAttribute("titulo", Utils.getTituloBoletin(parts[2]));
        MongoInterface.getInstance().setGenerated(adviceID,previous,title, parts[2], capFile.getDate());
        request.setAttribute("isdp", parts[2].endsWith("dp"));
        request.setAttribute("bulletinType", parts[2]);
        request.setAttribute("hasAreas", Utils.canIHasAreaz(aviso));
        RequestDispatcher rd = request.getRequestDispatcher("/jsp/finish.jsp");
        rd.forward(request, response);
    }

    @Override
    public void processForm(HttpServletRequest request, String[] parts, String currentId) throws ServletException, IOException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}


text:
<?php

declare(strict_types=1);

namespace Sonata\Component\Form\Transformer;

use Symfony\Component\Form\DataTransformerInterface;

/**
 * @author Vincent Composieux <vincent.composieux@gmail.com>
 */
class SerializeDataTransformer implements DataTransformerInterface
{
    public function transform($value)
    {
        return serialize($value);
    }

    public function reverseTransform($value)
    {
        if (!$value) {
            return [];
        }

        return unserialize($value);
    }
}


text:
[![Views in the last 24 hours](https://sourcegraph.com/api/repos/github.com/OpenROV/openrov-software/counters/views-24h.png)](https://sourcegraph.com/github.com/OpenROV/openrov-software)
[![Build Status](https://secure.travis-ci.org/OpenROV/openrov-software.png?branch=master)](http://travis-ci.org/OpenROV/openrov-software)
[![Code Climate](https://codeclimate.com/github/OpenROV/openrov-software.png)](https://codeclimate.com/github/OpenROV/openrov-software)
[![Coverage Status](https://coveralls.io/repos/OpenROV/openrov-software/badge.png)](https://coveralls.io/r/OpenROV/openrov-software)
[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/OpenROV/openrov-software/badges/quality-score.png?s=c24130cbf17aaa23f2680e3b45a0ec675ef2037f)](https://scrutinizer-ci.com/g/OpenROV/openrov-software/)
[![Code Coverage](https://scrutinizer-ci.com/g/OpenROV/openrov-software/badges/coverage.png?s=e356e3047940fb7ea47e36477c6064e23fee12c0)](https://scrutinizer-ci.com/g/OpenROV/openrov-software/)

OpenROV Cockpit
================

"[OpenROV](http://openrov.com/) is a DIY telerobotics community centered around underwater exploration & adventure."  One goal of OpenROV is to have onboard video for live viewing as the user operates the ROV.  Enter: OpenROV Cockpit.

Getting started
---------------

**If you just getting started and want to have working environment for the OpenROV Cockpit, we recommend that you start with using our last stable release from our [releases page](https://github.com/OpenROV/openrov-software/releases).  If you want to explore building your own image from scratch, refer to our
[OpenROV disk Image](https://github.com/OpenROV/openrov-image/blob/master/README.md) project.  The latest development image (from master) can be downloaded from http://54.187.8.25:8080/job/OpenROV-Image_BuildImage_master/.

Introduction
------------

We designed the onboard video platform using several key technologies:

- [MJPEG_Streamer](https://code.google.com/p/mjpg-streamer/)
- [Node.js](http://nodejs.org/)
- [Socket.io](http://socket.io/)

Combining these great technologies provides a lot of power and room for future growth.  But is also provides well documented means to extend OpenROV.  With Node.js and Socket.io, not only are we able to stream video to a web browser by updating an image, but we are also able to control the ROV and view valuable sensor information.  This is just the beginning.

Key Related Projects
----------------

* The firmware for the arduino can be found in [openrov/openrov-software-arduino](https://github.com/OpenROV/openrov-software-arduino) in the /OpenROV project.
* The dashboard project can be found in [openrov/openrov-dashboard](https://github.com/OpenROV/openrov-dashboard)

Note on Repository Branches
---------------------------

The "master" branch is the most current development branch of the code.  All work is done outside and submited as pull requests that *should* be working before they are merged.  There will also be a `<release>`-maintanence branch that has the code from the last stable release.  There may also be a `<release>`-alpha|beta|rc1 which is the next release that is being stabalized.  This will more than likely change as committers come and go, but that it what it looks like today.

Requirements
------------
- BeagleBone: [http://beagleboard.org/bone](http://beagleboard.org/bone)
- USB webcam:  we're using the Genius F100 HD
- Ubuntu for BeagleBone:  [http://elinux.org/BeagleBoardUbuntu#Demo_Image](http://elinux.org/BeagleBoardUbuntu#Demo_Image) or [https://github.com/codewithpassion/openrov-image](https://github.com/codewithpassion/openrov-image)
- mjpg-streamer:  [http://sourceforge.net/projects/mjpg-streamer/](http://sourceforge.net/projects/mjpg-streamer/)
- Node.js :  [http://nodejs.org/](http://nodejs.org/)
- Socket.io:  [http://socket.io/](http://socket.io/)

Installation
------------

Step 1
------

Follow the instructions from our image project to get a starting image: https://github.com/OpenROV/openrov-image.  The default user is *rov* and password is *OpenROV*

Step 2
------

Go ahead and start up the image in the beaglebone.  If you connect the rov to a router it will use DHCP to get an address. You many need to login to your router and examine the dhcp logs to figure out what IP was assigned.  If you connect directly to a laptop, a static IP of 192.168.254.1 is used.
Go ahead and SSH on to you rov

a) ssh rov@<address of rov>

Step 3
------

Customize the name of the image to match your rov#.

Change from "openrov" (without quotes) to "openrov-XXXX" (without quotes) - where XXXX is your serial number.

    vi /etc/hosts
    exit

Step 4
------

Upload the right firmware on to the arduino that is driving the motors and sensors.  The source code for the arduino is actually installed in the git repo on the beaglebone. The beaglebone has a full arduino development environment and the ability to upload the firmware to the arduino.

Since there are multiple versions of the ROV with multiple possible configurations you have to first tailor the options for the firmware to match your ROV.  It defaults to the stock installation for the *current* shipping ROV kit.

a) from the ssh session: sudo pico /opt/openrov/arduino/OpenROV/Aconfig.h

b) put a 1 for the options you have, a 0 if you don't have the option and save. For most folks you don't need to do anything because the type of board will be automatically detected. In case you could

c) Login to the web session for the rov, choose settings, and select the upload firmware to arduino option.

Updating
------------
NOTE: This is changing and may not be working properly.
The easiest way to upgrade your installation is to ssh on to

1) ssh on to your rov

2) cd /opt/openrov/cockpit

3) sudo ./update.sh

This will go to the github repository and pull the latest code. You may need to reboot after the update.  There is a known issue where the serial.io project sometimes fails to compile.  You can ignore that, but you may have to try again if it aborts the update.

Plugins
------------
You can create your own plugins and share them with the community. Take a look at our [openrov-grunt-init-plugin](https://github.com/openrov/openrov-grunt-init-plugin) project.

How to Contribute
------------

Contributions require that you sign a [CLA](http://wiki.openrov.com/index.php/Special:SignDocument?doc=9) before the project can accept your pull requests.

1) Fork the project in github

2) Add an issue to the issue list for the changes you want to make.  Browser the issues lists for many of the fixes and enhancement requests if your looking for ideas.

3) Make your changes and or fixes.

4) Test them locally on your ROV or using the mock framework for node if you don't have one.

5) Send a pull request back to the Master repository.

More details can be found on the [OpenROV Wiki](http://wiki.openrov.com/index.php/Contributing).

Someone on the team will review the pull request and ensure the changes work on the ROVs before approving the pull request.

License
-------

MIT License

Copyright (C) 2013 OpenROV Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
package com.elytradev.teckle.common.worldnetwork.item;

import com.elytradev.teckle.api.IWorldNetwork;
import com.elytradev.teckle.common.worldnetwork.common.WorldNetworkTraveller;
import com.elytradev.teckle.common.worldnetwork.common.node.WorldNetworkEndpoint;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;

public class ItemNetworkEndpoint extends WorldNetworkEndpoint {

    public ItemNetworkEndpoint(IWorldNetwork network, BlockPos pos, EnumFacing capabilityFace) {
        super(network, pos, capabilityFace);
    }

    @Override
    public boolean inject(WorldNetworkTraveller traveller, EnumFacing from) {
        TileEntity endPointTile = getNetwork().getWorld().getTileEntity(getPosition());

        if (endPointTile != null) {
            if (endPointTile.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, from)) {
                IItemHandler itemHandler = endPointTile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, from);

                ItemStack dataStack = new ItemStack(traveller.data.getCompoundTag("stack")).copy();
                for (int slot = 0; slot < itemHandler.getSlots(); slot++) {
                    dataStack = itemHandler.insertItem(slot, dataStack, false);

                    if (dataStack.isEmpty())
                        break;
                }

                if (!dataStack.isEmpty())
                    traveller.data.setTag("stack", dataStack.writeToNBT(new NBTTagCompound()));

                return dataStack.isEmpty();
            }
        }

        return false;
    }

    private boolean canInject(WorldNetworkTraveller traveller, EnumFacing from) {
        TileEntity endPointTile = getNetwork().getWorld().getTileEntity(getPosition());

        if (endPointTile != null) {
            if (endPointTile.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, from)) {
                IItemHandler itemHandler = endPointTile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, from);

                ItemStack dataStack = new ItemStack(traveller.data.getCompoundTag("stack"));
                ItemStack initialStack = dataStack.copy();
                for (int slot = 0; slot < itemHandler.getSlots(); slot++) {
                    dataStack = itemHandler.insertItem(slot, dataStack, true);

                    if (dataStack.isEmpty() || dataStack.getCount() != initialStack.getCount())
                        return true;
                }
            }
        }

        return false;
    }

    @Override
    public boolean canAcceptTraveller(WorldNetworkTraveller traveller, EnumFacing from) {
        return super.canAcceptTraveller(traveller, from) && canInject(traveller, from);
    }

}


text:
__author__ = 'RMGiroux'

debug_mode = 0

import asyncio
from asyncio import subprocess
from datetime import datetime, timedelta
import sys

import re

from pylibinit import addlibpath

addlibpath.add_lib_path()

from blessings import Terminal
from tqdm import format_meter

term = Terminal()

class OutputCollector:
    def __init__(self, name):
        self.name = name

    @asyncio.coroutine
    def process_line(self, stream):
        while not stream.at_eof():
            line = yield from stream.readline()
            print("%s: %s" % (self.name, line))

@asyncio.coroutine
def read_stdout(stream, callback):
    while True:
        line = yield from stream.readline()

        if not line:
            break
        else:
            callback(line)

@asyncio.coroutine
def async_exec(command, stdoutCallback):
    fork = yield from asyncio.create_subprocess_shell((command),
                                                      stdout=subprocess.PIPE,
                                                      stderr=subprocess.STDOUT)

    tasks = []
    if fork.stdout is not None:
        tasks.append(read_stdout(fork.stdout, stdoutCallback))
    else:
        print('No stdout')

    yield from asyncio.wait(tasks)

    retCode = yield from fork.wait()

    return retCode

def run_waf(directory, ufid, target=None):
    prefix = "%s/_build/%s" % (directory, ufid)
    waflock = ".waf-lock-%s" % ufid
    build_dir = "_build/%s" % (ufid)

    environment = (
        "export PREFIX=%s WAFLOCK=%s BDE_WAF_UFID=%s BDE_WAF_BUILD_DIR=%s" % (
            prefix, waflock, ufid, build_dir))

    waf_command = "waf configure clean build --test=run -j6 -k"

    if target is not None:
        waf_command += (" --target=%s" % target)

    command = "%s; cd %s; %s 2>&1 | tee %s.out " % (
        environment, directory, waf_command, ufid)

    # with term.location(1, 30 + (position * 5)):
    #    print("Starting command %s"%command)

    line_proc = LineProcessor(ufid, "uplid-placeholder")

    task = async_exec(command, lambda x: line_proc.line_callback(x))

    return task

progress_regex_string = b"\[\s*(\d+)/\s*(\d+)\s*\] \w+\s+(.*)"
progress_regex = re.compile(progress_regex_string)

test_summary = b"Test Summary"
test_summary_regex = re.compile(test_summary)

test_pass = b"All tests passed."
test_pass_regex = re.compile(test_pass)

test_fail = b"tests have fail"
test_fail_regex = re.compile(test_fail)

class LineProcessor:
    position = 1

    block_start_pattern_string = b"\\[(\\S+) \\((WARNING|ERROR|TEST)\\)\\] <<<<<<<<<<"
    block_end_pattern_string = b">>>>>>>>>>"
    block_pattern_string = block_start_pattern_string + b"(.*?)" + block_end_pattern_string

    block_start_pattern = re.compile(block_start_pattern_string)
    # re.S is aka re.DOTALL, so "." matches newlines as well.
    block_pattern = re.compile(block_pattern_string, re.S)
    block_end_pattern = re.compile(block_end_pattern_string)

    def __init__(self, ufid, uplid):
        self.ufid = ufid
        self.uplid = uplid
        self.position = LineProcessor.position
        self.start_time = datetime.now()

        LineProcessor.position = LineProcessor.position + 1

        self.diagnostic_buffer = ""
        self.processing_diag   = False

    def line_callback(self, line):
        line = line.rstrip()

        if debug_mode:
            with term.location(1, 30 + self.position * 2):
                print(" " * 80)
            with term.location(1, 30 + self.position * 2):
                print("%-20s: %-50s" % (self.ufid, line.decode("ascii")[-50:]))

        match = progress_regex.search(line)
        if match is not None:
            with term.location(1, self.position * 2):
                print(format_meter(int(match.group(1)), int(match.group(2)),
                                   (datetime.now() - self.start_time).total_seconds(),
                                   ascii=True, prefix=("%-20s" % self.ufid)))
            with term.location(5, self.position * 2 + 1):
                print("%60s" % match.group(3).decode("ascii")[-60:])

            return  # RETURN

        if self.processing_diag:
            match = LineProcessor.block_end_pattern.search(line)
            if match is not None:
                self.diagnostic_buffer+=line
                # TODO: Hand off diagnostic to database
                with term.location(1, 50):
                    print(" " * 80)
                with term.location(1, 50):
                    print(self.diagnostic_buffer[0:60])

                self.processing_diag = False
                return

            self.diagnostic_buffer+=line
            return

        match = LineProcessor.block_start_pattern.search(line)
        if match is not None:
            self.processing_diag = True
            self.diagnostic_buffer = line

            self.diagnostic_component = match.group(1)
            self.diagnostic_type = match.group(2)

            return

        match = test_summary_regex.search(line)
        if match is not None:
            with term.location(5, self.position * 2 + 1):
                print("%60s" % " ")
            with term.location(5, self.position * 2 + 1):
                print("%-60s" % line.decode("ascii")[-60:])

            if debug_mode:
                with term.location(1, 40 + self.position * 3):
                    print("%-20s: Test summary matched" % self.ufid)

                with term.location(1, 50):
                    print(
                            "%-20s: test summary match - hit enter to continue" % self.ufid)

                    my_input = sys.stdin.readline()

            return  # RETURN

        match = test_pass_regex.search(line)
        if match is not None:
            with term.location(5, self.position * 2 + 1):
                print("[%-60s]" % term.green(line.decode("ascii")[-60:]))

            if debug_mode:
                with term.location(1, 41 + self.position * 3):
                    print("%-20s: Test pass regex matched" % self.ufid)

                with term.location(1, 50):
                    print(
                            "%-20s: test pass    match - hit enter to continue" % self.ufid)

                    my_input = sys.stdin.readline()

            return  # RETURN

        match = test_fail_regex.search(line)
        if match is not None:
            with term.location(5, self.position * 2 + 1):
                print("[%-60s]" % term.red(line.decode("ascii")[-60:]))

            if debug_mode:
                with term.location(1, 42 + self.position * 3):
                    print("%-20s: Test fail regex matched" % self.ufid)

                with term.location(1, 50):
                    print(
                            "%-20s: test fail    match - hit enter to continue" % self.ufid)

                    my_input = sys.stdin.readline()

            return  # RETURN

loop = asyncio.get_event_loop()

checkout_path = sys.argv[1]

tasks = []
tasks.append(run_waf(checkout_path, "opt_exc_mt", target="bsls"))
tasks.append(
        run_waf(checkout_path, "dbg_exc_mt_64", target="bslscm"))
tasks.append(
        run_waf(checkout_path, "dbg_exc_mt_cpp11", target="bsls"))

print(term.clear())

with term.location(1, (LineProcessor.position + 2) * 2):
    with term.hidden_cursor():
        try:
            loop.run_until_complete(asyncio.wait(tasks))
        except e:
            print("Failed with exception:")
            print(e)

        loop.close()

print(term.move(1,50))

if debug_mode:
    print("Hit enter to exit")

    my_input = sys.stdin.readline()

# Test with
# PATH=$PWD/../bde-tools/bin:$PATH python3 ~/PycharmProjects/python_experiments/checkout.py \
# "export WAFLOCK=.waf-lock-dbg_exc_mt BDE_WAF_UFID=dbg_exc_mt; waf configure build --target=bsl" \
# "export WAFLOCK=.waf-lock-opt_exc_mt BDE_WAF_UFID=opt_exc_mt; waf configure build --target=bsl"

# Here's what bde_setwafenv.py sets...
# export BDE_WAF_UPLID=unix-linux-x86_64-2.6.18-gcc-4.9.2
# export BDE_WAF_UFID=dbg_exc_mt_64
# export BDE_WAF_BUILD_DIR="_build/unix-linux-x86_64-2.6.18-gcc-4.9.2-dbg_exc_mt_64"
# export WAFLOCK=".lock-waf-unix-linux-x86_64-2.6.18-gcc-4.9.2-dbg_exc_mt_64"
# export CXX=/opt/swt/install/gcc-4.9.2/bin/g++
# export CC=/opt/swt/install/gcc-4.9.2/bin/gcc
# unset BDE_WAF_COMP_FLAGS
# export PREFIX="/home/mgiroux/bde-install/unix-linux-x86_64-2.6.18-gcc-4.9.2-dbg_exc_mt_64"
# export PKG_CONFIG_PATH="/home/mgiroux/bde-install/unix-linux-x86_64-2.6.18-gcc-4.9.2-dbg_exc_mt_64/lib/pkgconfig"


text:
package com.amazonaws.services.eks.model;

import javax.annotation.Generated;

/**
 * <p>
 * This exception is thrown if the request contains a semantic error. The precise meaning will depend on the API, and
 * will be documented in the error message.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BadRequestException extends com.amazonaws.services.eks.model.AmazonEKSException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new BadRequestException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public BadRequestException(String message) {
        super(message);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>Odlične pizze. Za sad broj 1 za dostavu, nadam se da se neće pokvariti.</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/strossmayer</Source>
</CrawlItem>


text:
var http = require('http');
var cluster = require('cluster');
var express = require('express');
var cors = require('cors');
var bunyan = require('bunyan');
var bodyParser = require('body-parser');
var superagent = require('superagent');

var flightApi = require('./routes/flights');

var flightController = require('./routes/flights/flight-controller');

var config = require('./config');

var worker = 'unknown';
if (cluster.isWorker) {
  worker = cluster.worker.uniqueID;
  config.bunyan.worker = worker;
}
var log = bunyan.createLogger(config.bunyan);

// Pipe console printing to log file instead
// Logging will still show up in console as well.
console.error = log.error.bind(log);
console.log = log.info.bind(log);

var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);

app.use(bodyParser.json());
app.use(cors());

app.use('*', function(req, res, next) {
  res.setHeader('Content-Type', 'application/json');
  next();
});

app.get('/healthy', function(req, res) {
  res.send('OK');
});
app.use('/api', flightApi);

io.on('connection', function(socket) {
  socket.on('create-journey', function(data) {

  	console.log("hallo");
    flightController.findCheapestFlight(data, socket);
  });
  socket.on('ACK', function(data,data2) {
    flightController.updateACK(data,data2, socket);
  });

});

module.exports = server;


text:
package org.capcaval.c3.component.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface SubComponent {

}


text:
/*
 * TagUpdateBundle.java
 * Part of the MusicMan application by Ian Renton.  For information, please visit:
 * http://www.onlydreaming.net/software/musicman
 * This code is licenced under the GNU GPL v3 (http://www.gnu.org/licenses/).
 */
package net.onlydreaming.musicman.objects;

/**
 *
 * @author tsuki
 */
public class TagUpdateBundle {
    private String artist;
    private String album;
    private String title;
    private String track;
    private String genre;
    private boolean writeArtist;
    private boolean writeAlbum;
    private boolean writeTitle;
    private boolean writeTrack;
    private boolean writeGenre;

    public TagUpdateBundle(String artist, String album, String title, String track, String genre, boolean writeArtist, boolean writeAlbum, boolean writeTitle, boolean writeTrack, boolean writeGenre) {
        this.artist = artist;
        this.album = album;
        this.title = title;
        this.track = track;
        this.genre = genre;
        this.writeArtist = writeArtist;
        this.writeAlbum = writeAlbum;
        this.writeTitle = writeTitle;
        this.writeTrack = writeTrack;
        this.writeGenre = writeGenre;
    }

    /**
     * @return the artist
     */
    public String getArtist() {
        return artist;
    }

    /**
     * @return the album
     */
    public String getAlbum() {
        return album;
    }

    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }

    /**
     * @return the track
     */
    public String getTrack() {
        return track;
    }

    /**
     * @return the genre
     */
    public String getGenre() {
        return genre;
    }

    /**
     * @return the writeArtist
     */
    public boolean isWriteArtist() {
        return writeArtist;
    }

    /**
     * @return the writeAlbum
     */
    public boolean isWriteAlbum() {
        return writeAlbum;
    }

    /**
     * @return the writeTitle
     */
    public boolean isWriteTitle() {
        return writeTitle;
    }

    /**
     * @return the writeTrack
     */
    public boolean isWriteTrack() {
        return writeTrack;
    }

    /**
     * @return the writeGenre
     */
    public boolean isWriteGenre() {
        return writeGenre;
    }
}


text:
 /*
  Copyright (c) 2005,
	  Aaron Lefohn	(lefohn@cs.ucdavis.edu)
	  Adam Moerschell (atmoerschell@ucdavis.edu)
  All rights reserved.

  This software is licensed under the BSD open-source license. See
  http://www.opensource.org/licenses/bsd-license.php for more detail.

  *************************************************************
  Redistribution and use in source and binary forms, with or
  without modification, are permitted provided that the following
  conditions are met:

  Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.

  Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

  Neither the name of the University of Californa, Davis nor the names of
  the contributors may be used to endorse or promote products derived
  from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
  OF SUCH DAMAGE.
*/

#include "renderbuffer.h"
#include <iostream>
using namespace std;

Renderbuffer::Renderbuffer()
  : m_bufId(_CreateBufferId())
{}

Renderbuffer::Renderbuffer(GLenum internalFormat, int width, int height)
  : m_bufId(_CreateBufferId())
{
  Set(internalFormat, width, height);
}

Renderbuffer::~Renderbuffer()
{
  glDeleteRenderbuffersEXT(1, &m_bufId);
}

void Renderbuffer::Bind()
{
  glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_bufId);
}

void Renderbuffer::Unbind()
{
  glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
}

void Renderbuffer::Set(GLenum internalFormat, int width, int height)
{
  int maxSize = Renderbuffer::GetMaxSize();
  if (width > maxSize || height > maxSize ) {
    cerr << "Renderbuffer::Renderbuffer() ERROR:\n\t"
         << "Size too big (" << width << ", " << height << ")\n";
    return;
  }

  // Guarded bind
  GLint savedId = 0;
  glGetIntegerv( GL_RENDERBUFFER_BINDING_EXT, &savedId );
  if (savedId != (GLint)m_bufId) {
    Bind();
  }

  // Allocate memory for renderBuffer
  glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, internalFormat, width, height );

  // Guarded unbind
  if (savedId != (GLint)m_bufId) {
    glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, savedId);
  }
}

GLuint Renderbuffer::GetId() const
{
  return m_bufId;
}

GLint Renderbuffer::GetMaxSize()
{
  GLint maxAttach = 0;
  glGetIntegerv( GL_MAX_RENDERBUFFER_SIZE_EXT, &maxAttach );
  return maxAttach;
}

GLuint Renderbuffer::_CreateBufferId()
{
  GLuint id = 0;
  glGenRenderbuffersEXT(1, &id);
  return id;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using NUnit.Framework;
using ServiceStack.ServiceModel.Serialization;
using ServiceStack.ServiceModel.Tests.DataContracts.Operations;

namespace ServiceStack.ServiceModel.Tests
{
	[TestFixture]
	public class KeyValueDataContractDeserializerTests
	{
		[Test]
		public void create_dto_request_from_ids()
		{
			var dtoType = typeof(GetCustomers);
			var textValue = "1,2,3";
			var convertedValue = textValue.Split(',').ToList().ConvertAll(x => Convert.ToInt32(x));
			var valueMap = new Dictionary<string, string> { { "CustomerIds", textValue } };
			var result = (GetCustomers)KeyValueDataContractDeserializer.Instance.Parse(valueMap, dtoType);
			Assert.That(result.CustomerIds, Is.EquivalentTo(convertedValue));
		}

        [DataContract]
        public class Customer
        {
            [DataMember(Name = "first_name")]
            public string FirstName { get; set; }

            [DataMember(Name = "last_name")]
            public string LastName { get; set; }
        }

	    [Test]
	    public void KVP_Serializer_does_use_DataMember_Name_attribute()
	    {
            var valueMap = new Dictionary<string, string> { { "first_name", "james" }, { "last_name", "bond" } };

            var result = (Customer)KeyValueDataContractDeserializer.Instance.Parse(valueMap, typeof(Customer));

            Assert.That(result.FirstName, Is.EqualTo("james"));
            Assert.That(result.LastName, Is.EqualTo("bond"));
	    }
	}
}


text:
import java.io.*;
import java.awt.*;
import java.awt.event.*;

class RecordingFrame extends Frame
  implements WindowListener, ActionListener {

  boolean recording;

  TextField fnameField;
  Button browseButton;

  Label statusLabel;

  Button recordButton, nextButton, closeButton;
  VncViewer viewer;

  //
  // Check if current security manager allows to create a
  // RecordingFrame object.
  //

  public static boolean checkSecurity() {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
      try {
	security.checkPropertyAccess("user.dir");
	security.checkPropertyAccess("file.separator");
	// Work around (rare) checkPropertyAccess bug
	System.getProperty("user.dir");
      } catch (SecurityException e) {
	System.out.println("SecurityManager restricts session recording.");
	return false;
      }
    }
    return true;
  }

  //
  // Constructor.
  //

  RecordingFrame(VncViewer v) {
    super("TightVNC Session Recording");

    viewer = v;

    // Determine initial filename for next saved session.
    // FIXME: Check SecurityManager.

    String fname = nextNewFilename(System.getProperty("user.dir") +
				   System.getProperty("file.separator") +
				   "vncsession.fbs");

    // Construct new panel with file name field and "Browse" button.

    Panel fnamePanel = new Panel();
    GridBagLayout fnameGridbag = new GridBagLayout();
    fnamePanel.setLayout(fnameGridbag);

    GridBagConstraints fnameConstraints = new GridBagConstraints();
    fnameConstraints.gridwidth = GridBagConstraints.RELATIVE;
    fnameConstraints.fill = GridBagConstraints.BOTH;
    fnameConstraints.weightx = 4.0;

    fnameField = new TextField(fname, 64);
    fnameGridbag.setConstraints(fnameField, fnameConstraints);
    fnamePanel.add(fnameField);
    fnameField.addActionListener(this);

    fnameConstraints.gridwidth = GridBagConstraints.REMAINDER;
    fnameConstraints.weightx = 1.0;

    browseButton = new Button("Browse");
    fnameGridbag.setConstraints(browseButton, fnameConstraints);
    fnamePanel.add(browseButton);
    browseButton.addActionListener(this);

    // Construct the frame.

    GridBagLayout gridbag = new GridBagLayout();
    setLayout(gridbag);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weighty = 1.0;
    gbc.insets = new Insets(10, 0, 0, 0);

    Label helpLabel =
      new Label("File name to save next recorded session in:", Label.CENTER);
    gridbag.setConstraints(helpLabel, gbc);
    add(helpLabel);

    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.weighty = 0.0;
    gbc.insets = new Insets(0, 0, 0, 0);

    gridbag.setConstraints(fnamePanel, gbc);
    add(fnamePanel);

    gbc.fill = GridBagConstraints.BOTH;
    gbc.weighty = 1.0;
    gbc.insets = new Insets(10, 0, 10, 0);

    statusLabel = new Label("", Label.CENTER);
    gridbag.setConstraints(statusLabel, gbc);
    add(statusLabel);

    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.weightx = 1.0;
    gbc.weighty = 0.0;
    gbc.gridwidth = 1;
    gbc.insets = new Insets(0, 0, 0, 0);

    recordButton = new Button("Record");
    gridbag.setConstraints(recordButton, gbc);
    add(recordButton);
    recordButton.addActionListener(this);

    nextButton = new Button("Next file");
    gridbag.setConstraints(nextButton, gbc);
    add(nextButton);
    nextButton.addActionListener(this);

    closeButton = new Button("Close");
    gridbag.setConstraints(closeButton, gbc);
    add(closeButton);
    closeButton.addActionListener(this);

    // Set correct text, font and color for the statusLabel.
    stopRecording();

    pack();

    addWindowListener(this);
  }

  //
  // If the given string ends with ".NNN" where NNN is a decimal
  // number, increase this number by one. Otherwise, append ".001"
  // to the given string.
  //

  protected String nextFilename(String fname) {
    int len = fname.length();
    int suffixPos = len;
    int suffixNum = 1;

    if (len > 4 && fname.charAt(len - 4) == '.') {
      try {
	suffixNum = Integer.parseInt(fname.substring(len - 3, len)) + 1;
	suffixPos = len - 4;
      } catch (NumberFormatException e) { }
    }

    char[] zeroes = {'0', '0', '0'};
    String suffix = String.valueOf(suffixNum);
    if (suffix.length() < 3) {
      suffix = new String(zeroes, 0, 3 - suffix.length()) + suffix;
    }

    return fname.substring(0, suffixPos) + '.' + suffix;
  }

  //
  // Find next name of a file which does not exist yet.
  //

  protected String nextNewFilename(String fname) {
    String newName = fname;
    File f;
    try {
      do {
	newName = nextFilename(newName);
	f = new File(newName);
      } while (f.exists());
    } catch (SecurityException e) { }

    return newName;
  }

  //
  // Let the user choose a file name showing a FileDialog.
  //

  protected boolean browseFile() {
    File currentFile = new File(fnameField.getText());

    FileDialog fd =
      new FileDialog(this, "Save next session as...", FileDialog.SAVE);
    fd.setDirectory(currentFile.getParent());
    fd.setVisible(true);
    if (fd.getFile() != null) {
      String newDir = fd.getDirectory();
      String sep = System.getProperty("file.separator");
      if (newDir.length() > 0) {
	if (!sep.equals(newDir.substring(newDir.length() - sep.length())))
	  newDir += sep;
      }
      String newFname = newDir + fd.getFile();
      if (newFname.equals(fnameField.getText())) {
	fnameField.setText(newFname);
	return true;
      }
    }
    return false;
  }

  //
  // Start recording.
  //

  public void startRecording() {
    statusLabel.setText("Status: Recording...");
    statusLabel.setFont(new Font("Helvetica", Font.BOLD, 12));
    statusLabel.setForeground(Color.red);
    recordButton.setLabel("Stop recording");

    recording = true;

    viewer.setRecordingStatus(fnameField.getText());
  }

  //
  // Stop recording.
  //

  public void stopRecording() {
    statusLabel.setText("Status: Not recording.");
    statusLabel.setFont(new Font("Helvetica", Font.PLAIN, 12));
    statusLabel.setForeground(Color.black);
    recordButton.setLabel("Record");

    recording = false;

    viewer.setRecordingStatus(null);
  }

  //
  // Close our window properly.
  //

  public void windowClosing(WindowEvent evt) {
    setVisible(false);
  }

  //
  // Ignore window events we're not interested in.
  //

  public void windowActivated(WindowEvent evt) {}
  public void windowDeactivated (WindowEvent evt) {}
  public void windowOpened(WindowEvent evt) {}
  public void windowClosed(WindowEvent evt) {}
  public void windowIconified(WindowEvent evt) {}
  public void windowDeiconified(WindowEvent evt) {}

  //
  // Respond to button presses
  //

  public void actionPerformed(ActionEvent evt) {
    if (evt.getSource() == browseButton) {
      if (browseFile() && recording)
	startRecording();

    } else if (evt.getSource() == recordButton) {
      if (!recording) {
	startRecording();
      } else {
	stopRecording();
        fnameField.setText(nextNewFilename(fnameField.getText()));
      }

    } else if (evt.getSource() == nextButton) {
      fnameField.setText(nextNewFilename(fnameField.getText()));
      if (recording)
	startRecording();

    } else if (evt.getSource() == closeButton) {
      setVisible(false);

    }
  }
}


text:
$(function(){
    $("#register0").click(function(){
        location.href = 'register';
    });
    $("#login0").click(function(){
        var username = $("#username").val();
        var password = $("#password").val();
        var data = {"uname":username,"upwd":password};
        $.ajax({
            url:'/login',
            type:'post',
            data: data,
            success: function(data,status){
                if(status == 'success'){
                    location.href = 'main';
                }
            },
            error: function(data,status){
                if(status == 'error'){
                    location.href = 'login';
                }
            }
        });
    });
});


text:
<?php
namespace suda\application\exception;

use RuntimeException;

/**
 * 应用异常
 */
class ApplicationException extends RuntimeException
{
    const ERR_MANIFEST_IS_EMPTY = 1;
    const ERR_FRAMEWORK_VERSION = 2;
    const ERR_MODULE_REQUIREMENTS = 3;
    const ERR_MODULE_NAME = 4;
    const ERR_CONFLICT_MODULE_NAME = 5;
    const ERR_CONFLICT_MODULE_UNIQUE = 6;
    const ERR_PATH_NOT_EXISTS_IN_MODULE = 7;
}


text:
Deface::Override.new(:virtual_path => "spree/admin/orders/index",
                     :name => "subscriptions_admin_menu",
                     :insert_after => "[data-hook='admin_orders_index_search']",
                     :partial => "spree/admin/shared/orders_sub_menu")

Deface::Override.new(:virtual_path => "spree/admin/orders/new",
                     :name => "subscriptions_admin_menu",
                     :insert_after => "[data-hook='admin_order_new_header']",
                     :partial => "spree/admin/shared/orders_sub_menu")

Deface::Override.new(:virtual_path => "spree/admin/orders/edit",
                     :name => "subscriptions_admin_menu",
                     :insert_after => "[data-hook='admin_order_edit_form']",
                     :partial => "spree/admin/shared/orders_sub_menu")


text:
import { babel } from '@rollup/plugin-babel';
import license from 'rollup-plugin-license';
import { terser } from 'rollup-plugin-terser';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import pkg from './package.json';

const banner = ``;

const plugins = [
  babel({
    exclude: ['node_modules/**'],
  }),
  terser(),
  license({
    banner,
  }),
];

export default [
  {
    input: 'src/panelsnap.js',
    output: [
      { file: pkg.main, format: 'cjs' },
      { file: pkg.module, format: 'es' },
    ],
    external: ['tweezer.js'],
    plugins,
  },
  {
    input: 'src/panelsnap.js',
    output: [
      { file: pkg.browser, format: 'umd', name: 'PanelSnap' },
      { file: 'docs/panelsnap.js', format: 'umd', name: 'PanelSnap' },
    ],
    plugins: [...plugins, nodeResolve()],
  },
];


text:
namespace BananaVM {
	namespace Instruction {

//		AddInstruction::AddInstruction(RegisterName register0, RegisterName register1) : ArithmeticInstruction(register0, register1) { }

		void AddInstruction::perform(ProcessorThread& thread) {
			auto a = thread.getContext().getRegister(_register0);
			auto b = thread.getContext().getRegister(_register1);
			auto& result = thread.getContext().getAccumulatorRegister();
			auto& carry = thread.getContext().getCarryRegister();

			result = a + b;
			carry = (result < a) | (result < b);
		}

//		SubtractInstruction::SubtractInstruction(RegisterName register0, RegisterName register1) : ArithmeticInstruction(register0, register1){ }

		void SubtractInstruction::perform(ProcessorThread& thread) {
			auto a = thread.getContext().getRegister(_register0);
			auto b = thread.getContext().getRegister(_register1);
			auto& result = thread.getContext().getAccumulatorRegister();
//			auto& carry = thread.getContext().getCarryRegister();

			// TODO handle carry out
			result = a - b;
//			carry = (result > a) | (result > b);
		}

		void MultiplyInstruction::perform(ProcessorThread& thread) {
			auto a = thread.getContext().getRegister(_register0);
			auto b = thread.getContext().getRegister(_register1);
			auto& result = thread.getContext().getAccumulatorRegister();

			result = a * b;
		}

		void DivideInstruction::perform(ProcessorThread& thread) {
			auto a = thread.getContext().getRegister(_register0);
			auto b = thread.getContext().getRegister(_register1);
			auto& result = thread.getContext().getAccumulatorRegister();

			result = a / b;
		}
	}
}


text:
module states {
    export class Letter extends Phaser.Text {

        letter: string;
        bd: BusinessDelegate;

        constructor(game: Phaser.Game, x: number, y: number, letter: string, font: string) {
            super(game, x, y, letter, { font: font, fill: 'white', align: 'left', wordWrap: true, wordWrapWidth: 450 });

            this.letter = letter;
            this.font = font;

            this.inputEnabled = true;
            this.input.enableDrag(true);
            this.events.onDragStop.add(this.onDragStop);

            this.game.add.existing(this);

            this.bd = new BusinessDelegate();

        }

        onDragStop(letter: Letter) {
            // console.log("Pos: " + letter.letter + " (" + letter.position.x + ", " + letter.position.y + ")");
            // console.log("dim: " + letter.letter + " (" + letter.width + ", " + letter.height + ")");
            bd.createGame();
        }
    }
}


text:
<template name="branding">

      {{> settingsMenu }}

              {{_ "branding_panel_title" }}

            {{# if branding }}
              {{> viewProjectLogo branding=branding }}
              {{> uploadProjectLogo branding=branding }}
              {{> viewCoverPhoto branding=branding }}
              {{> uploadCoverPhoto branding=branding }}
              {{# autoForm
                id="brandingEdit"
                type="update"
                collection=brandingCollection
                doc=branding }}
              {{> afQuickField name='siteTitle' }}
              {{> afQuickField name='siteSlogan' }}
              {{> afQuickField name='colors' }}
              {{> afQuickField name='siteFooter' }}
              {{> afQuickField name='socialMedia' }}

                <button type="submit" class="btn btn-primary">
                  {{_ "branding_update" }}
                </button>

              {{/ autoForm }}
            {{ else }}
              {{# autoForm
                id="brandingAdd"
                type="insert"
                collection=brandingCollection }}
              {{> afQuickField name='siteTitle' }}
              {{> afQuickField name='siteSlogan' }}
              {{> afQuickField name='siteFooter' }}
              {{> afQuickField name='socialMedia' }}

                <button type="submit" class="btn btn-primary">
                  {{_ "branding_save" }}
                </button>

              {{/ autoForm }}
            {{/ if }}

</template>


text:
<?php
	function initialize_page()
	{

	}

	function display_page_content()
	{
		$emails = NLEmails::FindAll();
		$lists = NLLists::FindAll();
?>

Subscribers listed below

<?php
	$addresscount = 0;
	$subscribecount = 0;
	$subscribers = "";

	foreach($emails as $email)
	{
		$lists_subscribed_to = 0;

		foreach ($lists as $list)
		{
			if ($email->is_linked($list))
			{
				$lists_subscribed_to++;
			}
		}
		$address = "";
		if ($email->first_name && $email->last_name && $email->address1 && $email->city && $email->state && $email->zip)
		{
			$address = "(Complete address available)";
			$addresscount++;
		}
		$subscribers .= "\t\t\t\t\t\t
$email->email Subscribed to: $lists_subscribed_to lists $address
\n";
		$subscribecount++;
	}
?>

{<?php echo $subscribecount ?>} Subscribers with {<?php echo $addresscount ?>} complete address(es)

<?php echo $subscribers ?>

<?php } ?>


text:
title: <a-tetrahedron>
type: primitives
layout: docs
parent_section: primitives
---

## Example

```html
<a-tetrahedron color="#FF926B" radius="5"></a-tetrahedron>
```

## Attributes

| Attribute   | Component Mapping    | Default Value |
| --------    | -----------------    | ------------- |
| color       | material.color       | #FFF          |
| metalness   | material.metalness   | 0             |
| opacity     | material.opacity     | 1             |
| radius      | geometry.radius      | 1             |
| repeat      | material.repeat      | None          |
| roughness   | material.roughness   | 0.5           |
| shader      | material.shader      | standard      |
| side        | material.side        | front         |
| src         | material.src         | None          |
| transparent | material.transparent | false         |


text:
using LionFire.Coroutines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LionFire.Behaviors
{

    /// <summary>
    /// Can be injected in a Sequence to be used as a sleep
    /// </summary>
    public class DelayedCondition : PollingCondition, IPolledStatus
        , IHasStatusRecurranceParameters
    {
        DateTime startTime;
        //TimeSpan delay = TimeSpan.FromSeconds(10);
        TimeSpan Delay;
        TimeSpan delayRemaining { get { return RecurranceParameters.Interval; } set { recurranceParameters.Interval = value; } }
        BehaviorStatus result = BehaviorStatus.Succeeded;
        public string FailMessage;

        #region Construction

        public DelayedCondition() { }

        public DelayedCondition(TimeSpan delay, BehaviorStatus result)
        {
            switch (result)
            {
                case BehaviorStatus.Failed:
                case BehaviorStatus.Succeeded:
                    break;
                default:
                    throw new ArgumentException("result must be Succeeded or Failed");
            }
            this.Delay = delay;
            //this.delay = delay;

            this.result = result;
        }

        #endregion

        #region Transitions

        protected override BehaviorStatus OnStart()
        {
            startTime = DateTime.UtcNow;
            return base.OnStart();
        }

        protected override bool OnInitializing()
        {
            delayRemaining = Delay;
            return base.OnInitializing();
        }

        #endregion

        #region Poll for Status

        public override void UpdateStatus()
        {
            if (Status == BehaviorStatus.Running)
            {
                var time = DateTime.UtcNow;

                var remaining = (Delay - (time - startTime));
                l.Trace("DelayedCondition UpdateStatus() " + remaining.TotalSeconds + " remaining.");

                if (time - startTime > Delay)
                {
                    if (result == BehaviorStatus.Succeeded)
                    {
                        Succeed();
                    }
                    else if (result == BehaviorStatus.Failed)
                    {
                        Fail(FailMessage);
                    }
                    else throw new UnreachableCodeException();
                }
                else
                {
                    delayRemaining = remaining;
                }
            }
        }

        #endregion

        public RecurranceParameters RecurranceParameters
        {
            get
            {
                return recurranceParameters;
            }
        } private RecurranceParameters recurranceParameters = new RecurranceParameters();

        #region Misc

        private static ILogger l = Log.Get();

        #endregion
    }
}


text:
require 'helper'

class TestData2pdf < Test::Unit::TestCase

    should '#command call binary and quiet_option methods' do
      Data2pdf.expects(:binary).returns('engine')
      Data2pdf.expects(:quiet_option).returns('-q')
      (assert_equal 'engine -q  foo.html foo.pdf', (Data2pdf.send :command, 'foo.html', 'foo.pdf'))
    end

    should '#render return pdf file name if destination is file' do
      Data2pdf.stubs(:source).returns(['some-file.html', File])
      Data2pdf.stubs(:destination).returns(['some-file.pdf', File])
      Data2pdf.stubs(:stylesheets).returns(nil)
      Data2pdf.stubs(:binary).returns('engine')
      Data2pdf.stubs(:quiet_option).returns('-q')
      io = IO.popen('ls','w+')
      IO.stubs(:popen).returns(io)
      (assert_equal 'some-file.pdf', (Data2pdf.render 'some-file.html', 'some-file.pdf'))
    end

end


text:
- An **atom** (unique symbol) begins with a lowercase character.
- A **variable** (can change) begins with an uppercase letter / an underscore.

# Howto

Define facts:

```prolog
likes(wallace, cheese).
likes(grommit, cheese).
likes(wendolene, sheep).
```

Define a rule:

```prolog
friend(X, Y) :- \+(X = Y), likes(X, Z), likes(Y, Z).
```

That say: X is a friend of Y if:

- X != Y
- and X likes Z
- and Y likes Z

Now, we can load this code in prolog interpreter and tell our questions:

```prolog
| ?- ['friends.pl'].
| ?- likes(wallace, sheep).
no
| ?- likes(grommit, cheese).
yes
```

We can also found **Who** like cheese (prolog detect that **Who** is a variable and try to assign it with a solution):

```prolog
| ?- likes(Who, cheese).

Who = wallace ? h
Action (; for next solution, a for all solutions, RET to stop) ? ;

Who = grommit ?

(1 ms) yes
| ?-
```

I have pressed "h" for help, ";" and finally "RET" to stop.

# Bonus

With map.pl, you can choose an unique color for each provinces put as coloring argument.

Execution example:

```prolog
| ?- ['map.pl'].
...
(1 ms) yes
| ?- coloring(red, Mississippi, Georgia, Tennessee, Florida).

Florida = blue
Georgia = green
Mississippi = green
Tennessee = blue ?
```


text:
<?php
namespace SBData\Model\Field;
use SBData\Model\Value\Value;

/**
 * Represents the structure of an individual data element that stores text and
 * is kept hidden from the user but still propagates a parameter to a form.
 */
class HiddenField extends GenericHiddenField
{
	/**
	 * Constructs a new HiddenField instance
	 *
	 * @param $mandatory Indicates whether a given value is mandatory
	 * @param $maxlength Maximum size of the text field or null for infinite size
	 * @param $defaultValue The value it defaults to
	 */
	public function __construct(bool $mandatory = false, int $maxlength = null, $defaultValue = null)
	{
		parent::__construct(new Value($mandatory, $maxlength, $defaultValue));
	}
}
?>


text:
/* global describe, it */

'use strict'

var expect = require('expect.js')

var MailerLite = require('..')
var ML = new MailerLite()

const LIST_NAME = 'Mocha Test'

const TEST_SUBSCRIBERS = [
  {
    email: 'foo@bar.com',
    name: 'Foo Bar'
  },
  {
    email: 'john@doe.net',
    name: 'John Doe'
  }
]

describe('Subscribers', () => {
  it('should add a subscriber to a new list and remove it immediately', (done) => {
    let list_id = 0
    let user = TEST_SUBSCRIBERS[0]

    ML.Lists.addList(LIST_NAME)
      .then((data) => {
        list_id = data.id
        return ML.Subscribers.addSubscriber(list_id, user.email, user.name)
      })
      .then((data) => {
        expect(data.email).to.be.equal(user.email)
        return ML.Subscribers.deleteSubscriber(list_id, user.email)
      })
      .then((data) => {
        return ML.Lists.removeList(list_id)
      })
      .then(() => {
        done()
      })
  })
})


text:
from sys import argv

script, input_file = argv

def print_all(f):
  print f.read()

def rewind(f):
  f.seek(0)

def print_a_line(line_count, f):
  print line_count, f.readline()

current_file = open(input_file)

print "First, let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind, kind of like a tape."

rewind(current_file)

print "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)


text:
Wordlists
============================

Closed class word types
-------------------------------------------

Various wordlists, mostly for subtypes of closed class words

.. autodata:: corpkit.dictionaries.wordlists.wordlists

Systemic functional process types
-------------------------------------------

Inflected verbforms for systemic process types.

.. data:: corpkit.dictionaries.process_types.processes

Stopwords
-------------------------------------------

A list of arbitrary stopwords.

.. data:: corpkit.dictionaries.stopwords.stopwords

Systemic/dependency label conversion
-------------------------------------------

Systemic-functional to dependency role translation.

.. autodata:: corpkit.dictionaries.roles.roles

BNC reference corpus
-------------------------------------------

BNC word frequency list.

.. data:: corpkit.dictionaries.bnc.bnc

Spelling conversion
-------------------------------------------

A dict with U.S. English spellings as keys, U.K. spellings as values.

.. data:: corpkit.dictionaries.word_transforms.usa_convert


text:
package org.openecard.addon;

import org.openecard.common.interfaces.Dispatcher;
import org.openecard.common.interfaces.EventManager;
import org.openecard.common.sal.state.CardStateMap;
import org.openecard.gui.UserConsent;
import org.openecard.recognition.CardRecognition;

/**
 *
 * @author Tobias Wich <tobias.wich@ecsec.de>
 * @author Dirk Petrautzki <petrautzki@hs-coburg.de>
 */
public class Context {

    private AddonProperties _unnamed_AddonProperties_;
    private final AddonManager manager;
    private Dispatcher dispatcher;
    private UserConsent userConsent;

    private CardStateMap cardStates;
    private CardRecognition recognition;
    private EventManager eventManager;
    private EventHandler eventHandler;

    public Context(AddonManager manager, Dispatcher dispatcher, UserConsent userConsent, CardStateMap cardStates, CardRecognition recognition, EventManager eventManager, EventHandler eventHandler) {
	this.manager = manager;
	this.dispatcher = dispatcher;
	this.userConsent = userConsent;
	this.cardStates = cardStates;
	this.recognition = recognition;
	this.eventManager = eventManager;
	this.eventHandler = eventHandler;
    }

    public AddonManager getManager() {
	return manager;
    }

    public Dispatcher getDispatcher() {
	return dispatcher;
    }

    public EventManager getEventManager() {
	return eventManager;
    }

    public UserConsent getUserConsent() {
	return userConsent;
    }

    public AddonProperties getAddonProperties() {
	throw new UnsupportedOperationException();
    }

    public AddonProperties getActionProperties() {
	throw new UnsupportedOperationException();
    }

    /**
     * Gets the card states representing the internal state of the SAL.
     *
     * @return Current card states.
     * @deprecated Because this element leaks SAL internals which are better accessed with the SAL functions. Will be
     *   removed in version 1.2.0.
     */
    @Deprecated
    public CardStateMap getCardStates() {
	return cardStates;
    }

    public CardRecognition getRecognition() {
	return recognition;
    }

    public EventHandler getEventHandler() {
	return eventHandler;
    }

}


text:
layout: resources
ref: resources
order: 2
bgclass: resources

# translate below, never translate before the first :

title: Hulpbronnen
lang: nl
permalink: /nl/hulpbronnen.html
menu: "0:[ 'Node Hosting', '#node' ], 1:[ 'Crypto Compare', 'https://www.cryptocompare.com/coins/trc/forum' ], 5:[ 'Technische Hulpbronnen', '#technical' ], 8:[ 'Sociale Media', '#social' ], 12:[ 'Discussie', '#discussion' ], 13:[ 'Nieuws', '#news' ]"
headlines: "'Treed toe tot de Gemeenschap', 'Neem deel aan het Gesprek', 'Praat Mee', 'Verander de Wereld'"
social: Sociale Media
social_blurb: Sluit je aan bij onze sociale media berichten om te leren wat er nieuw is aan Terracoin.
news: Nieuws
news_blurb: Lees meer over wat Terracoin is, wat ons anders maakt, en waar we naartoe gaan als Crypto-technologie.
discussion: Discussie
discussion_blurb: Neem deel aan het Gesprek, Dit is waar u een verschil kan maken in de richting van TRC en uw Gemeenschap.
technical: Technische Hulpbronnen
donationservers: Donatie Masternodes - Stichting Terracoin liefdadigheidsmasternodes die zullen worden gebruikt om te doneren aan non-profitorganisaties zodra Terracoin een maand lang een waarde behoudt van $1 USD. Elke maand zal een non-profit worden gekozen door de gemeenschap en de helft van de nettowinst zal worden gedoneerd aan de non-profitorganisatie.
explorer: Explorer - Terracoin Block Explorer waarmee u op adres en transactie kunt zoeken.
kiva: KIVA - We hebben een team op Kiva waarvan individuen lid kunnen worden en microleningen kunnen maken voor mensen over de hele wereld. Voel je vrij om mee te doen en laat de wereld zien dat Terracoin kan helpen!
masternodes: Masternode Info - Geeft een overzicht van de verwachte winst van een masternode en kan uw exacte bedrag weergeven en of de masternode is ingeschakeld of niet.
services: Diensten - Hier kunt u de agenda voor het gedecentraliseerde bestuur bekijken, de huidige voorstellen bekijken en ontdekkingen doen voor nieuwe voorstellingen.
whitepaper: Witboek - Een levend document dat de geschiedenis en specificaties van Terracoin en Stichting Terracoin uitlegt.
wiki: Wiki - Vind meer informatie over Terracoin op onze Wiki.
paperwallet: Papieren Portemonee - Print en geef mensen Terracoin.
setup: Installatie Script - De één-druk-op-de-knop-oplossing voor het instellen van uw Masternode met video-instructies.
node_hosting: Node hosting partners
---


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EDUCATION = {
    "title": "Education",
    "content": "I have experties on various web technologies.",
    "education": [{
            "qualification": "B.E – IT",
            "year": "2005-09",
            "percentage": "67.9%",
            "from": "Rajasthan University",
            "location": "Rajasthan/India",
            "content": "Download updated resume."
        }, {
            "qualification": "XIIth",
            "year": "2001",
            "percentage": "71%",
            "from": "Bihar Intermediate Education Council",
            "location": "Bihar/India",
            "content": "Download updated resume."
        }, {
            "qualification": "Xth",
            "year": "1999",
            "percentage": "57%",
            "from": "Bihar School Examination Board",
            "location": "Bihar/India",
            "content": "Download updated resume."
        }]
};
//# sourceMappingURL=education.moc.data.js.map


text:
#pragma once

#include "ornabstractlistmodel.h"
#include "orncategorylistitem.h"

/**
 * @brief The categories model class
 * This will work properly only if api response contains sorted categories
 */
class OrnCategoriesModel : public OrnAbstractListModel<OrnCategoryListItem>
{
    Q_OBJECT
public:
    enum Role
    {
        CategoryIdRole = Qt::UserRole,
        AppsCountRole,
        DepthRole,
        NameRole,
        VisibilityRole,
        ChildrenRole,
    };
    Q_ENUM(Role)

    explicit OrnCategoriesModel(QObject *parent = nullptr);

    // QAbstractItemModel interface
public:
    QVariant data(const QModelIndex &index, int role) const override;
    void fetchMore(const QModelIndex &parent) override;
    QHash<int, QByteArray> roleNames() const override;

    // OrnAbstractListModel interface
protected:
    void processReply(const QJsonDocument &jsonDoc) override;
};


text:
__doc__ = """
collections compatibility module for older (pre-2.4) Python versions

This does not not NOT (repeat, *NOT*) provide complete collections
functionality.  It only wraps the portions of collections functionality
used by SCons, in an interface that looks enough like collections for
our purposes.
"""

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

# Use exec to hide old names from fixers.
exec("""if True:
            from UserDict import UserDict
            from UserList import UserList
            from UserString import UserString""")

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
OpenGLAppComponent::OpenGLAppComponent()   : frameCounter (0)
{
    setOpaque (true);
    openGLContext.setRenderer (this);
    openGLContext.attachTo (*this);
    openGLContext.setContinuousRepainting (true);
}

OpenGLAppComponent::~OpenGLAppComponent()
{
    // Before your subclass's destructor has completed, you must call
    // shutdownOpenGL() to release the GL context. (Otherwise there's
    // a danger that it may invoke a GL callback on your class while
    // it's in the process of being deleted.
    jassert (! openGLContext.isAttached());

    shutdownOpenGL();
}

void OpenGLAppComponent::shutdownOpenGL()
{
    openGLContext.detach();
}

void OpenGLAppComponent::newOpenGLContextCreated()
{
    initialise();
}

void OpenGLAppComponent::renderOpenGL()
{
    ++frameCounter;
    render();
}

void OpenGLAppComponent::openGLContextClosing()
{
    shutdown();
}


text:
'use strict';
// This is a basic test file for use with testling.
// The test script language comes from tape.
/* jshint node: true */
var test = require('tape');

var webdriver = require('selenium-webdriver');
var seleniumHelpers = require('../../../../../test/selenium-lib');

test('PeerConnection pc1 sample', function(t) {
  var driver = seleniumHelpers.buildDriver();

  driver.get('file://' + process.cwd() +
      '/src/content/peerconnection/pc1/index.html')
  .then(function() {
    t.pass('page loaded');
    return driver.findElement(webdriver.By.id('startButton')).click();
  })
  .then(function() {
    t.pass('got media');
    return driver.findElement(webdriver.By.id('callButton')).click();
  })
  .then(function() {
    return driver.wait(function() {
      return driver.executeScript(
          'return pc2 && pc2.iceConnectionState === \'connected\';');
    }, 30 * 1000);
  })
  .then(function() {
    t.pass('pc2 ICE connected');
    return driver.findElement(webdriver.By.id('hangupButton')).click();
  })
  .then(function() {
    return driver.wait(function() {
      return driver.executeScript('return pc1 === null');
    }, 30 * 1000);
  })
  .then(function() {
    t.pass('hangup');
    t.end();
  })
  .then(null, function(err) {
    t.fail(err);
    t.end();
  });
});


text:
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__))) unless $LOAD_PATH.include?(File.expand_path(File.dirname(__FILE__)))

require 'loofah'

module Loofah::ActiveRecord
  VERSION = "1.2.0"
end

if defined?(Rails) && [3,4,5].include?(Rails::VERSION::MAJOR)
  require 'loofah/activerecord/railtie'
elsif defined? Rails.configuration and Rails.configuration.frameworks.include?([:active_record]) # >= 2.1
  Rails.configuration.after_initialize do
    require 'loofah/activerecord/active_record'
    require 'loofah/activerecord/xss_foliate'
  end
elsif defined? ActiveRecord::Base # <= 2.0
  require 'loofah/activerecord/active_record'
  require 'loofah/activerecord/xss_foliate'
end


text:
require 'unindent/unindent'
require 'json'

module Autoparts
  module Commands
    class Init
      def initialize(args, options)
        if options.first == '-'
          # NOTE: a common usage of parts init is `eval $(parts init -)`.
          # Ensure that everything run below does not have stray output
          no_autoupdate_env = ENV['AUTOPARTS_NO_AUTOUPDATE']
          if autoupdate_due? && !(no_autoupdate_env && ['1', 'true'].include?(no_autoupdate_env.downcase))
            if Update.update(true)
              File.open(Path.config_last_update, 'w') do |f|
                f.write JSON.generate({
                  'last_update' => Time.now.to_i
                })
              end
              # rerun in case the code changes from underneath us break anything
              if File.basename($0) == 'parts' && File.executable?($0)
                exec({'AUTOPARTS_NO_AUTOUPDATE' => '1'}, "#{$0} init #{(options + args).join(' ')}")
              end
            end
          end
          Env.print_exports
        elsif options.include? '--start'
          Autoparts::Package.start_all
        else
          show_help
        end
      end

      def show_help
        profile = case ENV['SHELL']
        when /bash/
          '~/.bashrc'
        when /zsh/
          '~/.zshrc'
        else
          'your profile'
        end
        puts <<-STR.unindent
          # Load environment variables for Autoparts automatically by
          # adding the following to #{profile}

          eval "$(parts env)"
        STR
      end

      def autoupdate_due?
        info = nil
        begin
          info = JSON.parse(File.read(Path.config_last_update.to_s))
        rescue
        end

        !info || !info['last_update'] || (info['last_update'].to_i <= Time.now.to_i - 60 * 60 * 24)
      end
    end
  end
end


text:
layout: post
date: '2015-08-19'
title: "Bill Levkoff Junior Bridesmaid dress of Style 38002 Sleeveless Floor-Length Aline/Princess"
category: Bill Levkoff
tags: [Bill Levkoff ,Bill Levkoff,Aline/Princess ,Square,Floor-Length,Sleeveless]
---
### Bill Levkoff Junior Bridesmaid dress of Style 38002
Just **$209.99**
###   Sleeveless Floor-Length Aline/Princess

BRANDS	Bill Levkoff

Silhouette	Aline/Princess

Neckline	Square

Hemline/Train	Floor-Length

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/bill-levkoff-/15055-bill-levkoff-junior-bridesmaid-dress-of-style-38002.html](https://www.readybrides.com/en/bill-levkoff-/15055-bill-levkoff-junior-bridesmaid-dress-of-style-38002.html)


text:
package dilithium

import (
	"fmt"
	"io"

	"circl/sign/dilithium/internal/common"
	"circl/sign/dilithium/mode2"
)

// implMode2 implements the mode.Mode interface for Dilithium2.
type implMode2 struct{}

// Mode2 is Dilithium in mode "Dilithium2".
var Mode2 Mode = &implMode2{}

func (m *implMode2) GenerateKey(rand io.Reader) (
	PublicKey, PrivateKey, error) {
	return mode2.GenerateKey(rand)
}

func (m *implMode2) NewKeyFromSeed(seed []byte) (PublicKey,
	PrivateKey) {
	if len(seed) != common.SeedSize {
		panic(fmt.Sprintf("seed must be of length %d", common.SeedSize))
	}
	seedBuf := [common.SeedSize]byte{}
	copy(seedBuf[:], seed)
	return mode2.NewKeyFromSeed(&seedBuf)
}

func (m *implMode2) Sign(sk PrivateKey, msg []byte) []byte {
	isk := sk.(*mode2.PrivateKey)
	ret := [mode2.SignatureSize]byte{}
	mode2.SignTo(isk, msg, ret[:])
	return ret[:]
}

func (m *implMode2) Verify(pk PublicKey, msg []byte, signature []byte) bool {
	ipk := pk.(*mode2.PublicKey)
	return mode2.Verify(ipk, msg, signature)
}

func (m *implMode2) PublicKeyFromBytes(data []byte) PublicKey {
	var ret mode2.PublicKey
	if len(data) != mode2.PublicKeySize {
		panic("packed public key must be of mode2.PublicKeySize bytes")
	}
	var buf [mode2.PublicKeySize]byte
	copy(buf[:], data)
	ret.Unpack(&buf)
	return &ret
}

func (m *implMode2) PrivateKeyFromBytes(data []byte) PrivateKey {
	var ret mode2.PrivateKey
	if len(data) != mode2.PrivateKeySize {
		panic("packed public key must be of mode2.PrivateKeySize bytes")
	}
	var buf [mode2.PrivateKeySize]byte
	copy(buf[:], data)
	ret.Unpack(&buf)
	return &ret
}

func (m *implMode2) SeedSize() int {
	return common.SeedSize
}

func (m *implMode2) PublicKeySize() int {
	return mode2.PublicKeySize
}

func (m *implMode2) PrivateKeySize() int {
	return mode2.PrivateKeySize
}

func (m *implMode2) SignatureSize() int {
	return mode2.SignatureSize
}

func (m *implMode2) Name() string {
	return "Dilithium2"
}

func init() {
	modes["Dilithium2"] = Mode2
}


text:
import React from 'react';
import VideoListItem from './video_list_item';

//key tag is used with an array like lists so it makes updating a list easier without having to recreate the entire list
//for the example we used ETAG as a unique ID for each item.
//props -> refers to the this.state object from the index. .videos refers to the this.state.videos
//video in this respect is just an arbitary variable name, but it is one of 5 videos, from that object.

//passing onVideoSelect into the props for video_list_item to have access

const VideoList = (props) => {

	const videoItems = props.videos.map((video) => {
		return (
			<VideoListItem
			onVideoSelect={props.onVideoSelect}
			key={video.etag}
			video={video} />);
	});

	return(
			<ul className='col-md-4 list-group' >
				{videoItems}
			</ul>
		);
	};

export default VideoList;


text:
<?php

/**
 * HTTP Response
 *
 * @package     Nails
 * @subpackage  common
 * @category    Factory
 * @author      Nails Dev Team
 */

namespace Nails\Common\Factory;

use GuzzleHttp\Psr7\Response;
use Nails\Common\Helper\ArrayHelper;

/**
 * Class HttpResponse
 *
 * @package Nails\Common\Factory
 */
class HttpResponse
{
    /**
     * @var Response
     */
    protected $oResponse;

    // --------------------------------------------------------------------------

    /**
     * HttpResponse constructor.
     *
     * @param Response $oResponse
     */
    public function __construct(Response $oResponse)
    {
        $this->oResponse = $oResponse;
    }

    // --------------------------------------------------------------------------

    /**
     * Get the HTTP response
     *
     * @return Response
     */
    public function getResponse(): Response
    {
        return $this->oResponse;
    }

    // --------------------------------------------------------------------------

    /**
     * Returns the response headers
     *
     * @return array
     */
    public function getHeaders(): array
    {
        return $this->oResponse->getHeaders();
    }

    // --------------------------------------------------------------------------

    /**
     * Returns a single header
     *
     * @param string $sHeader The header to return
     *
     * @return mixed|null
     */
    public function getHeader($sHeader)
    {
        return ArrayHelper::getFromArray($sHeader, $this->oResponse->getHeaders());
    }

    // --------------------------------------------------------------------------

    /**
     * Return the response's status code
     *
     * @return int
     */
    public function getStatusCode(): int
    {
        return $this->oResponse->getStatusCode();
    }

    // --------------------------------------------------------------------------

    /**
     * Returns the response's reason phrase
     *
     * @return string
     */
    public function getReasonPhrase(): string
    {
        return $this->oResponse->getReasonPhrase();
    }

    // --------------------------------------------------------------------------

    /**
     * Return the response's body, optionally parsed as JSON
     *
     * @param boolean $bIsJSON Whether the body is JSON or not
     *
     * @return array|\stdClass|string|null
     */
    public function getBody($bIsJSON = true)
    {
        if ($bIsJSON) {
            return json_decode($this->oResponse->getBody());
        } else {
            return (string) $this->oResponse->getBody();
        }
    }
}