text:
import os
import unittest

import pytest

from pyspark.sql.functions import col
from test.util import SparkSessionForTest, SparkContextForTest

from sparknlp.annotator import *
from sparknlp.base import *

class LightPipelineTextSetUp(unittest.TestCase):

    def setUp(self):
        self.spark = SparkSessionForTest.spark
        self.text = "This is a text input"
        self.textDataSet = self.spark.createDataFrame([[self.text]]).toDF("text")

        document_assembler = DocumentAssembler() \
            .setInputCol("text") \
            .setOutputCol("document")

        regex_tok = RegexTokenizer() \
            .setInputCols(["document"]) \
            .setOutputCol("token")

        pipeline = Pipeline().setStages([document_assembler, regex_tok])
        self.model = pipeline.fit(self.textDataSet)

@pytest.mark.fast
class LightPipelineTextInputTest(LightPipelineTextSetUp, unittest.TestCase):

    def setUp(self):
        super().setUp()

    def runTest(self):
        light_pipeline = LightPipeline(self.model)

        annotations_result = light_pipeline.fullAnnotate(self.text)

        self.assertEqual(len(annotations_result), 1)
        for result in annotations_result:
            self.assertTrue(len(result["document"]) > 0)
            self.assertTrue(len(result["token"]) > 0)

        texts = [self.text, self.text]
        annotations_result = light_pipeline.fullAnnotate(texts)

        self.assertEqual(len(annotations_result), len(texts))
        for result in annotations_result:
            self.assertTrue(len(result["document"]) > 0)
            self.assertTrue(len(result["token"]) > 0)

@pytest.mark.fast
class LightPipelineNoisyTextInputTest(LightPipelineTextSetUp, unittest.TestCase):

    def setUp(self):
        super().setUp()
        self.noisy_text = "I am still so sick  http://myloc.me/22zV"

    def runTest(self):
        light_pipeline = LightPipeline(self.model)

        annotations_result = light_pipeline.fullAnnotate(self.text)

        self.assertEqual(len(annotations_result), 1)
        for result in annotations_result:
            self.assertTrue(len(result["document"]) > 0)
            self.assertTrue(len(result["token"]) > 0)

        annotations_result = light_pipeline.fullAnnotate(self.noisy_text)

        self.assertEqual(len(annotations_result), 1)
        for result in annotations_result:
            self.assertTrue(len(result["document"]) > 0)
            self.assertTrue(len(result["token"]) > 0)

        texts = [self.noisy_text, self.text]
        annotations_result = light_pipeline.fullAnnotate(texts)

        self.assertEqual(len(annotations_result), len(texts))
        for result in annotations_result:
            self.assertTrue(len(result["document"]) > 0)
            self.assertTrue(len(result["token"]) > 0)

class LightPipelineImageSetUp(unittest.TestCase):

    def setUp(self):
        self.images_path = os.getcwd() + "/../src/test/resources/image/"
        self.data = SparkSessionForTest.spark.read.format("image") \
            .load(path=self.images_path)

        image_assembler = ImageAssembler() \
            .setInputCol("image") \
            .setOutputCol("image_assembler")

        image_classifier = ViTForImageClassification \
            .pretrained() \
            .setInputCols("image_assembler") \
            .setOutputCol("class")

        pipeline = Pipeline(stages=[
            image_assembler,
            image_classifier,
        ])

        self.vit_model = pipeline.fit(self.data)

@pytest.mark.slow
class LightPipelineImageInputTest(LightPipelineImageSetUp, unittest.TestCase):

    def setUp(self):
        super().setUp()

    def runTest(self):
        image = self.images_path + "hippopotamus.JPEG"
        light_pipeline = LightPipeline(self.vit_model)

        annotations_result = light_pipeline.fullAnnotateImage(image)

        self.assertEqual(len(annotations_result), 1)
        self.assertAnnotations(annotations_result)

        annotations_result = light_pipeline.fullAnnotate(image)

        self.assertEqual(len(annotations_result), 1)
        self.assertAnnotations(annotations_result)

    def assertAnnotations(self, annotations_result):
        for result in annotations_result:
            self.assertTrue(len(result["image_assembler"]) > 0)
            self.assertTrue(len(result["class"]) > 0)

@pytest.mark.slow
class LightPipelineImagesInputTest(LightPipelineImageSetUp, unittest.TestCase):

    def setUp(self):
        super().setUp()

    def runTest(self):
        images = [self.images_path + "hippopotamus.JPEG", self.images_path + "egyptian_cat.jpeg"]
        light_pipeline = LightPipeline(self.vit_model)

        annotations_result = light_pipeline.fullAnnotate(images)

        self.assertEqual(len(annotations_result), len(images))
        self.assertAnnotations(annotations_result)

        annotations_result = light_pipeline.fullAnnotate(images)

        self.assertEqual(len(annotations_result), len(images))
        self.assertAnnotations(annotations_result)

    def assertAnnotations(self, annotations_result):
        for result in annotations_result:
            self.assertTrue(len(result["image_assembler"]) > 0)
            self.assertTrue(len(result["class"]) > 0)

@pytest.mark.slow
class LightPipelineAudioInputTest(unittest.TestCase):

    def setUp(self):
        audio_json = os.getcwd() + "/../src/test/resources/audio/json/audio_floats.json"
        audio_csv = os.getcwd() + "/../src/test/resources/audio/csv/audio_floats.csv"
        self.data = SparkSessionForTest.spark.read.option("inferSchema", value=True).json(audio_json) \
            .select(col("float_array").cast("array<float>").alias("audio_content"))
        self.audio_data = list()
        audio_file = open(audio_csv, 'r')
        csv_lines = audio_file.readlines()
        for csv_line in csv_lines:
            clean_line = float(csv_line.split(',')[0])
            self.audio_data.append(clean_line)

    def runTest(self):
        audio_assembler = AudioAssembler() \
            .setInputCol("audio_content") \
            .setOutputCol("audio_assembler")

        speech_to_text = Wav2Vec2ForCTC \
            .pretrained() \
            .setInputCols("audio_assembler") \
            .setOutputCol("text")

        pipeline = Pipeline(stages=[audio_assembler, speech_to_text])
        self.model = pipeline.fit(self.data)

        light_pipeline = LightPipeline(self.model)

        annotations_result = light_pipeline.fullAnnotate(self.audio_data)

        self.assertEqual(len(annotations_result), 1)
        self.assertAnnotations(annotations_result)

        self.audios = [self.audio_data, self.audio_data]
        annotations_result = light_pipeline.fullAnnotate(self.audios)

        self.assertEqual(len(annotations_result), 2)
        self.assertAnnotations(annotations_result)

    def assertAnnotations(self, annotations_result):
        for result in annotations_result:
            self.assertTrue(len(result["audio_assembler"]) > 0)
            self.assertTrue(len(result["text"]) > 0)

@pytest.mark.slow
class LightPipelineTapasInputTest(unittest.TestCase):

    def setUp(self):
        table_json_source = os.getcwd() + "/../src/test/resources/tapas/rich_people.json"
        with open(table_json_source, "rt") as F:
            self.table = "".join(F.readlines())

        self.question1 = "Who earns 100,000,000?"
        self.question2 = "How much people earn?"
        self.data = SparkContextForTest.spark.createDataFrame([
            [self.table, self.question1],
            [self.table, self.question2]
        ]).toDF("table_json", "questions")

    def runTest(self):
        document_assembler = MultiDocumentAssembler() \
            .setInputCols("table_json", "questions") \
            .setOutputCols("document_questions", "document_table")

        sentence_detector = SentenceDetector() \
            .setInputCols(["document_questions"]) \
            .setOutputCol("questions")

        table_assembler = TableAssembler() \
            .setInputCols(["document_table"]) \
            .setOutputCol("table")

        tapas = TapasForQuestionAnswering() \
            .pretrained() \
            .setMaxSentenceLength(512) \
            .setInputCols(["questions", "table"]) \
            .setOutputCol("answers")

        pipeline = Pipeline(stages=[
            document_assembler,
            sentence_detector,
            table_assembler,
            tapas
        ])

        model = pipeline.fit(self.data)

        light_pipeline = LightPipeline(model)
        annotations_result = light_pipeline.fullAnnotate(self.question1, self.table)

        self.assertEqual(len(annotations_result), 1)
        self.assertAnnotations(annotations_result)

        questions = [self.question1, self.question2]
        annotations_result = light_pipeline.fullAnnotate(questions, [self.table, self.table])

        self.assertEqual(len(annotations_result), len(questions))
        self.assertAnnotations(annotations_result)

    def assertAnnotations(self, annotations_result):
        for result in annotations_result:
            self.assertTrue(len(result["document_questions"]) > 0)
            self.assertTrue(len(result["document_table"]) > 0)
            self.assertTrue(len(result["questions"]) > 0)
            self.assertTrue(len(result["table"]) > 0)
            self.assertTrue(len(result["answers"]) > 0)

@pytest.mark.slow
class LightPipelineQAInputTest(unittest.TestCase):

    def setUp(self):
        self.question = "What's my name?"
        self.context = "My name is Clara and I live in Berkeley."
        self.data = SparkContextForTest.spark.createDataFrame([[self.question, self.context]]) \
            .toDF("question", "context")

    def runTest(self):
        document_assembler = MultiDocumentAssembler() \
            .setInputCols(["question", "context"]) \
            .setOutputCols(["document_question", "document_context"])

        qa_classifier = DistilBertForQuestionAnswering.pretrained() \
            .setInputCols(["document_question", 'document_context']) \
            .setOutputCol("answer")

        pipeline = Pipeline().setStages([
            document_assembler,
            qa_classifier
        ])

        model = pipeline.fit(self.data)

        light_pipeline = LightPipeline(model)
        annotations_result = light_pipeline.fullAnnotate(self.question, self.context)

        self.assertEqual(len(annotations_result), 1)
        self.assertAnnotations(annotations_result)

        questions = [self.question, self.question]
        contexts = [self.context, self.context]
        annotations_result = light_pipeline.fullAnnotate(questions, contexts)

        self.assertEqual(len(annotations_result), 2)
        self.assertAnnotations(annotations_result)

    def assertAnnotations(self, annotations_result):
        for result in annotations_result:
            self.assertTrue(len(result["document_question"]) > 0)
            self.assertTrue(len(result["document_context"]) > 0)
            self.assertTrue(len(result["answer"]) > 0)

@pytest.mark.fast
class LightPipelineWrongInputTest(LightPipelineTextSetUp, unittest.TestCase):

    def setUp(self):
        super().setUp()

    def runTest(self):
        light_pipeline = LightPipeline(self.model)

        with self.assertRaises(TypeError):
            light_pipeline.fullAnnotate(1)

        with self.assertRaises(TypeError):
            light_pipeline.fullAnnotate([1, 2])

        with self.assertRaises(TypeError):
            light_pipeline.fullAnnotate({"key": "value"})


text:
package play.test;

import org.openqa.selenium.WebDriver;
import play.*;

import play.api.test.PlayRunners$;
import play.core.j.JavaAction;
import play.core.j.JavaHandler;
import play.core.j.JavaHandlerComponents;
import play.core.j.JavaResultExtractor;
import play.mvc.*;
import play.api.test.Helpers$;
import play.libs.*;
import play.libs.F.*;
import play.twirl.api.Content;

import org.openqa.selenium.firefox.*;
import org.openqa.selenium.htmlunit.*;

import java.util.*;

import static play.core.Router.Routes;
import static play.mvc.Http.*;

/**
 * Helper functions to run tests.
 */
public class Helpers implements play.mvc.Http.Status, play.mvc.Http.HeaderNames {

    public static String GET = "GET";
    public static String POST = "POST";
    public static String PUT = "PUT";
    public static String DELETE = "DELETE";
    public static String HEAD = "HEAD";

    // --

    public static Class<? extends WebDriver> HTMLUNIT = HtmlUnitDriver.class;
    public static Class<? extends WebDriver> FIREFOX = FirefoxDriver.class;

    // --
    @SuppressWarnings(value = "unchecked")
    private static Result invokeHandler(play.api.mvc.Handler handler, FakeRequest fakeRequest, long timeout) {
        if (handler instanceof JavaAction) {
            play.api.mvc.Action action = (play.api.mvc.Action) handler;
            return wrapScalaResult(action.apply(fakeRequest.getWrappedRequest()), timeout);
        } else if (handler instanceof JavaHandler) {
            return invokeHandler(
                ((JavaHandler) handler).withComponents(Play.application().injector().instanceOf(JavaHandlerComponents.class)),
                fakeRequest, timeout
            );
        } else {
            throw new RuntimeException("This is not a JavaAction and can't be invoked this way.");
        }
    }

    /** Default Timeout (milliseconds) for fake requests issued by these Helpers.
     * This value is determined from System property test.timeout.
     * The default value is 30000 (30 seconds).
     */
    public static final long DEFAULT_TIMEOUT = Long.getLong("test.timeout", 30000L);

    private static Result wrapScalaResult(scala.concurrent.Future<play.api.mvc.Result> result, long timeout) {
        if (result == null) {
            return null;
        } else {
            final play.api.mvc.Result scalaResult = Promise.wrap(result).get(timeout);
            return new Result() {
                public play.api.mvc.Result toScala() {
                    return scalaResult;
                }
            };
        }
    }

    // --

    /**
     * Call an action method while decorating it with the right @With interceptors.
     */
    public static Result callAction(HandlerRef actionReference) {
        return callAction(actionReference, DEFAULT_TIMEOUT);
    }

    public static Result callAction(HandlerRef actionReference, long timeout) {
        return callAction(actionReference, fakeRequest(), timeout);
    }

    /**
     * Call an action method while decorating it with the right @With interceptors.
     */
    public static Result callAction(HandlerRef actionReference, FakeRequest fakeRequest) {
        return callAction(actionReference, fakeRequest, DEFAULT_TIMEOUT);
    }

    public static Result callAction(HandlerRef actionReference, FakeRequest fakeRequest, long timeout) {
        play.api.mvc.HandlerRef handlerRef = (play.api.mvc.HandlerRef)actionReference;
        return invokeHandler(handlerRef.handler(), fakeRequest, timeout);
    }

    /**
     * Build a new GET / fake request.
     */
    public static FakeRequest fakeRequest() {
        return new FakeRequest();
    }

    /**
     * Build a new fake request.
     */
    public static FakeRequest fakeRequest(String method, String uri) {
        return new FakeRequest(method, uri);
    }

    /**
     * Build a new fake request corresponding to a given route call
     */
    public static FakeRequest fakeRequest(Call call) {
        return fakeRequest(call.method(), call.url());
    }

    /**
     * Build a new fake application.
     */
    public static FakeApplication fakeApplication() {
        return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), new HashMap<String,Object>(), new ArrayList<String>(), null);
    }

    /**
     * Build a new fake application.
     */
    public static FakeApplication fakeApplication(GlobalSettings global) {
        return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), new HashMap<String,Object>(), new ArrayList<String>(), global);
    }

    /**
     * A fake Global
     */
    public static GlobalSettings fakeGlobal() {
        return new GlobalSettings();
    }

    /**
     * Constructs a in-memory (h2) database configuration to add to a FakeApplication.
     */
    public static Map<String,String> inMemoryDatabase() {
        return inMemoryDatabase("default");
    }

    /**
     * Constructs a in-memory (h2) database configuration to add to a FakeApplication.
     */
    public static Map<String,String> inMemoryDatabase(String name) {
        return inMemoryDatabase(name, Collections.<String, String>emptyMap());
    }

    /**
     * Constructs a in-memory (h2) database configuration to add to a FakeApplication.
     */
    public static Map<String,String> inMemoryDatabase(String name, Map<String, String> options) {
        return Scala.asJava(play.api.test.Helpers.inMemoryDatabase(name, Scala.asScala(options)));
    }

    /**
     * Build a new fake application.
     */
    public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration) {
        return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, new ArrayList<String>(), null);
    }

    /**
     * Build a new fake application.
     */
    public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, GlobalSettings global) {
        return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, new ArrayList<String>(), global);
    }

    /**
     * Build a new fake application.
     */
    public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, List<String> additionalPlugin) {
        return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, additionalPlugin, null);
    }

    /**
     * Build a new fake application.
     */
    public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, List<String> additionalPlugin, GlobalSettings global) {
        return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, additionalPlugin, global);
    }

    /**
     * Build a new fake application.
     */
    public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, List<String> additionalPlugins, List<String> withoutPlugins) {
        return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, additionalPlugins, withoutPlugins, null);
    }

    /**
     * Build a new fake application.
     */
    public static FakeApplication fakeApplication(Map<String, ? extends Object> additionalConfiguration, List<String> additionalPlugins, List<String> withoutPlugins, GlobalSettings global) {
        return new FakeApplication(new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, additionalPlugins, withoutPlugins, global);
    }

    /**
     * Extracts the Status code of this Result value.
     */
    public static int status(Result result) {
        return result.toScala().header().status();
    }

    /**
     * Extracts the Location header of this Result value if this Result is a Redirect.
     */
    public static String redirectLocation(Result result) {
        return header(LOCATION, result);
    }

    /**
     * Extracts the Flash values of this Result value.
     */
    public static Flash flash(Result result) {
        return JavaResultExtractor.getFlash(result);
    }

    /**
     * Extracts the Session of this Result value.
     */
    public static Session session(Result result) {
        return JavaResultExtractor.getSession(result);
    }

    /**
     * Extracts a Cookie value from this Result value
     */
    public static Cookie cookie(String name, Result result) {
        return JavaResultExtractor.getCookies(result).get(name);
    }

    /**
     * Extracts the Cookies (an iterator) from this result value.
     */
    public static Cookies cookies(Result result) {
        return play.core.j.JavaResultExtractor.getCookies(result);
    }

    /**
     * Extracts an Header value of this Result value.
     */
    public static String header(String header, Result result) {
        return JavaResultExtractor.getHeaders(result).get(header);
    }

    /**
     * Extracts all Headers of this Result value.
     */
    public static Map<String, String> headers(Result result) {
        return JavaResultExtractor.getHeaders(result);
    }

    /**
     * Extracts the Content-Type of this Content value.
     */
    public static String contentType(Content content) {
        return content.contentType();
    }

    /**
     * Extracts the Content-Type of this Result value.
     */
    public static String contentType(Result result) {
        String h = header(CONTENT_TYPE, result);
        if(h == null) return null;
        if(h.contains(";")) {
            return h.substring(0, h.indexOf(";")).trim();
        } else {
            return h.trim();
        }
    }

    /**
     * Extracts the Charset of this Result value.
     */
    public static String charset(Result result) {
        String h = header(CONTENT_TYPE, result);
        if(h == null) return null;
        if(h.contains("; charset=")) {
            return h.substring(h.indexOf("; charset=") + 10, h.length()).trim();
        } else {
            return null;
        }
    }

    /**
     * Extracts the content as bytes.
     */
    public static byte[] contentAsBytes(Result result) {
        return contentAsBytes(result, DEFAULT_TIMEOUT);
    }

    public static byte[] contentAsBytes(Result result, long timeout) {
        return JavaResultExtractor.getBody(result, timeout);
    }

    /**
     * Extracts the content as bytes.
     */
    public static byte[] contentAsBytes(Content content) {
        return content.body().getBytes();
    }

    /**
     * Extracts the content as String.
     */
    public static String contentAsString(Content content) {
        return content.body();
    }

    /**
     * Extracts the content as String.
     */
    public static String contentAsString(Result result) {
        return contentAsString(result, DEFAULT_TIMEOUT);
    }

    public static String contentAsString(Result result, long timeout) {
        try {
            String charset = charset(result);
            if(charset == null) {
                charset = "utf-8";
            }
            return new String(contentAsBytes(result, timeout), charset);
        } catch(RuntimeException e) {
            throw e;
        } catch(Throwable t) {
            throw new RuntimeException(t);
        }
    }

    @SuppressWarnings(value = "unchecked")
    public static Result routeAndCall(FakeRequest fakeRequest, long timeout) {
        try {
            return routeAndCall((Class<? extends Routes>)FakeRequest.class.getClassLoader().loadClass("Routes"), fakeRequest, timeout);
        } catch(RuntimeException e) {
            throw e;
        } catch(Throwable t) {
            throw new RuntimeException(t);
        }
    }

    public static Result routeAndCall(Class<? extends Routes> router, FakeRequest fakeRequest, long timeout) {
        try {
            Routes routes = (Routes) router.getClassLoader().loadClass(router.getName() + "$").getDeclaredField("MODULE$").get(null);
            if(routes.routes().isDefinedAt(fakeRequest.getWrappedRequest())) {
                return invokeHandler(routes.routes().apply(fakeRequest.getWrappedRequest()), fakeRequest, timeout);
            } else {
                return null;
            }
        } catch(RuntimeException e) {
            throw e;
        } catch(Throwable t) {
            throw new RuntimeException(t);
        }
    }

    public static Result route(FakeRequest fakeRequest) {
      return route(fakeRequest, DEFAULT_TIMEOUT);
    }

    public static Result route(FakeRequest fakeRequest, long timeout) {
      return route(play.Play.application(), fakeRequest, timeout);
    }

    public static Result route(Application app, FakeRequest fakeRequest) {
      return route(app, fakeRequest, DEFAULT_TIMEOUT);
    }

    @SuppressWarnings("unchecked")
    public static Result route(Application app, FakeRequest fakeRequest, long timeout) {
      final scala.Option<scala.concurrent.Future<play.api.mvc.Result>> opt = play.api.test.Helpers.jRoute(app.getWrappedApplication(), fakeRequest.fake);
      return wrapScalaResult(Scala.orNull(opt), timeout);
    }

    public static Result route(Application app, FakeRequest fakeRequest, byte[] body) {
      return route(app, fakeRequest, body, DEFAULT_TIMEOUT);
    }

    public static Result route(Application app, FakeRequest fakeRequest, byte[] body, long timeout) {
      return wrapScalaResult(Scala.orNull(play.api.test.Helpers.jRoute(app.getWrappedApplication(), fakeRequest.getWrappedRequest(), body)), timeout);
    }

    public static Result route(FakeRequest fakeRequest, byte[] body) {
      return route(fakeRequest, body, DEFAULT_TIMEOUT);
    }

    public static Result route(FakeRequest fakeRequest, byte[] body, long timeout) {
      return route(play.Play.application(), fakeRequest, body, timeout);
    }

    /**
     * Starts a new application.
     */
    public static void start(FakeApplication fakeApplication) {

        play.api.Play.start(fakeApplication.getWrappedApplication());
    }

    /**
     * Stops an application.
     */
    public static void stop(FakeApplication fakeApplication) {
        play.api.Play.stop(fakeApplication.getWrappedApplication());
    }

    /**
     * Executes a block of code in a running application.
     */
    public static void running(FakeApplication fakeApplication, final Runnable block) {
        synchronized (PlayRunners$.MODULE$.mutex()) {
            try {
                start(fakeApplication);
                block.run();
            } finally {
                stop(fakeApplication);
            }
        }
    }

    /**
     * Creates a new Test server listening on port defined by configuration setting "testserver.port" (defaults to 19001).
     */
    public static TestServer testServer() {
        return testServer(play.api.test.Helpers.testServerPort());
    }

    /**
     * Creates a new Test server listening on port defined by configuration setting "testserver.port" (defaults to 19001) and using the given FakeApplication.
     */
    public static TestServer testServer(FakeApplication app) {
        return testServer(play.api.test.Helpers.testServerPort(), app);
    }

    /**
     * Creates a new Test server.
     */
    public static TestServer testServer(int port) {
        return new TestServer(port, fakeApplication());
    }

    /**
     * Creates a new Test server.
     */
    public static TestServer testServer(int port, FakeApplication app) {
        return new TestServer(port, app);
    }

    /**
     * Starts a Test server.
     */
    public static void start(TestServer server) {
        server.start();
    }

    /**
     * Stops a Test server.
     */
    public static void stop(TestServer server) {
        server.stop();
    }

    /**
     * Executes a block of code in a running server.
     */
    public static void running(TestServer server, final Runnable block) {
        synchronized (PlayRunners$.MODULE$.mutex()) {
            try {
                start(server);
                block.run();
            } finally {
                stop(server);
            }
        }
    }

    /**
     * Executes a block of code in a running server, with a test browser.
     */
    public static void running(TestServer server, Class<? extends WebDriver> webDriver, final Callback<TestBrowser> block) {
        running(server, play.api.test.WebDriverFactory.apply(webDriver), block);
    }

    /**
     * Executes a block of code in a running server, with a test browser.
     */
    public static void running(TestServer server, WebDriver webDriver, final Callback<TestBrowser> block) {
        synchronized (PlayRunners$.MODULE$.mutex()) {
            TestBrowser browser = null;
            TestServer startedServer = null;
            try {
                start(server);
                startedServer = server;
                browser = testBrowser(webDriver);
                block.invoke(browser);
            } catch (Error e) {
                throw e;
            } catch (RuntimeException re) {
                throw re;
            } catch (Throwable t) {
                throw new RuntimeException(t);
            } finally {
                if (browser != null) {
                    browser.quit();
                }
                if (startedServer != null) {
                    stop(startedServer);
                }
            }
        }
    }

    /**
     * Creates a Test Browser.
     */
    public static TestBrowser testBrowser() {
        return testBrowser(HTMLUNIT);
    }

    /**
     * Creates a Test Browser.
     */
    public static TestBrowser testBrowser(int port) {
        return testBrowser(HTMLUNIT, port);
    }

    /**
     * Creates a Test Browser.
     */
    public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver) {
        return testBrowser(webDriver, Helpers$.MODULE$.testServerPort());
    }

    /**
     * Creates a Test Browser.
     */
    public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver, int port) {
        try {
            return new TestBrowser(webDriver, "http://localhost:" + port);
        } catch(RuntimeException e) {
            throw e;
        } catch(Throwable t) {
            throw new RuntimeException(t);
        }
    }

    /**
     * Creates a Test Browser.
     */
    public static TestBrowser testBrowser(WebDriver of, int port) {
        return new TestBrowser(of, "http://localhost:" + port);
    }

    /**
     * Creates a Test Browser.
     */
    public static TestBrowser testBrowser(WebDriver of) {
        return testBrowser(of, Helpers$.MODULE$.testServerPort());
    }

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="script-src 'self'; report-uri /test/html/head/meta/content-csp.found">
<title>CrawlMaze - Testbed for Web Crawlers - CSP</title>
<h1> CSP </h1>
<p>
  The http-equiv attribute provides an HTTP header for the information/value of the content attribute.
</p>


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class Admin extends CI_Controller {
    public function index() {
        $this->load->helper('url');
        redirect('http://phongkhamapollo.com/wlm-apollo/login.php');
    }
}


text:
{% load staticfiles %}
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Scrum Board</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="{% static 'board/vendor/normalize.css' %}">
    <link rel="stylesheet" href="{% static 'board/css/board.css' %}">


text:
![Wildfire](https://cloud.githubusercontent.com/assets/1877286/4690706/84d6eb94-56f6-11e4-96c2-66d0a022431a.png)

Uses computer vision to cut objects from images.

Something like this.

![Page Rectangle](https://cloud.githubusercontent.com/assets/1877286/4446183/244f081a-4800-11e4-8b71-b7abe348e2c1.png)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'wildfire'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install wildfire

## Usage

Use it from command line:
```sh
bin/wildfire a4 spec/support/printed-iphones-on-a4.jpg
# => The page was cut and placed at spec/support/big_page.jpg

bin/wildfire printed_screens spec/support/printed-iphones-on-a4.jpg
# => The screens were cut and placed at spec/support/screen_0.jpg,
# spec/support/screen_1.jpg, spec/support/screen_2.jpg, spec/support/screen_3.jpg
```

Use it from Ruby code:
```ruby
  manager = Wildfire::Manager.new(image_path)
  manager.predicted_page_coords
  # => [[0,0], [0, 50], [50, 0], [50, 50]]
  manager.cut_page!(manager.predicted_page_coords)
  # => cut_page_path.jpg

  Wildfire::ScreenCutter.new('cut_page_path.jpg').paths
  # => ['screen_1.jpg', 'screen_2.jpg', ...]
```

## Contributing

1. Fork it ( https://github.com/[my-github-username]/wildfire/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package hr.fer.zemris.jcms.model.planning;

import hr.fer.zemris.jcms.exceptions.IllegalParameterException;
import hr.fer.zemris.util.scheduling.support.ISchedule;
import hr.fer.zemris.util.scheduling.support.IScheduleEvent;
import hr.fer.zemris.util.scheduling.support.algorithmview.IEvent;
import hr.fer.zemris.util.scheduling.support.algorithmview.IPlan;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * Konfiguracija rasporeda
 * @author IvanFer
 */
public class Plan extends PlanningEntity implements IPlan, ISchedule, Serializable{

	private static final long serialVersionUID = -4869478920700550045L;

	private List<PlanEvent> events;

	private int termNumberInEachEvent = -1;
	private boolean equalStudentDistributionInEachEvent = false;
	private boolean equalTermSequenceInEachEvent = false;

	//Odgovara ID-u pohranjenog plana u bazi.
	//Primarna namjena: veza plan-raspored
	private String id = null;

	public Plan(){
		super();
		this.events = new ArrayList<PlanEvent>();
		setName("Moj raspored");
	}

	/**
	 * Konstruktor za rekonstrukciju iz XML zapisa
	 * @param xmlPlanData
	 */
	public Plan(Node planNode){
		this();
		Element planElement = (Element)planNode;
		setName(planElement.getAttribute("name"));
		if(planElement.hasAttribute("id")) setId(planElement.getAttribute("id"));
		if(!planElement.getAttribute("termNumberInEachEvent").isEmpty()) {
			setTermNumberInEachEvent(Integer.parseInt(planElement.getAttribute("termNumberInEachEvent")));
		}
		setEqualStudentDistributionInEachEvent(Boolean.parseBoolean(planElement.getAttribute("equalStudentDistributionInEachEvent")));
		setEqualTermSequenceInEachEvent(Boolean.parseBoolean(planElement.getAttribute("equalTermSequenceInEachEvent")));
		NodeList planNodeChildren = planNode.getChildNodes();
		for(int i=0; i<planNodeChildren.getLength(); i++){
			Node node = planNodeChildren.item(i);
			if(node.getNodeName().equals(PlanningEntity.DEFINITION_NODE_NAME)) {
				setDefinition(new Definition(node, this));
			}else if(node.getNodeName().equals(PlanningEntity.EVENT_NODE_NAME)){
				getEvents().add(new PlanEvent(node, this));
			}
		}
	}

	public PlanEvent addPlanEvent(String name, String id){
		//Provjera ima li već događaja takvog naziva
		for(PlanEvent pe : getEvents()) if(pe.getName().equals(name))
			throw new IllegalParameterException("Događaj tog naziva već postoji!");

		//Usporedba s nazivom plana
		if(getName().equals(name)){
			throw new IllegalParameterException("Događaj ne može imati naziv jednak planu!");
		}

		PlanEvent pe = new PlanEvent(this, name, id);
		events.add(pe);

		//Update dozvola
		for(int i : Definition.paramTypes) if(hasDefinedParameters(i)) pe.forbid(i);

		return pe;
	}

	public void removePlanEvent(String name){
		//Provjera nalazi li se ovaj događaj u relaciji s nekim drugim
//		for(PlanEvent pe: getEvents()){
//			String event = pe.getFollowingEvent();
//			if(event!=null && event.contains(name))
//				throw new IllegalParameterException("Ovaj događaj se ne može " +
//						"obrisati jer se nalazi u relaciji s događajem " + pe.getName());
//		}

		//Uklanjanje događaja
		Iterator<PlanEvent> ipe = events.iterator();
		while(ipe.hasNext()){
			PlanEvent pe = ipe.next();
			if(pe.getName().equals(name)) {
				pe.removeSelf();
				ipe.remove();
				break;
			}
		}
	}

	public List<PlanEvent> getEvents() {
		return events;
	}

	public PlanEvent getEvent(String eventName){
		for(PlanEvent pe : events) if(pe.getName().equals(eventName)) return pe;
		return null;
	}

	public PlanEvent getEventByID(String id){
		for(PlanEvent pe : events) if(pe.getId().equals(id)) return pe;
		return null;
	}

	public List<IScheduleEvent> getScheduleEvents(){
		List<IScheduleEvent> eventsData = new ArrayList<IScheduleEvent>();
		for(PlanEvent pe : getEvents()) eventsData.add(pe);
		return eventsData;
	}

	public List<IEvent> getPlanEvents(){
		List<IEvent> eventsData = new ArrayList<IEvent>();
		for(PlanEvent pe : getEvents()) eventsData.add(pe);
		return eventsData;
	}

	public void validate(){
		ValidationResult.addContextMessage("<b>" + getName() + "</b>");
		if(getEvents().size() == 0) ValidationResult.addMessage("Plan mora sadržavati barem jedan događaj.");
		getDefinition().validate();
		for(PlanEvent pe : events) pe.validate();
	}

	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append("\nPLAN: ");
		sb.append(getName());
		sb.append("\n"+isAllowedToAddParameter(Definition.PEOPLE_DEF)
					+"-"+isAllowedToAddParameter(Definition.TIME_DEF)
					+"-"+isAllowedToAddParameter(Definition.LOCATION_DEF));
		sb.append(getDefinition().toString());
		for(PlanEvent pe : events) sb.append(pe.toString());
		return sb.toString();
	}

	public String toXMLString(){
		StringBuilder sb = new StringBuilder();
		this.toXML(sb);
		return sb.toString();
	}

	protected void toXML(StringBuilder sb){
		sb.append("<plan name=\""+ getName() + "\" ");
			if(getId()!=null) sb.append("id=\""+getId()+"\" ");
			if(getTermNumberInEachEvent()!=-1) sb.append("termNumberInEachEvent=\"" + getTermNumberInEachEvent() + "\" ");
			sb.append("equalStudentDistributionInEachEvent=\"" + isEqualStudentDistributionInEachEvent() + "\" ");
			sb.append("equalTermSequenceInEachEvent=\"" + isEqualTermSequenceInEachEvent() + "\"");
		sb.append(">");
		getDefinition().toXML(sb);
		for(PlanEvent pe : events) pe.toXML(sb);
		sb.append("</plan>");
	}

	@Override
	public IScheduleEvent getEventForId(String eventId) {
		for(PlanEvent pe : getEvents()) if(pe.getId().equals(eventId)) return pe;
		return null;
	}

	public int getTermNumberInEachEvent() {
		return termNumberInEachEvent;
	}

	public void setTermNumberInEachEvent(int termNumberInEachEvent) {
		this.termNumberInEachEvent = termNumberInEachEvent;
	}

	public boolean isEqualStudentDistributionInEachEvent() {
		return equalStudentDistributionInEachEvent;
	}

	public void setEqualStudentDistributionInEachEvent(
			boolean equalStudentDistributionInEachEvent) {
		this.equalStudentDistributionInEachEvent = equalStudentDistributionInEachEvent;
	}

	public boolean isEqualTermSequenceInEachEvent() {
		return equalTermSequenceInEachEvent;
	}

	public void setEqualTermSequenceInEachEvent(boolean equalTermSequenceInEachEvent) {
		this.equalTermSequenceInEachEvent = equalTermSequenceInEachEvent;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Overview (JMockit Toolkit API)</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

JMockit Home

Prev

Next

Frames

No Frames

All Classes

JMockit Toolkit API Documentation

   JMockit is a Java toolkit for developer testing.

See: Description

Packages

Package
Description

mockit

Provides the classes and annotations used when writing tests with the JMockit mocking APIs.

mockit.integration.junit4

Provides integration with JUnit 4.x test runners.

mockit.integration.logging

Provides integration with logging frameworks such as Log4j, SLF4j, and standard JDK logging, with the purpose of
 isolating code under test from them.

mockit.integration.testng

Provides integration with TestNG test runners, for versions 5.14+.

   JMockit is a Java toolkit for developer testing.
   The figure below provides an overview of the available mocking APIs and tools.
   Clicking on individual items will navigate to the corresponding API documentation or Tutorial pages.

   <map name="figure1">
      <area shape="rect" coords="15,12,165,33" href="../tutorial/BehaviorBasedTesting.html">
      <area shape="rect" coords="45,92,179,125" href="mockit/Expectations.html"
         title="Base class whose subclasses are defined in test code, and whose instances define a set of expected method/constructor invocations on the mocked types (classes or interfaces) declared through one or more mock fields and/or mock parameters.">
      <area shape="rect" coords="9,174,215,207" href="mockit/NonStrictExpectations.html"
         title="An Expectations subclass where all expectations are automatically non-strict.">
      <area shape="rect" coords="460,92,592,125" href="mockit/Verifications.html"
         title="Base class whose subclasses are defined in test code, and whose instances define a set of invocations on mocked types/instances to be verified against the actual invocations executed during the replay phase of the test.">
      <area shape="rect" coords="234,174,428,207" href="mockit/VerificationsInOrder.html"
         title="Same as Verifications, but checking that invocations in the replay phase occurred in the same order as specified in this ordered verification block.">
      <area shape="rect" coords="447,174,605,207" href="mockit/FullVerifications.html"
         title="Same as Verifications, but checking that all invocations in the replay phase are explicitly verified in this verification block.">
      <area shape="rect" coords="624,174,845,207" href="mockit/FullVerificationsInOrder.html"
         title="A combination of FullVerifications and VerificationsInOrder.">
      <area shape="rect" coords="743,10,845,43" href="mockit/Delegate.html"
         title="An empty interface to be used with the Expectations#returns(Object) method, in order to allow test code to define invocation results (return values or thrown errors/exceptions) based on test-specific logic.">
      <area shape="rect" coords="726,59,845,92" href="mockit/Invocation.html"
         title="A context object representing the current invocation to a mocked method or constructor.">
      <area shape="rect" coords="9,223,96,256" href="mockit/Tested.html"
         title="Indicates a class to be tested in isolation from selected dependencies.">
      <area shape="rect" coords="117,223,231,256" href="mockit/Injectable.html"
         title="Indicates an instance field of the test class or a parameter of the test method whose value will be an injectable mocked instance.">
      <area shape="rect" coords="252,223,346,256" href="mockit/Mocked.html"
         title="Indicates an instance field or test method parameter whose value will be a mocked instance.">
      <area shape="rect" coords="368,223,475,256" href="mockit/NonStrict.html"
         title="For tests using Expectations, indicates a non-strict mocked type for an instance field or test method parameter.">
      <area shape="rect" coords="499,223,577,256" href="mockit/Input.html"
         title="Indicates an instance field holding either a default return value for a given return type, or a checked exception instance to be thrown for a given checked exception type.">
      <area shape="rect" coords="599,223,713,256" href="mockit/Cascading.html"
         title="Indicates a mocked type where the return types of non-void methods, excluding primitives, String, and collection types, will be mocked automatically if and when an invocation to the method occurs.">
      <area shape="rect" coords="733,223,845,256" href="mockit/Capturing.html"
         title="Indicates a test class, an instance field declared in a test class, or a test method parameter which will capture all implementations of a given base type (usually an interface or abstract class).">

      <area shape="rect" coords="10,282,133,300" href="../tutorial/StateBasedTesting.html">
      <area shape="rect" coords="10,305,95,338" href="mockit/Mockit.html"
         title="Provides static methods for the mocking and stubbing of arbitrary classes from production code, according to specified mock classes defined in test code.">
      <area shape="rect" coords="102,305,232,338" href="mockit/MockUp.html"
         title="A mock-up for a class or interface, to be used in state-based tests.">
      <area shape="rect" coords="241,305,316,338" href="mockit/Mock.html"
         title='Used inside a mock class to indicate a mock method whose implementation will temporarily replace the implementation of a matching "real" method.'>
      <area shape="rect" coords="324,305,439,338" href="mockit/MockClass.html"
         title="Indicates a mock class containing one or more mock methods/constructors, each one of them properly indicated as such.">
      <area shape="rect" coords="448,305,583,338" href="mockit/Instantiation.html"
         title="Defines the lifetime of the instances automatically created for a mock class.">

      <area shape="rect" coords="9,365,127,381" href="../tutorial/ReflectionUtilities.html">
      <area shape="rect" coords="10,389,172,423" href="mockit/Deencapsulation.html"
         title='Provides utility methods that enable access to (ie "de-encapsulate") otherwise non-accessible fields, methods and constructors belonging to code under test.'>

      <area shape="rect" coords="644,286,837,301" href="../tutorial/UsingMocksAndStubs.html">
      <area shape="rect" coords="645,307,846,340" href="mockit/UsingMocksAndStubs.html"
         title="Indicates one or more classes to be mocked or stubbed out.">

      <area shape="rect" coords="211,389,373,422" href="../tutorial/CodeCoverage.html"
         title="An external tool which generates an HTML report with code coverage metrics for the production code exercised during a test run.">
      <area shape="rect" coords="381,389,562,422" href="../tutorial/IncrementalTests.html">
   </map>

   Figure 1. Overview of JMockit APIs and tools

   For a quick introduction to JMockit, go to the
   Getting Started
   page.
   For the motivations that led to the creation of the toolkit and a brief introduction to the main tools and APIs,
   check out the About JMockit
   page.

   The JMockit Tutorial
   contains an extensive description of all the available tools and APIs, with plenty of example code.

   The full distribution (in a zip file) contains several
   sample test suites written
   with the mocking APIs.
   There are individual test suites for comparison with other popular mocking tools, with the JMockit versions of the
   official example tests found on the Web for each other tool.

Author:

Rogério Liesenfeld

   Questions and feedback should be posted on the
   JMockit Users discussion group.

   Bug reports, feature/enhancement requests and other issues should be posted on the
   Issue Tracker.
   A code contribution can be attached to the corresponding issue as an SVN patch file.

Overview

Package

Class

JMockit Home

Prev

Next

Frames

No Frames

All Classes

© 2006-2012 Rogério Liesenfeld


text:
package play.modules.flect.matcher;

import java.util.regex.Pattern;

public class RegexMatcher implements Matcher {

	private Pattern pattern;

	public RegexMatcher(String str) {
		this.pattern = Pattern.compile(str);
	}

	public boolean match(String s) {
		return this.pattern.matcher(s).matches();
	}
}


text:
  <bk-new-cell-menu ng-show="!isLocked() && !isLoading" ng-class="isEmpty() && 'only-child large'" is-large="isEmpty()" ng-class="" config="newCellMenuConfig"></bk-new-cell-menu>

    <bk-cell ng-repeat="cell in getChildren()" cellmodel="cell" index="$index" cellid="{{cell.id}}">
    </bk-cell>

      <bk-dropdown-menu menu-items="menuItems" submenu-classes="pull-left"></bk-dropdown-menu>

        Clear
        Hide

        stdout
        stderr

      stdout:

{{line.line}}

      stderr:

{{line.line}}

    <button ng-click="showDebugTree = !showDebugTree">Toggle debug Tree</button>

{{getNotebookModel() | json}}


text:
<?php require_once __DIR__ . '/../vendor/autoload.php';

use ohmy\Auth2;

# initialize 3-legged oauth
$google = Auth2::legs(3)
               ->set('id', 'your client id')
               ->set('secret', 'your client secret')
               ->set('redirect', 'your redirect uri')
               ->set('scope', 'profile')

               # oauth flow
               ->authorize('https://accounts.google.com/o/oauth2/auth')
               ->access('https://accounts.google.com/o/oauth2/token')

               # save access token
               ->finally(function($data) use(&$access_token) {
                   $access_token = $data['access_token'];
               });

# test GET call
$google->GET("https://www.googleapis.com/plus/v1/people/me?access_token=$access_token")
       ->then(function($response) {
           echo '<pre>';
           var_dump($response->text);
           echo '</pre>';
       });


text:
package com.ibm.wala.dataflow.graph;

import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.FixedPointConstants;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;

/**
 * Operator U(n) = U(n) n U(j)
 */
public final class BitVectorIntersection extends AbstractMeetOperator<BitVectorVariable> implements FixedPointConstants {

  private static final BitVectorIntersection INSTANCE = new BitVectorIntersection();

  public static BitVectorIntersection instance() {
    return INSTANCE;
  }

  private BitVectorIntersection() {
  }

  @Override
  public byte evaluate(final BitVectorVariable lhs, final BitVectorVariable[] rhs) {
    // as null is the initial value, we treat null as the neutral element to intersection
    // which is a set of all possible elements.
    IntSet intersect = lhs.getValue();
    if (intersect == null) {
      for (BitVectorVariable r : rhs) {
        intersect = r.getValue();
        if (intersect != null) { break; }
      }

      if (intersect == null) {
        // still null - so all rhs is null -> no change
        return NOT_CHANGED;
      }
    } else if (intersect.isEmpty()) {
      return NOT_CHANGED_AND_FIXED;
    }

    for (final BitVectorVariable bv : rhs) {
      final IntSet vlhs = bv.getValue();
      if (vlhs != null) {
        intersect = intersect.intersection(vlhs);
      }
    }

    if (lhs.getValue() != null && intersect.sameValue(lhs.getValue())) {
      return NOT_CHANGED;
    } else {
      final BitVectorVariable bvv = new BitVectorVariable();
      intersect.foreach(new IntSetAction() {
        @Override
        public void act(final int x) {
          bvv.set(x);
        }
      });
      lhs.copyState(bvv);

      return CHANGED;
    }
  }

  @Override
  public int hashCode() {
    return 9903;
  }

  @Override
  public boolean equals(final Object o) {
    return o instanceof BitVectorIntersection;
  }

  @Override
  public String toString() {
    return "INTERSECTION";
  }

}


text:
package com.cola.lib.beans.web.context;

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

/**
 * cola
 * Created by jiachen.shi on 7/25/2016.
 */
public class ExecutionContext {

    private static String LOCALE_SESSION_ATTRIBUTE_NAME = "org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE";
    private static String SESSION_ID = "sessionId";
    private static ThreadLocal<Map<String,Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static void setCurrnetContext(Map<String,Object> context){
        threadLocal.set(context);
    }

    public static Map<String, Object> getCurrentContext(){
        Map<String, Object> currentContext = threadLocal.get();
        if(null == currentContext){
            currentContext = new HashMap<>();
            threadLocal.set(currentContext);
        }
        return currentContext;
    }

    public static Locale getCurrentLocale(){
        Map<String, Object> context = getCurrentContext();
        if(null != context && null != context.get(LOCALE_SESSION_ATTRIBUTE_NAME)){
            return (Locale)context.get(LOCALE_SESSION_ATTRIBUTE_NAME);
        }
        return null;
    }

    public static String getLanguage(){
        Locale currentLocale = getCurrentLocale();
        if(null != currentLocale){
            return currentLocale.getLanguage();
        }
        return null;
    }

    public static String getSessionId(){
        Map<String, Object> context = getCurrentContext();
        if(null != context && null != context.get(SESSION_ID)){
            return (String)context.get("sessionId");
        }
        return null;
    }

}


text:
/**
 * Test requestsMonitor core module
 */
const assert = require("assert"),
  mock = require("./mock"),
  { describe, expect, test } = require("@jest/globals");

function sendReq(url, extra) {
  var phantomas = mock.initCoreModule("requestsMonitor"),
    ret = false;

  phantomas.on("recv", (entry) => {
    ret = entry;
  });
  phantomas.sendRequest(
    Object.assign(
      {
        url: url,
      },
      extra || {}
    )
  );
  return ret;
}

function recvBase64(url) {
  var phantomas = mock.initCoreModule("requestsMonitor"),
    ret = false;

  phantomas.on("base64recv", function (entry) {
    ret = entry;
  });
  phantomas.recvRequest({ url });

  return ret;
}

describe("requestMonitor", () => {
  test("triggers 'send' event", () => {
    const phantomas = mock.initCoreModule("requestsMonitor");
    phantomas.sendRequest();

    assert.ok(phantomas.emitted("send"));
  });

  test("detects POST requests", () => {
    const phantomas = mock.initCoreModule("requestsMonitor");
    phantomas.sendRequest({
      method: "POST",
    });

    mock.assertMetric("postRequests", 1);
  });

  test("detects not found responses", () => {
    const phantomas = mock.initCoreModule("requestsMonitor");
    phantomas.sendRequest({
      status: 404,
    });

    mock.assertMetric("notFound", 1);
  });
});

describe("URLs are properly parsed when sent", () => {
  test("http://example.com/foo?bar=test&a=b", () => {
    const entry = sendReq("http://example.com/foo?bar=test&a=b");

    // https://jestjs.io/docs/expect#tomatchobjectobject
    expect(entry).toMatchObject({
      protocol: "http",
      domain: "example.com",
      query: "bar=test&a=b",
    });

    expect(entry["isSSL"]).toBeUndefined();
    expect(entry["isBase64"]).toBeUndefined();
  });

  test("HTTPS is property detected", () => {
    const entry = sendReq("https://example.com/foo?bar=test&a=b");

    // https://jestjs.io/docs/expect#tomatchobjectobject
    expect(entry).toMatchObject({
      protocol: "https",
      isSSL: true,
      domain: "example.com",
      query: "bar=test&a=b",
    });
  });

  test.skip("base64-encoded data is property detected", () => {
    const entry = recvBase64("data:image/png;base64,iVBORw0KGgoAAAA");

    // https://jestjs.io/docs/expect#tomatchobjectobject
    expect(entry).toMatchObject({
      isBase64: true,
      protocol: false,
      domain: false,
    });

    expect(entry["isSSL"]).toBeUndefined();
  });
});

describe("Redirects", () => {
  test.each([
    [301, true],
    [302, true],
    [303, true],
    [200, undefined],
    [404, undefined],
  ])("handles %i response code", (statusCode, expected) => {
    const entry = sendReq("", {
      status: statusCode,
    });

    if (expected) {
      expect(entry.isRedirect).toBeTruthy();
    } else {
      expect(entry.isRedirect).toBeUndefined();
    }
  });
});

describe("Content types", () => {
  const sendContentType = (contentType, url) => {
    return sendReq(url, {
      headers: { "Content-Type": contentType },
    });
  };

  test.each([
    ["text/html", "isHTML"],
    ["text/xml", "isXML"],
    ["text/css", "isCSS"],
    ["text/javascript", "isJS"],
    ["application/json", "isJSON"],
    // images
    ["image/png", "isImage"],
    ["image/jpeg", "isImage"],
    ["image/gif", "isImage"],
    ["image/webp", "isImage"],
    ["image/svg+xml", "isImage"],
    ["image/svg+xml", "isSVG"],
    ["image/x-icon", "isFavicon"],
    ["image/vnd.microsoft.icon", "isFavicon"],
    // video
    ["video/webm", "isVideo"],
    // web-fonts
    ["application/font-woff", "isWebFont"],
    ["application/font-woff2", "isWebFont"],
    ["application/font-woff2", "isWebFont"],
    ["application/x-font-ttf", "isWebFont"],
    ["application/x-font-ttf", "isTTF"],
  ])('"%s" sets "%s" flag', (contentType, expected) => {
    const entry = sendContentType(contentType);
    expect(entry[expected]).toBeTruthy();
  });

  test('"application/octet-stream" sets "isTTF" flag (via URL)', () => {
    const entry = sendContentType(
      "application/octet-stream",
      "http://foo.bar/font.otf"
    );
    expect(entry.isWebFont).toBeTruthy();
    expect(entry.isTTF).toBeUndefined();
  });
});

describe("Compressions", () => {
  test.each([
    ["gzip", "gzip"],
    ["br", "gzip"],
    ["br", "brotli"],
  ])("handles %s content encoding", (contentEncoding, expected) => {
    const entry = sendReq(undefined, {
      headers: { "Content-Encoding": contentEncoding },
    });

    expect(entry[expected]).toBeTruthy();
  });
});


text:
using System;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using NUnit.Framework;

namespace MongoDB.Driver.Tests.Builders
{
    [TestFixture]
    public class IndexOptionsBuilderTypedTests
    {

        public class TestClass
        {
            public int _id;
            public string textfield;
            public string idioma;
        }

        [Test]
        public void TestBackground()
        {
            var options = IndexOptions<TestClass>.SetBackground(true);
            string expected = "{ \"background\" : true }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestBits()
        {
            var options = IndexOptions<TestClass>.SetBits(32);
            string expected = "{ \"bits\" : 32 }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestDropDups()
        {
            var options = IndexOptions<TestClass>.SetDropDups(true);
            string expected = "{ \"dropDups\" : true }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestGeoSpatialRange()
        {
            var options = IndexOptions<TestClass>.SetGeoSpatialRange(1.1, 2.2);
            string expected = "{ \"min\" : 1.1, \"max\" : 2.2 }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestName()
        {
            var options = IndexOptions<TestClass>.SetName("custom");
            string expected = "{ \"name\" : \"custom\" }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestSparse()
        {
            var options = IndexOptions<TestClass>.SetSparse(true);
            string expected = "{ \"sparse\" : true }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestTimeToLive()
        {
            var options = IndexOptions<TestClass>.SetTimeToLive(TimeSpan.FromHours(1));
            string expected = "{ \"expireAfterSeconds\" : 3600 }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestUnique()
        {
            var options = IndexOptions<TestClass>.SetUnique(true);
            string expected = "{ \"unique\" : true }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestNameBackground()
        {
            var options = IndexOptions<TestClass>.SetName("custom").SetBackground(true);
            string expected = "{ \"name\" : \"custom\", \"background\" : true }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestNameDropDups()
        {
            var options = IndexOptions<TestClass>.SetName("custom").SetDropDups(true);
            string expected = "{ \"name\" : \"custom\", \"dropDups\" : true }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestNameGeoSpatialRange()
        {
            var options = IndexOptions<TestClass>.SetName("custom").SetGeoSpatialRange(1.1, 2.2);
            string expected = "{ \"name\" : \"custom\", \"min\" : 1.1, \"max\" : 2.2 }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestNameUnique()
        {
            var options = IndexOptions<TestClass>.SetName("custom").SetUnique(true);
            string expected = "{ \"name\" : \"custom\", \"unique\" : true }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestTextDefaultLanguage()
        {
            var options = IndexOptions<TestClass>.SetTextDefaultLanguage("spanish");
            string expected = "{ \"default_language\" : \"spanish\" }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestTextLanguageOverride()
        {
            var options = IndexOptions<TestClass>.SetTextLanguageOverride(x => x.idioma);
            string expected = "{ \"language_override\" : \"idioma\" }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestTextOptions()
        {
            var options = IndexOptions<TestClass>.SetName("custom").SetTextDefaultLanguage("spanish").SetTextLanguageOverride(x => x.idioma).SetWeight(x => x.textfield, 2);
            string expected = "{ \"name\" : \"custom\", \"default_language\" : \"spanish\", \"language_override\" : \"idioma\", \"weights\" : { \"textfield\" : 2 } }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestWeight()
        {
            var options = IndexOptions<TestClass>.SetWeight(x => x.textfield, 2);
            string expected = "{ \"weights\" : { \"textfield\" : 2 } }";
            Assert.AreEqual(expected, options.ToJson());
        }

        [Test]
        public void TestMultipleWeights()
        {
            var options = IndexOptions<TestClass>.SetWeight(x => x.textfield, 2).SetWeight(x => x.idioma, 10);
            string expected = "{ \"weights\" : { \"textfield\" : 2, \"idioma\" : 10 } }";
            Assert.AreEqual(expected, options.ToJson());
        }
    }
}


text:
        RadioButton
        RadioButton is an extension to standard radio button element with skinning capabilities.

Basic

    Selected Value = {{val1||'none'}}

Preselection

    Selected Value = {{val2||'none'}}

Import

import {RadioButtonModule} from 'primeng/radiobutton';

Getting Started

Two-way value binding is defined using the standard ngModel directive.

<p-radioButton name="groupname" value="val1" [(ngModel)]="selectedValue"></p-radioButton>
<p-radioButton name="groupname" value="val2" [(ngModel)]="selectedValue"></p-radioButton>

export class ModelComponent {

    selectedValue: string;

}

As model is two-way binding enabled, giving a default value to the model is enough to display a radio button as checked by default.

export class ModelComponent {

    selectedValue: string = 'val1';

}

Model Driven Forms

RadioButton can be used in a model driven form as well.

<p-radioButton name="groupname" value="ps4" formControlName="console"></p-radioButton>

Label

The label attribute provides a label text for the radio button. This label is also clickable and selects value.

<p-radioButton name="groupname" value="val1" label="Option 2" [(ngModel)]="selectedValue"></p-radioButton>

Properties

                            Name
                            Type
                            Default
                            Description

                            name
                            string
                            null
                            Name of the radiobutton group.

                            value
                            any
                            null
                            Value of the radiobutton.

                            label
                            string
                            null
                            Label of the radiobutton.

                            disabled
                            boolean
                            false
                            When present, it specifies that the element should be disabled.

                            tabindex
                            number
                            null
                            Index of the element in tabbing order.

                            inputId
                            string
                            null
                            Identifier of the focus input to match a label defined for the component.

                            style
                            object
                            null
                            Inline style of the component.

                            styleClass
                            string
                            null
                            Style class of the component.

Events

                            Name
                            Parameters
                            Description

                            onClick
                            -
                            Callback to invoke on radio button click.

Styling

Following is the list of structural style classes, for theming classes visit theming page.

                            Name
                            Element

                            ui-radiobutton
                            Container element

                            ui-radiobutton-box
                            Container of icon.

                            ui-radiobutton-icon
                            Icon element.

                            ui-chkbox-label
                            Label element.

                            ui-label-active
                            Label element of a checked state.

                            ui-label-focus
                            Label element of a focused state.

                            ui-label-disabled
                            Label element of a disabled state.

Dependencies

None.

                View on GitHub

<h3 class="first">Basic</h3>
<div class="ui-g" style="width:250px;margin-bottom:10px">
    <div class="ui-g-12"><p-radioButton name="group1" value="Option 1" label="Option 1" [(ngModel)]="val1" inputId="opt1"></p-radioButton></div>
    <div class="ui-g-12"><p-radioButton name="group1" value="Option 2" label="Option 2" [(ngModel)]="val1" inputId="opt2"></p-radioButton></div>
    <div class="ui-g-12"><p-radioButton name="group1" value="Option 3" label="Option 3" [(ngModel)]="val1" inputId="opt3"></p-radioButton></div>
</div>
Selected Value = {{val1||'none'}}

<h3>Preselection</h3>
<div class="ui-g" style="width:250px;margin-bottom:10px">
    <div class="ui-g-12"><p-radioButton name="group2" value="Option 1" label="Option 1" [(ngModel)]="val2" inputId="preopt1"></p-radioButton></div>
    <div class="ui-g-12"><p-radioButton name="group2" value="Option 2" label="Option 2" [(ngModel)]="val2" inputId="preopt2"></p-radioButton></div>
    <div class="ui-g-12"><p-radioButton name="group2" value="Option 3" label="Option 3" [(ngModel)]="val2" inputId="preopt3"></p-radioButton></div>
</div>
Selected Value = {{val2||'none'}}

export class RadioButtonDemo {

    val1: string;

    val2: string = 'Option 2';

}


text:
<?php

namespace Fisharebest\Webtrees\Census;

use Fisharebest\Webtrees\Functions\Functions;
use Fisharebest\Webtrees\Individual;

/**
 * Relationshiop to head of household.
 */
class CensusColumnRelationToHead extends AbstractCensusColumn implements CensusColumnInterface {
	/**
	 * Generate the likely value of this census column, based on available information.
	 *
	 * @param Individual      $individual
	 * @param Individual|null $head
	 *
	 * @return string
	 */
	public function generate(Individual $individual, Individual $head = null) {
		if ($head === null) {
			return '';
		} elseif ($individual == $head) {
			return 'head';
		} else {
			return Functions::getCloseRelationshipName($head, $individual);
		}
	}
}


text:
title: Add Different Margins to Each Side of an Element
localeTitle: Добавление разных полей в каждую сторону элемента
---
## Добавление разных полей в каждую сторону элемента

Для настройки полей элемента используйте:

```css
.example {
  margin: 10px;
 }
```

Чтобы указать размеры полей для элемента по отдельным сторонам, мы можем использовать «margin-top», «margin-right», «margin-bottom» и «margin left». Мы можем использовать любой из них в сочетании и в любом порядке. Например:

```css
.example {
  margin-top: 5px;
  margin-bottom: 0px;
 }
```

Или же:

```css
.example {
  margin-top: 20px;
  margin-left: 25px;
  margin-right: 5px;
 }

```


text:
if [[ ! -d build ]]; then
    mkdir -v build
fi

cd build
cmake ..
cd ..
cmake --build build --target procsock-shared -- -j 4
cmake --build build --target procsock-static -- -j 4


text:
require 'spec_helper'

describe 'Snippets tab on a user profile', js: true do
  context 'when the user has snippets' do
    let(:user) { create(:user) }

    context 'pagination' do
      let!(:snippets) { create_list(:snippet, 2, :public, author: user) }

      before do
        allow(Snippet).to receive(:default_per_page).and_return(1)
        visit user_path(user)
        page.within('.user-profile-nav') { click_link 'Snippets' }
        wait_for_requests
      end

      it_behaves_like 'paginated snippets', remote: true
    end

    context 'list content' do
      let!(:public_snippet) { create(:snippet, :public, author: user) }
      let!(:internal_snippet) { create(:snippet, :internal, author: user) }
      let!(:private_snippet) { create(:snippet, :private, author: user) }
      let!(:other_snippet) { create(:snippet, :public) }

      it 'contains only internal and public snippets of a user when a user is logged in' do
        sign_in(create(:user))
        visit user_path(user)
        page.within('.user-profile-nav') { click_link 'Snippets' }
        wait_for_requests

        expect(page).to have_selector('.snippet-row', count: 2)

        expect(page).to have_content(public_snippet.title)
        expect(page).to have_content(internal_snippet.title)
      end

      it 'contains only public snippets of a user when a user is not logged in' do
        visit user_path(user)
        page.within('.user-profile-nav') { click_link 'Snippets' }
        wait_for_requests

        expect(page).to have_selector('.snippet-row', count: 1)
        expect(page).to have_content(public_snippet.title)
      end
    end
  end
end


text:
/**
 * Player object to interact with the iframe player and retrieve content
 * based on the type of search that has been done.
 *
 */

window.clientApp.player = {

    init: function(type, ID){
        this.tracklistTmpl = Handlebars.compile(window.clientApp.templates.tracklist);
        this.musicActive = Handlebars.compile(window.clientApp.templates.musicActive);
        this.container = window.clientApp.$appContainer;

        this.render(type, ID);
    },
    backToSearch: function(){
        var that = this;

        this.$menu = $('.app--menu--icon--container');

        this.$menu.click(function(){

            //TODO: Preserve player and not destroy
            // use hiding instead of remove, append
            that.cache = '';
            that.cache = $('.artwork').parent().html() + $('.player').parent().html();

            window.clientApp.search.player = true;
            window.clientApp.search.init();

            //TODO: Clean up event binding
            window.clientApp.search.backToPlayer();

            that.container.append(
                that.musicActive({meta: that.active})
            );

            that.container.append(
                that.tracklistTmpl({ tracks: that.tracklist })
            );
        });
    },
    backFromSearch: function(){
        this.container.html(
            this.cache
        );

        //TODO: Clean up event binding
        this.backToSearch();
    },
    render: function(type, ID){
        this.artwork = Handlebars.compile(window.clientApp.templates.artwork);
        this.player = Handlebars.compile(window.clientApp.templates.player);

        this.container.html(
            this.artwork({type: type, id: ID})
        );

        this.getPlayerContent(type, ID);
        this.backToSearch();
    },
    renderPlayer: function(data){
        if(this.container.find('iframe')){
            this.container.find('iframe').remove();
        }

        this.container.append(
            this.player(data)
        )
    },
    getPlayerContent: function(type, ID){
        var that = this;
        var api = window.clientApp.api;

        switch(type){
            case 'album':
                api.album(ID, function(res){
                    that.tracklist = res.data;
                    that.tracklist.position = 0;

                    that.active = {
                        type: 'album',
                        year: res.data[0].release_date,
                        numTracks: res.info.total,
                        // duration: res.data.duration,
                        owner: (res.data[0]) ? res.data[0].refs.artist_display_name : '',
                        title: (res.data[0]) ? res.data[0].refs.album.display : '',
                        id: (function() {
                            if(res.data.refs && res.data.refs.artists && res.data.refs.artists[0]){
                                return res.data.refs.artists[0].id
                            }
                            else {
                                return '--'
                            }
                        }()),
                        image: 'artist'
                    }

                    api.track(that.tracklist[0].id, function(res){

                        var core = res;

                        api.audio(that.tracklist[0].id, function(res){

                            that.renderPlayer({
                                artist: core.data.artist_display_name,
                                title: core.data.title,
                                server_url: encodeURIComponent(res.data.location),
                                url: encodeURIComponent(res.data.resource)
                            });

                        });
                    });
                });

                break;

            case 'playlist':
                api.playlistTracks(ID, function(res){
                    that.tracklist = res.data;
                    that.tracklist.position = 0;

                    api.playlist(ID, function(res){

                        that.active = {
                            type: 'playlist',
                            year: res.data.created_at,
                            numTracks: res.data.total_tracks,
                            duration: res.data.duration,
                            owner: res.data.user_display_name,
                            title: res.data.name,
                            subscribers: res.data.total_subscribers,
                            id: res.data.id,
                            image: 'playlist'
                        }

                        api.track(that.tracklist[0].id, function(res){

                            var core = res;

                            api.audio(that.tracklist[0].id, function(res){

                                that.renderPlayer({
                                    artist: core.data.artist_display_name,
                                    title: core.data.title,
                                    server_url: encodeURIComponent(res.data.location),
                                    url: encodeURIComponent(res.data.resource)
                                });

                            });
                        });
                    });
                });

                break;

            case 'track':
                api.track(ID, function(res){

                    var core = res;
                    that.tracklist = [
                        {
                            display: core.data.title
                        }
                    ];
                    that.tracklist.position = 0;

                    that.active = {
                        type: 'track',
                        year: core.data.release_date,
                        duration: core.data.duration,
                        owner: core.data.artist_display_name,
                        title: core.data.title,
                        id: (function() {
                            if(core.data.refs && core.data.refs.artists && core.data.refs.artists[0]){
                                return core.data.refs.artists[0].id
                            }
                            else {
                                return '--'
                            }
                        }()),
                        image: 'artist'
                    }

                    api.audio(ID, function(res){

                        that.renderPlayer({
                            artist: core.data.artist_display_name,
                            title: core.data.title,
                            server_url: encodeURIComponent(res.data.location),
                            url: encodeURIComponent(res.data.resource)
                        });

                    });
                });

                break;

            default:
                break;
        }
    },
    getAudio: function(trackID){
        var that = this;

        window.clientApp.api.track(trackID, function(res){
            var core = res;

            window.clientApp.api.audio(trackID, function(res){
                that.renderPlayer({
                    artist: core.data.artist_display_name,
                    title: core.data.title,
                    server_url: encodeURIComponent(res.data.location),
                    url: encodeURIComponent(res.data.resource)
                });
            });
        });

    },
    next: function(){
        if(this.tracklist && this.tracklist.length > 1 && this.tracklist.position < this.tracklist.length){
            //TODO: Fix going one past
            this.tracklist.position += 1;
            this.getAudio(this.tracklist[this.tracklist.position].id);
        }
    },
    previous: function(){
        if(this.tracklist && this.tracklist.length > 1 && this.tracklist.position > 0){
            this.tracklist.position -= 1;
            this.getAudio(this.tracklist[this.tracklist.position].id);
        }
    }
}


text:
/**
 * jCarousel Core
 */
(function($) {
    'use strict';

    var jCarousel = $.jCarousel = {};

    jCarousel.version = '@VERSION';

    var rRelativeTarget = /^([+\-]=)?(.+)$/;

    jCarousel.parseTarget = function(target) {
        var relative = false,
            parts    = typeof target !== 'object' ?
                           rRelativeTarget.exec(target) :
                           null;

        if (parts) {
            target = parseInt(parts[2], 10) || 0;

            if (parts[1]) {
                relative = true;
                if (parts[1] === '-=') {
                    target *= -1;
                }
            }
        } else if (typeof target !== 'object') {
            target = parseInt(target, 10) || 0;
        }

        return {
            target: target,
            relative: relative
        };
    };

    jCarousel.detectCarousel = function(element) {
        var carousel;

        while (element.size() > 0) {
            carousel = element.filter('[data-jcarousel]');

            if (carousel.size() > 0) {
                return carousel;
            }

            carousel = element.find('[data-jcarousel]');

            if (carousel.size() > 0) {
                return carousel;
            }

            element = element.parent();
        }

        return null;
    };

    jCarousel.base = function(pluginName) {
        return {
            version:  jCarousel.version,
            _options:  {},
            _element:  null,
            _carousel: null,
            _init:     $.noop,
            _create:   $.noop,
            _destroy:  $.noop,
            _reload:   $.noop,
            create: function() {
                this._element
                    .attr('data-' + pluginName.toLowerCase(), true)
                    .data(pluginName, this);

                if (false === this._trigger('create')) {
                    return this;
                }

                this._create();

                this._trigger('createend');

                return this;
            },
            destroy: function() {
                if (false === this._trigger('destroy')) {
                    return this;
                }

                this._destroy();

                this._trigger('destroyend');

                this._element
                    .removeData(pluginName)
                    .removeAttr('data-' + pluginName.toLowerCase());

                return this;
            },
            reload: function(options) {
                if (false === this._trigger('reload')) {
                    return this;
                }

                if (options) {
                    this.options(options);
                }

                this._reload();

                this._trigger('reloadend');

                return this;
            },
            element: function() {
                return this._element;
            },
            options: function(key, value) {
                if (arguments.length === 0) {
                    return $.extend({}, this._options);
                }

                if (typeof key === 'string') {
                    if (typeof value === 'undefined') {
                        return typeof this._options[key] === 'undefined' ?
                                null :
                                this._options[key];
                    }

                    this._options[key] = value;
                } else {
                    this._options = $.extend({}, this._options, key);
                }

                return this;
            },
            carousel: function() {
                if (!this._carousel) {
                    this._carousel = jCarousel.detectCarousel(this.options('carousel') || this._element);

                    if (!this._carousel) {
                        $.error('Could not detect carousel for plugin "' + pluginName + '"');
                    }
                }

                return this._carousel;
            },
            _trigger: function(type, element, data) {
                var event,
                    defaultPrevented = false;

                data = [this].concat(data || []);

                (element || this._element).each(function() {
                    event = $.Event((type + '.' + pluginName).toLowerCase());

                    $(this).trigger(event, data);

                    if (event.isDefaultPrevented()) {
                        defaultPrevented = true;
                    }
                });

                return !defaultPrevented;
            }
        };
    };

    jCarousel.plugin = function(pluginName, pluginPrototype) {
        var Plugin = $[pluginName] = function(element, options) {
            this._element = $(element);
            this.options(options);

            this._init();
            this.create();
        };

        Plugin.fn = Plugin.prototype = $.extend(
            {},
            jCarousel.base(pluginName),
            pluginPrototype
        );

        $.fn[pluginName] = function(options) {
            var args        = Array.prototype.slice.call(arguments, 1),
                returnValue = this;

            if (typeof options === 'string') {
                this.each(function() {
                    var instance = $(this).data(pluginName);

                    if (!instance) {
                        return $.error(
                            'Cannot call methods on ' + pluginName + ' prior to initialization; ' +
                            'attempted to call method "' + options + '"'
                        );
                    }

                    if (!$.isFunction(instance[options]) || options.charAt(0) === '_') {
                        return $.error(
                            'No such method "' + options + '" for ' + pluginName + ' instance'
                        );
                    }

                    var methodValue = instance[options].apply(instance, args);

                    if (methodValue !== instance && typeof methodValue !== 'undefined') {
                        returnValue = methodValue;
                        return false;
                    }
                });
            } else {
                this.each(function() {
                    var instance = $(this).data(pluginName);

                    if (instance instanceof Plugin) {
                        instance.reload(options);
                    } else {
                        new Plugin(this, options);
                    }
                });
            }

            return returnValue;
        };

        return Plugin;
    };
}(jQuery));


text:
'use strict';

// TODO: Rewrite

describe('Suggestions service: Search for suggestions for a given term.', function() {
  var $httpBackend;
  var query = {
    q: 'marquez',
    limit: 2
  };
  var suggestData = {
    "type": "urn:blinkboxbooks:schema:suggestion",
    "suggestions": [
      {
        "type": "BOOK",
        "text": "Gabriel Garcia Marquez - A Life"
      },
      {
        "type": "AUTHOR",
        "text": "Gerald Martin"
      }
    ]
  };

  // Load the app module
  beforeEach(module('MobcastApp.services', 'AppConstants', 'AppConfig', 'ServiceConfig', 'testConstants', 'MobcastApp.mocks.error'));

  // configure the httpBackend for the call to access the library of the user
  beforeEach(inject(function ($injector) {
    var ROUTES_TEST = $injector.get('ROUTES_TEST');
    $httpBackend = $injector.get('$httpBackend');

		$httpBackend.when('GET', ROUTES_TEST.NON_SECURE.LIVE.SEARCH+'suggestions?limit='+query.limit+'&q='+query.q).respond(suggestData);
    $httpBackend.when('GET', '/api/local/config').respond(200);
    $httpBackend.when('GET', '/api/auth/users').respond(200);

  }));

  it('Looks for a suggestions for a given term', inject(function (Search) {

    var suggestions = null;

    // get the search results
    Search.suggestions(query).then(function (response) {
				if (response.data.suggestions !== 'undefined' && response.data.suggestions.length > 0) {
          suggestions = response.data.suggestions;
        }
      }
    );

    // sends the data to the promise
		$httpBackend.flush();

    // check the data
    expect(suggestions).toBeDefined();
    expect(suggestions[0].type).toEqual('BOOK');
    expect(suggestions[0].text).toEqual('Gabriel Garcia Marquez - A Life');
    expect(suggestions[1].type).toEqual('AUTHOR');
    expect(suggestions[1].text).toEqual('Gerald Martin');

  }));

});


text:
<?php

namespace Vinkla\Tests\Instagram;

use MetzWeb\Instagram\Instagram;
use Vinkla\Instagram\InstagramFactory;

/**
 * This is the Instagram factory test class.
 *
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class InstagramFactoryTest extends AbstractTestCase
{
    public function testMakeStandard()
    {
        $factory = $this->getInstagramFactory();

        $return = $factory->make([
            'client_id' => 'your-client-id',
            'client_secret' => null,
            'callback_url' => null,
        ]);

        $this->assertInstanceOf(Instagram::class, $return);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testMakeWithoutClientId()
    {
        $factory = $this->getInstagramFactory();

        $factory->make([
            'client_secret' => null,
            'callback_url' => null,
        ]);
    }

    protected function getInstagramFactory()
    {
        return new InstagramFactory();
    }
}


text:
#ifndef CORDOVACOMMAND_H_
#define CORDOVACOMMAND_H_

#include <FWeb.h>
#include <FBase.h>

using namespace Osp::Web::Controls;
using namespace Osp::Base;
using namespace Osp::Base::Utility;

class CordovaCommand {
public:
	CordovaCommand();
	CordovaCommand(Web* pWeb);
	virtual ~CordovaCommand();
protected:
	Web* pWeb;
public:
	virtual void Run(const String& command) =0;
};

#endif /* CORDOVACOMMAND_H_ */


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_CONSTRAINTS_DECLLOWEXPR_H_
#define _BLAZE_MATH_CONSTRAINTS_DECLLOWEXPR_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/math/typetraits/IsDeclLowExpr.h>

namespace blaze {

//=================================================================================================
//
//  MUST_BE_DECLLOWEXPR_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup math_constraints
//
// In case the given data type \a T is not a decllow expression (i.e. a type derived from the
// DeclLowExpr base class), a compilation error is created.
*/
#define BLAZE_CONSTRAINT_MUST_BE_DECLLOWEXPR_TYPE(T) \
   static_assert( ::blaze::IsDeclLowExpr<T>::value, "Non-decllow expression type detected" )
//*************************************************************************************************

//=================================================================================================
//
//  MUST_NOT_BE_DECLLOWEXPR_TYPE CONSTRAINT
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Constraint on the data type.
// \ingroup math_constraints
//
// In case the given data type \a T is a decllow expression (i.e. a type derived from the
// DeclLowExpr base class), a compilation error is created.
*/
#define BLAZE_CONSTRAINT_MUST_NOT_BE_DECLLOWEXPR_TYPE(T) \
   static_assert( !::blaze::IsDeclLowExpr<T>::value, "Decllow expression type detected" )
//*************************************************************************************************

} // namespace blaze

#endif


text:
var main = function() {

};

main.prototype = {
	transform : function(opt) {
		// transformer function
		var processor = new XSLTProcessor(),
			span      = document.createElement('span'),
			tmpltXpath = '//xsl:template[@name="'+ opt.template +'"]',
			temp;

		temp = xNode.selectSingleNode(opt.xsl, tmpltXpath);
		temp.setAttribute('match', opt.match);
		processor.importStylesheet(opt.xsl);
		span.appendChild(processor.transformToFragment(opt.xml, document));
		temp.removeAttribute('match');

		return span.innerHTML;
	}
};

module.exports = new main();

/*
 * XML Node 'selectNodes' & 'selectSingleNode'
 */
window.xNode = function() {

};

xNode.selectNodes = function(XNode, XPath) {
	if (XNode.evaluate) {
		var ns = XNode.createNSResolver(XNode.documentElement),
			qI = XNode.evaluate(XPath, XNode, ns, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null),
			res = [],
			i   = 0,
			il  = qI.snapshotLength;
		for (; i<il; i++) {
			res.push( qI.snapshotItem(i) );
		}
		return res;
	} else {
		return XNode.selectNodes(XPath);
	}
};

xNode.selectSingleNode = function(XNode, XPath) {
	if (XNode.evaluate) {
		var xI = this.selectNodes(XNode, XPath);
		return (xI.length > 0)? xI[0] : null;
	} else {
		return XNode.selectSingleNode(XPath);
	}
};


text:
package org.apache.spark.graphx

import scala.reflect.ClassTag

/**
 * Implements a Pregel-like bulk-synchronous message-passing API.
 *
 * Unlike the original Pregel API, the GraphX Pregel API factors the sendMessage computation over
 * edges, enables the message sending computation to read both vertex attributes, and constrains
 * messages to the graph structure.  These changes allow for substantially more efficient
 * distributed execution while also exposing greater flexibility for graph-based computation.
 *
 * @example We can use the Pregel abstraction to implement PageRank:
 * {{{
 * val pagerankGraph: Graph[Double, Double] = graph
 *   // Associate the degree with each vertex
 *   .outerJoinVertices(graph.outDegrees) {
 *     (vid, vdata, deg) => deg.getOrElse(0)
 *   }
 *   // Set the weight on the edges based on the degree
 *   .mapTriplets(e => 1.0 / e.srcAttr)
 *   // Set the vertex attributes to the initial pagerank values
 *   .mapVertices((id, attr) => 1.0)
 *
 * def vertexProgram(id: VertexId, attr: Double, msgSum: Double): Double =
 *   resetProb + (1.0 - resetProb) * msgSum
 * def sendMessage(id: VertexId, edge: EdgeTriplet[Double, Double]): Iterator[(VertexId, Double)] =
 *   Iterator((edge.dstId, edge.srcAttr * edge.attr))
 * def messageCombiner(a: Double, b: Double): Double = a + b
 * val initialMessage = 0.0
 * // Execute Pregel for a fixed number of iterations.
 * Pregel(pagerankGraph, initialMessage, numIter)(
 *   vertexProgram, sendMessage, messageCombiner)
 * }}}
 *
 */
object Pregel {

  /**
   * Execute a Pregel-like iterative vertex-parallel abstraction.  The
   * user-defined vertex-program `vprog` is executed in parallel on
   * each vertex receiving any inbound messages and computing a new
   * value for the vertex.  The `sendMsg` function is then invoked on
   * all out-edges and is used to compute an optional message to the
   * destination vertex. The `mergeMsg` function is a commutative
   * associative function used to combine messages destined to the
   * same vertex.
   *
   * On the first iteration all vertices receive the `initialMsg` and
   * on subsequent iterations if a vertex does not receive a message
   * then the vertex-program is not invoked.
   *
   * This function iterates until there are no remaining messages, or
   * for `maxIterations` iterations.
   *
   * @tparam VD the vertex data type
   * @tparam ED the edge data type
   * @tparam A the Pregel message type
   *
   * @param graph the input graph.
   *
   * @param initialMsg the message each vertex will receive at the on
   * the first iteration
   *
   * @param maxIterations the maximum number of iterations to run for
   *
   * @param activeDirection the direction of edges incident to a vertex that received a message in
   * the previous round on which to run `sendMsg`. For example, if this is `EdgeDirection.Out`, only
   * out-edges of vertices that received a message in the previous round will run. The default is
   * `EdgeDirection.Either`, which will run `sendMsg` on edges where either side received a message
   * in the previous round. If this is `EdgeDirection.Both`, `sendMsg` will only run on edges where
   * *both* vertices received a message.
   *
   * @param vprog the user-defined vertex program which runs on each
   * vertex and receives the inbound message and computes a new vertex
   * value.  On the first iteration the vertex program is invoked on
   * all vertices and is passed the default message.  On subsequent
   * iterations the vertex program is only invoked on those vertices
   * that receive messages.
   *
   * @param sendMsg a user supplied function that is applied to out
   * edges of vertices that received messages in the current
   * iteration
   *
   * @param mergeMsg a user supplied function that takes two incoming
   * messages of type A and merges them into a single message of type
   * A.  ''This function must be commutative and associative and
   * ideally the size of A should not increase.''
   *
   * @return the resulting graph at the end of the computation
   *
   */
  def apply[VD: ClassTag, ED: ClassTag, A: ClassTag]
     (graph: Graph[VD, ED],
      initialMsg: A,
      maxIterations: Int = Int.MaxValue,
      activeDirection: EdgeDirection = EdgeDirection.Either)
     (vprog: (VertexId, VD, A) => VD,
      sendMsg: EdgeTriplet[VD, ED] => Iterator[(VertexId, A)],
      mergeMsg: (A, A) => A)
    : Graph[VD, ED] =
  {
    var g = graph.mapVertices((vid, vdata) => vprog(vid, vdata, initialMsg)).cache()
    // compute the messages
    var messages = g.mapReduceTriplets(sendMsg, mergeMsg)
    var activeMessages = messages.count()
    // Loop
    var prevG: Graph[VD, ED] = null
    var i = 0
    while (activeMessages > 0 && i < maxIterations) {
      // Receive the messages. Vertices that didn't get any messages do not appear in newVerts.
      val newVerts = g.vertices.innerJoin(messages)(vprog).cache()
      // Update the graph with the new vertices.
      prevG = g
      g = g.outerJoinVertices(newVerts) { (vid, old, newOpt) => newOpt.getOrElse(old) }
      g.cache()

      val oldMessages = messages
      // Send new messages. Vertices that didn't get any messages don't appear in newVerts, so don't
      // get to send messages. We must cache messages so it can be materialized on the next line,
      // allowing us to uncache the previous iteration.
      messages = g.mapReduceTriplets(sendMsg, mergeMsg, Some((newVerts, activeDirection))).cache()
      // The call to count() materializes `messages`, `newVerts`, and the vertices of `g`. This
      // hides oldMessages (depended on by newVerts), newVerts (depended on by messages), and the
      // vertices of prevG (depended on by newVerts, oldMessages, and the vertices of g).
      activeMessages = messages.count()
      // Unpersist the RDDs hidden by newly-materialized RDDs
      oldMessages.unpersist(blocking=false)
      newVerts.unpersist(blocking=false)
      prevG.unpersistVertices(blocking=false)
      // count the iteration
      i += 1
    }

    g
  } // end of apply

} // end of class Pregel


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ui.base.TabFragment">

    <android.support.design.widget.TabLayout
        style="@style/AppTheme.TabLayout"
        android:id="@+id/tab"
        app:tabGravity="fill"
        app:tabMaxWidth="0dp" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1" />

</LinearLayout>