text:
package io.realm.permissions;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Nullable;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.realm.PermissionManager;
import io.realm.annotations.Index;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.RealmClass;
import io.realm.annotations.Required;
import io.realm.internal.Util;
import io.realm.internal.permissions.BasePermissionApi;

/**
 * This class represents a permission offer for a Realm that can be given to other users.
 * When an offer is successfully created, it will be represented by an {@code offerToken} that can be sent
 * to other users. Once they accept this token, the permissions covered by this offer will take effect for that
 * user.
 *

 * Permission offers can only be created by users that can manage the Realm, the offer is about.
 *
 * @see PermissionManager#makeOffer(PermissionOffer, PermissionManager.MakeOfferCallback)
 * @see PermissionManager#acceptOffer(String, PermissionManager.AcceptOfferCallback)
 * @see Permissions description for general
 * documentation.
 */

@RealmClass
public class PermissionOffer implements BasePermissionApi {

    // Base fields
    @PrimaryKey
    @Required
    private String id = UUID.randomUUID().toString();
    @Required
    private Date createdAt = new Date();
    @Required
    private Date updatedAt = new Date();
    private Integer statusCode; // nil=not processed, 0=success, >0=error
    private String statusMessage;

    // Offer fields
    @Index
    private String token;
    @Required
    private String realmUrl;
    private boolean mayRead;
    private boolean mayWrite;
    private boolean mayManage;
    private Date expiresAt;

    /**
     * Constructor required by Realm. Should not be used.
     */
    public PermissionOffer() {
        // No args constructor required by Realm
    }

    /**
     * Creates a request for an permission offer that last until it is manually revoked.
     *
     * @param url specific url to Realm effected this offer encompasses all Realms manged by the user making the offer.
     * @param accessLevel the {@link AccessLevel} granted to the user accepting the offer.
     *
     * @see PermissionManager#revokeOffer(String, PermissionManager.RevokeOfferCallback)
     */
    @SuppressFBWarnings("EI_EXPOSE_REP2")
    public PermissionOffer(String url, AccessLevel accessLevel) {
        //noinspection ConstantConditions
        this(url, accessLevel, null);
    }

    /**
     * Creates a request for a permission offer that last until it is manually revoked.
     *
     * @param url specific url to Realm effected. The user sending the offer must have manage rights to this Realm.
     * @param accessLevel the {@link AccessLevel} granted to the user accepting the offer.
     * @param expiresAt the date and time when this offer expires. If {@code null} is provided the offer never expires.
     *
     *
     * @see PermissionManager#revokeOffer(String, PermissionManager.RevokeOfferCallback)
     */
    @SuppressFBWarnings("EI_EXPOSE_REP2")
    public PermissionOffer(String url, AccessLevel accessLevel, @Nullable Date expiresAt) {
        validateUrl(url);
        validateAccessLevel(accessLevel);
        this.mayRead = accessLevel.mayRead();
        this.mayWrite = accessLevel.mayWrite();
        this.mayManage = accessLevel.mayManage();
        this.realmUrl = url;
        //noinspection ConstantConditions
        this.expiresAt = (expiresAt != null) ? (Date) expiresAt.clone() : null;
    }

    private void validateUrl(String url) {
        if (Util.isEmptyString(url)) {
            throw new IllegalArgumentException("Non-empty 'realmUrl' required.");
        }

        try {
            // Validate basic syntax.
            new URI(url);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Invalid 'realmUrl'.", e);
        }
    }

    private void validateAccessLevel(AccessLevel accessLevel) {
        if (accessLevel == null) {
            throw new IllegalArgumentException("Non-null 'accessLevel' required.");
        }
    }

    /**
     * Returns the id uniquely identifying this offer.
     *
     * @return the id uniquely identifying this offer.
     */
    @Override
    public String getId() {
        return id;
    }

    /**
     * Returns the timestamp when this offer was created.
     *
     * @return the timstamp when this offer was created.
     */
    @Override
    @SuppressFBWarnings("EI_EXPOSE_REP")
    public Date getCreatedAt() {
        return createdAt;
    }

    /**
     * Returns the timestamp this offer was last updated.
     *
     * @return the timestamp when this offer was last updated.
     */
    @Override
    @SuppressFBWarnings("EI_EXPOSE_REP")
    public Date getUpdatedAt() {
        return updatedAt;
    }

    /**
     * Returns the server status code for this change.
     *
     * @return {@code null} if not yet processed. {@code 0} if successful, {@code >0} if an error happened.
     * See {@link #getStatusMessage()}.
     */
    @Override
    @Nullable
    public Integer getStatusCode() {
        return statusCode;
    }

    /**
     * Returns the servers status message, if an error occurred. Otherwise it will return {@code null}.
     *
     * @return The servers status message in case of an error, {@code null} otherwise.
     */
    @Override
    @Nullable
    public String getStatusMessage() {
        return statusMessage;
    }

    /**
     * Checks if the request was successfully handled by the Realm Object Server.
     *
     * @return {@code true} if the request was handled successfully. {@code false} if not. See {@link #getStatusMessage()}
     *         for the full error message.
     */
    public boolean isOfferCreated() {
        return !Util.isEmptyString(token);
    }

    /**
     * Returns the offer token if this offer was successfully created.
     *
     * @return the offer token or {@code null} if the offer wasn't created yet.
     */
    @Nullable
    public String getToken() {
        return token;
    }

    /**
     * Returns the Realm URL for which the permissions are granted.
     *
     * @return the Realm URL for which the permissions should be granted.
     */
    public String getRealmUrl() {
        return realmUrl;
    }

    /**
     * Returns whether or not the user accepting this offer is granted read permission.
     *
     * @return {@code true} if the user accepting this offer is granted read permission, {@code false} if not.
     */
    public boolean mayRead() {
        return mayRead;
    }

    /**
     * Returns whether or not the user accepting this offer is granted write permission.
     *
     * @return {@code true} if the user accepting this offer is granted write permission, {@code false} if not.
     */
    public boolean mayWrite() {
        return mayWrite;
    }

    /**
     * Returns whether or not the user accepting this offer is granted manage permission. This will allow this user
     * to also grant or remove permission for other users on this Realm.
     *
     * @return {@code true} if the user accepting this offer is granted mange permission, {@code false} if not.
     */
    public boolean mayManage() {
        return mayManage;
    }

    /**
     * Returns when this offer expires. {@code null} is returned if this offer never expires.
     *
     * @return the date when this offer expires or {@code null} if it never expires.
     */
    @SuppressFBWarnings("EI_EXPOSE_REP")
    @Nullable
    public Date getExpiresAt() {
        return expiresAt;
    }

    @Override
    public String toString() {
        return "PermissionOffer{" +
                "id='" + id + '\'' +
                ", createdAt=" + createdAt +
                ", updatedAt=" + updatedAt +
                ", statusCode=" + statusCode +
                ", statusMessage='" + statusMessage + '\'' +
                ", token='" + token + '\'' +
                ", realmUrl='" + realmUrl + '\'' +
                ", mayRead=" + mayRead +
                ", mayWrite=" + mayWrite +
                ", mayManage=" + mayManage +
                ", expiresAt=" + expiresAt +
                '}';
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE252_Unchecked_Return_Value__wchar_t_snprintf_17.c
Label Definition File: CWE252_Unchecked_Return_Value.label.xml
Template File: point-flaw-17.tmpl.c
*/
/*
 * @description
 * CWE: 252 Unchecked Return Value
 * Sinks: snprintf
 *    GoodSink: Check if snwprintf() fails
 *    BadSink : Do not check if snwprintf() fails
 * Flow Variant: 17 Control flow: for loops
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#define SRC L"string"

#ifdef _WIN32
#define SNPRINTF _snwprintf
#else
#define SNPRINTF snprintf
#endif

#ifndef OMITBAD

void CWE252_Unchecked_Return_Value__wchar_t_snprintf_17_bad()
{
    int j;
    for(j = 0; j < 1; j++)
    {
        {
            /* By initializing dataBuffer, we ensure this will not be the
             * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgetws() and other variants */
            wchar_t dataBuffer[100] = L"";
            wchar_t * data = dataBuffer;
            /* FLAW: Do not check the return value */
            SNPRINTF(data,100-wcslen(SRC)-1, L"%s\n", SRC);
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses the GoodSinkBody in the for statements */
static void good1()
{
    int k;
    for(k = 0; k < 1; k++)
    {
        {
            /* By initializing dataBuffer, we ensure this will not be the
             * CWE 690 (Unchecked Return Value To NULL Pointer) flaw for fgetws() and other variants */
            wchar_t dataBuffer[100] = L"";
            wchar_t * data = dataBuffer;
            /* FIX: check the return value */
            if (SNPRINTF(data,100-wcslen(SRC)-1, L"%s\n", SRC) < 0)
            {
                printLine("snwprintf failed!");
            }
        }
    }
}

void CWE252_Unchecked_Return_Value__wchar_t_snprintf_17_good()
{
    good1();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE252_Unchecked_Return_Value__wchar_t_snprintf_17_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE252_Unchecked_Return_Value__wchar_t_snprintf_17_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using Moq;
using MvcMonitor.Data.Providers;
using MvcMonitor.Data.Providers.Factories;
using MvcMonitor.ErrorHandling;
using MvcMonitor.Models;
using NUnit.Framework;

namespace MvcMonitor.Tests.ErrorHubTests
{
    [TestFixture]
    [Category("Core")]
    public class GetPagedErrorsTests
    {
        private Mock<IIndexProviderFactory> _mockIndexProviderFactory;
        private int _page;
        private int _pageSize;
        private string _filterFrom;
        private string _filterTo;
        private string _filterUser;
        private string _filterApplication;
        private string _filterLocation;
        private Mock<IIndexProvider> _mockIndexProvider;
        private PagedList<ErrorModel> _result;
        private PagedList<ErrorModel> _providerResult;

        [SetUp]
        public void WhenFetchingErrorsForTheIndexPage()
        {
            _page = 2;
            _pageSize = 10;
            _filterFrom = "2014-02-25";
            _filterTo = "2014-02-28";
            _filterUser = "skfjnsdf";
            _filterApplication = "sjfe";
            _filterLocation = "sfisbdf";

            _providerResult = new PagedList<ErrorModel>(10, 5, 100,
                                                        new List<ErrorModel> {new ErrorModel {Id = Guid.NewGuid()}});

            _mockIndexProvider = new Mock<IIndexProvider>();
            _mockIndexProvider
                .Setup(provider => provider.GetErrors(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
                    It.IsAny<string>(), It.IsAny<string>()))
                .Returns(_providerResult);

            _mockIndexProviderFactory = new Mock<IIndexProviderFactory>();
            _mockIndexProviderFactory
                .Setup(factory => factory.Create())
                .Returns(_mockIndexProvider.Object);

            var hub = new ErrorHub(null, null, _mockIndexProviderFactory.Object);

            _result = hub.GetPagedErrors(_page, _pageSize, _filterFrom, _filterTo, _filterUser, _filterApplication, _filterLocation);
        }

        [Test]
        public void ThenTheIndexProviderFetchesTheErrors()
        {
            _mockIndexProvider.Verify(provider => provider.GetErrors(_page, _pageSize,
                It.Is<DateTime>(dateFrom => dateFrom == DateTime.Parse(_filterFrom)),
                It.Is<DateTime>(dateTo => dateTo.Year == 2014 && dateTo.Month == 2 && dateTo.Day == 28 && dateTo.Hour == 23
                     && dateTo.Minute == 59 && dateTo.Second == 59),
                _filterUser, _filterApplication, _filterLocation));
        }

        [Test]
        public void ThenThePagedListIsReturned()
        {
            Assert.That(_result, Is.EqualTo(_providerResult));
        }
    }

    [TestFixture("")]
    [TestFixture((string)null)]
    [TestFixture("INVALID_$GG09gegRGjw9rs££56")]
    [Category("Core")]
    public class GetPagedErrorsWithNoDateFilterTests
    {
        private readonly string _emptyDateField;
        private Mock<IIndexProviderFactory> _mockIndexProviderFactory;
        private int _page;
        private int _pageSize;
        private string _filterFrom;
        private string _filterTo;
        private string _filterUser;
        private string _filterApplication;
        private string _filterLocation;
        private Mock<IIndexProvider> _mockIndexProvider;
        private PagedList<ErrorModel> _result;
        private PagedList<ErrorModel> _providerResult;

        public GetPagedErrorsWithNoDateFilterTests(string emptyDateField)
        {
            _emptyDateField = emptyDateField;
        }

        [SetUp]
        public void WhenFetchingErrorsForTheIndexPage()
        {
            _page = 2;
            _pageSize = 10;
            _filterFrom = _emptyDateField;
            _filterTo = _emptyDateField;
            _filterUser = "skfjnsdf";
            _filterApplication = "sjfe";
            _filterLocation = "sfisbdf";

            _providerResult = new PagedList<ErrorModel>(10, 5, 100,
                                                        new List<ErrorModel> { new ErrorModel { Id = Guid.NewGuid() } });

            _mockIndexProvider = new Mock<IIndexProvider>();
            _mockIndexProvider
                .Setup(provider => provider.GetErrors(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(),
                    It.IsAny<string>(), It.IsAny<string>()))
                .Returns(_providerResult);

            _mockIndexProviderFactory = new Mock<IIndexProviderFactory>();
            _mockIndexProviderFactory
                .Setup(factory => factory.Create())
                .Returns(_mockIndexProvider.Object);

            var hub = new ErrorHub(null, null, _mockIndexProviderFactory.Object);

            _result = hub.GetPagedErrors(_page, _pageSize, _filterFrom, _filterTo, _filterUser, _filterApplication, _filterLocation);
        }

        [Test]
        public void ThenTheIndexProviderFetchesTheErrorsWithNullDateFilters()
        {
            _mockIndexProvider.Verify(provider => provider.GetErrors(_page, _pageSize, null, null, _filterUser, _filterApplication, _filterLocation));
        }

        [Test]
        public void ThenThePagedListIsReturned()
        {
            Assert.That(_result, Is.EqualTo(_providerResult));
        }
    }
}


text:
void initrd_test(uint32_t initrd_start)
{
	(void)initrd_start;
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>WebGL OES_vertex_array_object Conformance Tests</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>

<canvas id="canvas" style="width: 50px; height: 50px;"> </canvas>


text:
var querystring = require('querystring'),
    request = require('request');

var search_location = function (address, cb) {

    var url = 'http://maps.googleapis.com/maps/api/geocode/json';

    var q = {
        sensor: 'false',
        address: address
    };

    url += '?' + querystring.stringify(q);

    request(url, function (error, response, body) {

        var gmapsResults = JSON.parse(body).results[0];

        var h = {};
        gmapsResults.address_components.forEach(function (c) {
            c.types.forEach(function (t) {
                if (t === 'country') {
                    h[t] = c.long_name;
                } else {
                    h[t] = c.short_name;
                }
            });
        });

        cb({
            "street_number": h.street_number,
            "street": h.route,
            "country": h.country,
            "postal": h.postal_code,
            "state": h.administrative_area_level_1,
            "city": h.locality,
            "lat": gmapsResults.geometry.location.lat,
            "lon": gmapsResults.geometry.location.lng,
            "quality": "50"
        });

    });

};

exports.search_location = search_location;

exports.worker = function (task, config) {

    var input = JSON.parse(task.config.input);

    search_location(input.LOCATION, function (response) {

        task.respondCompleted({
            _OUTPUT: response
        });

    });

};


text:
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

$.validator.unobtrusive.adapters.addSingleVal("minimumlength", "count");

$.validator.addMethod("minimumlength", function (value, element, count) {
    if (value.length < count) {
        return false;
    }

    return true;
});

$.validator.unobtrusive.adapters.addSingleVal("maximumlength", "count");

$.validator.addMethod("maximumlength", function (value, element, count) {
    if (value.length > count) {
        return false;
    }

    return true;
});

$.validator.unobtrusive.adapters.addSingleVal("uppercasecount", "count");

$.validator.addMethod("uppercasecount", function (value, element, count) {
    if (value.replace(/[^A-Z]/g, "").length < count) {
        return false;
    }

    return true;
});

$.validator.unobtrusive.adapters.addSingleVal("numberscount", "count");

$.validator.addMethod("numberscount", function (value, element, count) {
    if (value.replace(/[^0-9]/g, "").length < count) {
        return false;
    }

    return true;
});

$.validator.unobtrusive.adapters.addSingleVal("symbolscount", "count");

$.validator.addMethod("symbolscount", function (value, element, count) {
    if (value.replace(/[^~!@#$%^&*_\-+'\|\\(){}\[\]:;\"'<>,.?/]/g, "").length < count) {

        return false;
    }

    return true;
});


text:
/**
 * @file
 *
 * @brief Zephyr testing framework _test_deprecated.
 */

#ifndef ZEPHYR_TESTSUITE_ZTEST_TEST_H_
#define ZEPHYR_TESTSUITE_ZTEST_TEST_H_

#include <zephyr/app_memory/app_memdomain.h>
#include <zephyr/init.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

struct unit_test {
	const char *name;
	void (*test)(void);
	void (*setup)(void);
	void (*teardown)(void);
	uint32_t thread_options;
};

/**
 * Stats about a ztest suite
 */
struct ztest_suite_stats {
	/** The number of times that the suite ran */
	uint32_t run_count;
	/** The number of times that the suite was skipped */
	uint32_t skip_count;
	/** The number of times that the suite failed */
	uint32_t fail_count;
};

/**
 * A single node of test suite. Each node should be added to a single linker section which will
 * allow ztest_run_registered_test_suites() to iterate over the various nodes.
 */
struct ztest_suite_node {
	/** The name of the test suite. */
	const char *name;
	/** Pointer to the test suite. */
	struct unit_test *suite;
	/**
	 * An optional predicate function to determine if the test should run. If NULL, then the
	 * test will only run once on the first attempt.
	 *
	 * @param state The current state of the test application.
	 * @return True if the suite should be run; false to skip.
	 */
	bool (*predicate)(const void *state);
	/** Stats */
	struct ztest_suite_stats *stats;
};

extern struct ztest_suite_node _ztest_suite_node_list_start[];
extern struct ztest_suite_node _ztest_suite_node_list_end[];

/**
 * Create and register a ztest suite. Using this macro creates a new test suite (using
 * ztest_test_suite). It then creates a struct ztest_suite_node in a specific linker section.
 *
 * Tests can then be run by calling ztest_run_registered_test_suites(const void *state) by passing
 * in the current state. See the documentation for ztest_run_registered_test_suites for more info.
 *
 * @param SUITE_NAME The name of the suite (see ztest_test_suite for more info)
 * @param PREDICATE A function to test against the state and determine if the test should run.
 * @param args Varargs placeholder for the remaining arguments passed for the unit tests.
 */
#define ztest_register_test_suite(SUITE_NAME, PREDICATE, args...)                                  \
	ztest_test_suite(SUITE_NAME, ##args);                                                      \
	struct ztest_suite_stats UTIL_CAT(z_ztest_test_node_stats_, SUITE_NAME);                   \
	static STRUCT_SECTION_ITERABLE(ztest_suite_node, z_ztest_test_node_##SUITE_NAME) = {       \
		.name = #SUITE_NAME,                                                               \
		.suite = _##SUITE_NAME,                                                            \
		.predicate = PREDICATE,                                                            \
		.stats = &UTIL_CAT(z_ztest_test_node_stats_, SUITE_NAME),                          \
	};

/**
 * Run the registered unit tests which return true from their pragma function.
 *
 * @param state The current state of the machine as it relates to the test executable.
 * @return The number of tests that ran.
 */
int ztest_run_registered_test_suites(const void *state);

/**
 * @brief Fails the test if any of the registered tests did not run.
 *
 * When registering test suites, a pragma function can be provided to determine WHEN the test should
 * run. It is possible that a test suite could be registered but the pragma always prevents it from
 * running. In cases where a test should make sure that ALL suites ran at least once, this function
 * may be called at the end of test_main(). It will cause the test to fail if any suite was
 * registered but never ran.
 */
void ztest_verify_all_registered_test_suites_ran(void);

/**
 * @brief Run a test suite.
 *
 * Internal implementation. Do not call directly. This will run the full test suite along with some
 * checks for fast failures and initialization.
 *
 * @param name The name of the suite to run.
 * @param suite Pointer to the first unit test.
 * @return Negative value if the test suite never ran; otherwise, return the number of failures.
 */
int z_ztest_run_test_suite(const char *name, struct unit_test *suite);

/**
 * @defgroup ztest_test_deprecated Ztest testing macros
 * @ingroup ztest
 *
 * This module eases the testing process by providing helpful macros and other
 * testing structures.
 *
 * @{
 */

/**
 * @brief Fail the currently running test.
 *
 * This is the function called from failed assertions and the like. You
 * probably don't need to call it yourself.
 */
void ztest_test_fail(void);

/**
 * @brief Pass the currently running test.
 *
 * Normally a test passes just by returning without an assertion failure.
 * However, if the success case for your test involves a fatal fault,
 * you can call this function from k_sys_fatal_error_handler to indicate that
 * the test passed before aborting the thread.
 */
void ztest_test_pass(void);

/**
 * @brief Skip the current test.
 */
void ztest_test_skip(void);

/**
 * @brief Do nothing, successfully.
 *
 * Unit test / setup function / teardown function that does
 * nothing, successfully. Can be used as a parameter to
 * ztest_unit_test_setup_teardown().
 */
static inline void unit_test_noop(void)
{
}

/**
 * @brief Define a test with setup and teardown functions
 *
 * This should be called as an argument to ztest_test_suite. The test will
 * be run in the following order: @a setup, @a fn, @a teardown.
 *
 * @param fn Main test function
 * @param setup Setup function
 * @param teardown Teardown function
 */
#define ztest_unit_test_setup_teardown(fn, setup, teardown)                                        \
	{                                                                                \
		STRINGIFY(fn), fn, setup, teardown, 0                                              \
	}

/**
 * @brief Define a user mode test with setup and teardown functions
 *
 * This should be called as an argument to ztest_test_suite. The test will
 * be run in the following order: @a setup, @a fn, @a teardown. ALL
 * test functions will be run in user mode, and only if CONFIG_USERSPACE
 * is enabled, otherwise this is the same as ztest_unit_test_setup_teardown().
 *
 * @param fn Main test function
 * @param setup Setup function
 * @param teardown Teardown function
 */
#define ztest_user_unit_test_setup_teardown(fn, setup, teardown)                                   \
	{                                                                                \
		STRINGIFY(fn), fn, setup, teardown, K_USER                                         \
	}

/**
 * @brief Define a test function
 *
 * This should be called as an argument to ztest_test_suite.
 *
 * @param fn Test function
 */
#define ztest_unit_test(fn)                                                                        \
	ztest_unit_test_setup_teardown(fn, unit_test_noop, unit_test_noop)

/**
 * @brief Define a test function that should run as a user thread
 *
 * This should be called as an argument to ztest_test_suite.
 * If CONFIG_USERSPACE is not enabled, this is functionally identical to
 * ztest_unit_test().
 *
 * @param fn Test function
 */
#define ztest_user_unit_test(fn)                                                                   \
	ztest_user_unit_test_setup_teardown(fn, unit_test_noop, unit_test_noop)

/**
 * @brief Define a SMP-unsafe test function
 *
 * As ztest_unit_test(), but ensures all test code runs on only
 * one CPU when in SMP.
 *
 * @param fn Test function
 */
#ifdef CONFIG_SMP
#define ztest_1cpu_unit_test(fn)                                                                   \
	ztest_unit_test_setup_teardown(fn, z_test_1cpu_start, z_test_1cpu_stop)
#else
#define ztest_1cpu_unit_test(fn) ztest_unit_test(fn)
#endif

/**
 * @brief Define a SMP-unsafe test function that should run as a user thread
 *
 * As ztest_user_unit_test(), but ensures all test code runs on only
 * one CPU when in SMP.
 *
 * @param fn Test function
 */
#ifdef CONFIG_SMP
#define ztest_1cpu_user_unit_test(fn)                                                              \
	ztest_user_unit_test_setup_teardown(fn, z_test_1cpu_start, z_test_1cpu_stop)
#else
#define ztest_1cpu_user_unit_test(fn) ztest_user_unit_test(fn)
#endif

/* definitions for use with testing application shared memory   */
#ifdef CONFIG_USERSPACE
#define ZTEST_DMEM	K_APP_DMEM(ztest_mem_partition)
#define ZTEST_BMEM	K_APP_BMEM(ztest_mem_partition)
#define ZTEST_SECTION	K_APP_DMEM_SECTION(ztest_mem_partition)
extern struct k_mem_partition ztest_mem_partition;
#else
#define ZTEST_DMEM
#define ZTEST_BMEM
#define ZTEST_SECTION	.data
#endif

/**
 * @brief Define a test suite
 *
 * This function should be called in the following fashion:
 * ```{.c}
 *      ztest_test_suite(test_suite_name,
 *              ztest_unit_test(test_function),
 *              ztest_unit_test(test_other_function)
 *      );
 *
 *      ztest_run_test_suite(test_suite_name);
 * ```
 *
 * @param suite Name of the testing suite
 */
#define ztest_test_suite(suite, ...)                                                               \
	static ZTEST_DMEM struct unit_test _##suite[] = { __VA_ARGS__, { 0 } }
/**
 * @brief Run the specified test suite.
 *
 * @param suite Test suite to run.
 */
#define ztest_run_test_suite(suite)                                                                \
	z_ztest_run_test_suite(#suite, _##suite)

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* ZEPHYR_TESTSUITE_ZTEST_TEST_H_ */


text:
package survey.data;

import java.util.Properties;
import redis.clients.jedis.JedisPool;

public class NamespaceStorage {

    private final RepositoryFactory _factory;
    private final JedisPool _jedisPool;
    private final String _namespaceName;
    private final Properties _properties;
    private final String _redisPrefix;
    private final VoteRepository _voteRepository;

    public NamespaceStorage(RepositoryFactory factory, String namespaceName, JedisPool jedisPool, Properties properties) {
        assert jedisPool != null;
        assert namespaceName != null;
        assert properties != null;

        _factory = factory;
        _jedisPool = jedisPool;
        _namespaceName = namespaceName;
        _properties = properties;

        String p = properties == null ? null : properties.getProperty("redis.prefix");
        _redisPrefix = p == null ? "survey:" : p;
        _voteRepository = new VoteRepository(this);
    }

    public String generateIndexKey(String surveyPath) {
        assert surveyPath != null;
        assert surveyPath.indexOf(":") < 0;

        return generateRedisKeyOf("index", surveyPath.replaceAll("/", ":"));
    }

    private String generateRedisKeyOf(String tag, Object...args) {
        assert tag != null;
        assert args != null;

        StringBuffer buf = new StringBuffer();
        buf.append(_redisPrefix);
        buf.append(_namespaceName);
        buf.append(":");
        buf.append(tag);
        for (Object obj : args) {
            assert obj != null;
            buf.append(":");
            buf.append(obj.toString());
        }
        return buf.toString();
    }

    public String generateVoteKey(String surveyPath) {
        assert surveyPath != null;
        assert surveyPath.indexOf(":") < 0;

        return generateRedisKeyOf("vote", surveyPath.replaceAll("/", ":"));
    }

    public RepositoryFactory getFactory() {
        return _factory;
    }

    public JedisPool getJedisPool() {
        return _jedisPool;
    }

    public Object getLocalCache(String key) {
        return getFactory().getLocalCache().getValue(key);
    }

    public String getNamespaceName() {
        return _namespaceName;
    }

    public Properties getProperties() {
        return _properties;
    }

    public VoteRepository getVoteRepository() {
        return _voteRepository;
    }

    public void putLocalCache(String key, Object value) {
        getFactory().getLocalCache().putValue(key, value);
    }

    // For debugging.
    @Override
    public String toString() {
        return _namespaceName;
    }

}


text:
package org.wso2.carbon.apimgt.gateway.inbound.websocket.response;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.common.gateway.constants.GraphQLConstants;
import org.wso2.carbon.apimgt.gateway.handlers.streaming.websocket.WebSocketUtils;
import org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext;
import org.wso2.carbon.apimgt.gateway.dto.GraphQLOperationDTO;
import org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO;
import org.wso2.carbon.apimgt.gateway.inbound.websocket.utils.InboundWebsocketProcessorUtil;
import org.wso2.carbon.apimgt.impl.APIConstants;

/**
 * A GraphQL subscriptions specific extension of ResponseProcessor. This class intercepts the inbound websocket
 * execution path of graphQL subscription responses (subscribe messages).
 */
public class GraphQLResponseProcessor extends ResponseProcessor {

    /**
     * Handle inbound websocket responses of GraphQL subscriptions and perform authentication, authorization
     * and throttling. This identifies operation from the subscription responses using the unique message id parameter.
     *
     * @param msgSize               Message size of graphQL subscription response payload
     * @param msgText               The GraphQL subscription response payload text
     * @param inboundMessageContext InboundMessageContext
     * @return InboundProcessorResponseDTO
     */
    @Override
    public InboundProcessorResponseDTO handleResponse(int msgSize, String msgText,
                                                      InboundMessageContext inboundMessageContext) {

        InboundProcessorResponseDTO responseDTO =
                InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext);
        JSONObject graphQLMsg = new JSONObject(msgText);
        if (!responseDTO.isError() && checkIfSubscribeMessageResponse(graphQLMsg)) {
            if (graphQLMsg.has(GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_ID)
                    && graphQLMsg.getString(GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_ID) != null) {
                String operationId = graphQLMsg.getString(
                        GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_ID);
                GraphQLOperationDTO graphQLOperationDTO =
                        inboundMessageContext.getVerbInfoForGraphQLMsgId(
                                graphQLMsg.getString(GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_ID));
                WebSocketUtils.setApiPropertyToChannel(inboundMessageContext.getCtx(),
                        APIConstants.API_ELECTED_RESOURCE, graphQLOperationDTO.getOperation());
                // validate scopes based on subscription payload when security is enabled
                String authType = graphQLOperationDTO.getVerbInfoDTO().getAuthType();
                if (!StringUtils.capitalize(APIConstants.AUTH_TYPE_NONE.toLowerCase()).equals(authType)) {
                    responseDTO = InboundWebsocketProcessorUtil
                            .validateScopes(inboundMessageContext, graphQLOperationDTO.getOperation(), operationId);
                }
                if (!responseDTO.isError()) {
                    //throttle for matching resource
                    return InboundWebsocketProcessorUtil.doThrottleForGraphQL(msgSize,
                            graphQLOperationDTO.getVerbInfoDTO(), inboundMessageContext, operationId);
                }
            } else {
                responseDTO = InboundWebsocketProcessorUtil
                        .getBadRequestFrameErrorDTO("Missing mandatory id field in the message");
            }
        }
        return responseDTO;
    }

    /**
     * Check if messages is valid subscription operation execution result. Payload should consist 'type' field and its
     * value equal to either of 'data' or 'next'. The value 'data' is used in 'subscriptions-transport-ws'
     * protocol and 'next' is used in 'graphql-ws' protocol.
     *
     * @param graphQLMsg GraphQL message
     * @return true if valid operation
     */
    private boolean checkIfSubscribeMessageResponse(JSONObject graphQLMsg) {
        return graphQLMsg.getString(GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_TYPE) != null
                && GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_ARRAY_FOR_DATA.contains(
                graphQLMsg.getString(GraphQLConstants.SubscriptionConstants.PAYLOAD_FIELD_NAME_TYPE));
    }
}


text:
using System;
using Aspose.Cloud;

namespace CSharp.Section
{
    class GetAllSections
    {
        public static void Run()
        {
            string inputfile = "doc-sample.doc";
            string subdirection = "Section";

            // Upload input file from local directory to Cloud Storage
            Common.UploadFile(inputfile, subdirection);

            // Get a List of Sections from a Word Document
            WordsSectionsResponse wordsSectionsResponse = Common.WordsService.WordsSections.GetSectionsList(inputfile, Common.FOLDER);

            Console.WriteLine("\n" +  inputfile + " have " + wordsSectionsResponse.Sections.SectionLinkList.Count + " sections.");
        }
    }
}


text:
package com.intellij.codeInsight.editorActions.enter;

import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.highlighting.BraceMatcher;
import com.intellij.codeInsight.highlighting.BraceMatchingUtil;
import com.intellij.lang.ASTNode;
import com.intellij.lang.Language;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.HighlighterIterator;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.TokenType;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;

public class EnterAfterUnmatchedBraceHandler extends EnterHandlerDelegateAdapter {
  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.editorActions.enter.EnterAfterUnmatchedBraceHandler");

  @Override
  public Result preprocessEnter(@NotNull final PsiFile file, @NotNull final Editor editor, @NotNull final Ref<Integer> caretOffsetRef, @NotNull final Ref<Integer> caretAdvance,
                                @NotNull final DataContext dataContext, final EditorActionHandler originalHandler) {
    Document document = editor.getDocument();
    CharSequence text = document.getCharsSequence();
    Project project = file.getProject();
    int caretOffset = caretOffsetRef.get().intValue();
    int unmatchedLBracesNumber = getUnmatchedLBracesNumberBefore(editor, caretOffset, file.getFileType());
    if (!CodeInsightSettings.getInstance().INSERT_BRACE_ON_ENTER || unmatchedLBracesNumber <= 0) {
      return Result.Continue;
    }

    int offset = CharArrayUtil.shiftForward(text, caretOffset, " \t");
    if (offset < document.getTextLength()) {
      char c = text.charAt(offset);
      if (c != ')' && c != ']' && c != ';' && c != ',' && c != '%' && c != '<' && c != '?') {
        offset = calculateOffsetToInsertClosingBrace(file, text, offset);
        //offset = CharArrayUtil.shiftForwardUntil(text, caretOffset, "\n");
      }
    }
    offset = Math.min(offset, document.getTextLength());

    // We need to adjust indents of the text that will be moved, hence, need to insert preliminary line feed.
    // Example:
    //     if (test1()) {
    //     } else {<caret> if (test2()) {
    //         foo();
    //     }
    // We insert here '\n}' after 'foo();' and have the following:
    //     if (test1()) {
    //     } else { if (test2()) {
    //         foo();
    //         }
    //     }
    // That is formatted incorrectly because line feed between 'else' and 'if' is not inserted yet (whole 'if' block is indent anchor
    // to 'if' code block('{}')). So, we insert temporary line feed between 'if' and 'else', correct indent and remove that temporary
    // line feed.
    int bracesToInsert = 0;
    outer:
    for (int i = caretOffset - 1; unmatchedLBracesNumber > 0 && i >= 0 && bracesToInsert < unmatchedLBracesNumber; i--) {
      char c = text.charAt(i);
      switch (c) {
        case ' ':
        case '\n':
        case '\t':
          continue;
        case '{': bracesToInsert++; break;
        default: break outer;
      }
    }
    bracesToInsert = Math.max(bracesToInsert, 1);
    document.insertString(offset, "\n" + StringUtil.repeatSymbol('}', bracesToInsert));
    document.insertString(caretOffset, "\n");
    PsiDocumentManager.getInstance(project).commitDocument(document);
    long stamp = document.getModificationStamp();
    boolean closingBraceIndentAdjusted;
    try {
      CodeStyleManager.getInstance(project).adjustLineIndent(file, new TextRange(caretOffset, offset + 2));
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    finally {
      closingBraceIndentAdjusted = stamp != document.getModificationStamp();
      document.deleteString(caretOffset, caretOffset + 1);
    }

    // There is a possible case that formatter was unable to adjust line indent for the closing brace (that is the case for plain text
    // document for example). Hence, we're trying to do the manually.
    if (!closingBraceIndentAdjusted) {
      int line = document.getLineNumber(offset);
      StringBuilder buffer = new StringBuilder();
      int start = document.getLineStartOffset(line);
      int end = document.getLineEndOffset(line);
      for (int i = start; i < end; i++) {
        char c = text.charAt(i);
        if (c != ' ' && c != '\t') {
          break;
        }
        else {
          buffer.append(c);
        }
      }
      if (buffer.length() > 0) {
        document.insertString(offset + 1, buffer);
      }
    }

    return Result.DefaultForceIndent;
  }

  /**
   * Current handler inserts closing curly brace (right brace) if necessary. There is a possible case that it should be located
   * more than one line forward.
   *

   * Example
   *

   *     if (test1()) {
   *     } else {<caret> if (test2()) {
   *         foo();
   *     }
   *

   *

   * We want to get this after the processing:
   *

   *     if (test1()) {
   *     } else {
   *         if (test2()) {
   *             foo();
   *         }
   *     }
   *

   * I.e. closing brace should be inserted two lines below current caret line. Hence, we need to calculate correct offset
   * to use for brace inserting. This method is responsible for that.
   *

   * In essence it inspects PSI structure and finds PSE elements with the max length that starts at caret offset. End offset
   * of that element is used as an insertion point.
   *
   * @param file    target PSI file
   * @param text    text from the given file
   * @param offset  target offset where line feed will be inserted
   * @return        offset to use for inserting closing brace
   */
  private static int calculateOffsetToInsertClosingBrace(PsiFile file, CharSequence text, final int offset) {
    PsiElement element = PsiUtilCore.getElementAtOffset(file, offset);
    ASTNode node = element.getNode();
    if (node != null && node.getElementType() == TokenType.WHITE_SPACE) {
      return CharArrayUtil.shiftForwardUntil(text, offset, "\n");
    }
    for (PsiElement parent = element.getParent(); parent != null; parent = parent.getParent()) {
      ASTNode parentNode = parent.getNode();
      if (parentNode == null || parentNode.getStartOffset() != offset) {
        break;
      }
      element = parent;
    }
    if (element.getTextOffset() != offset) {
      return CharArrayUtil.shiftForwardUntil(text, offset, "\n");
    }
    else {
      return element.getTextRange().getEndOffset();
    }
  }

  public static boolean isAfterUnmatchedLBrace(Editor editor, int offset, FileType fileType) {
    return getUnmatchedLBracesNumberBefore(editor, offset, fileType) > 0;
  }

  /**
   * Calculates number of unmatched left braces before the given offset.
   *
   * @param editor    target editor
   * @param offset    target offset
   * @param fileType  target file type
   * @return          number of unmatched braces before the given offset;
   *                  negative value if it's not possible to perform the calculation or if there are no unmatched left braces before
   *                  the given offset
   */
  private static int getUnmatchedLBracesNumberBefore(Editor editor, int offset, FileType fileType) {
    if (offset == 0) {
      return -1;
    }
    CharSequence chars = editor.getDocument().getCharsSequence();
    if (chars.charAt(offset - 1) != '{') {
      return -1;
    }

    EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter();
    HighlighterIterator iterator = highlighter.createIterator(offset - 1);
    BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);

    if (!braceMatcher.isLBraceToken(iterator, chars, fileType) || !braceMatcher.isStructuralBrace(iterator, chars, fileType)) {
      return -1;
    }

    Language language = iterator.getTokenType().getLanguage();

    iterator = highlighter.createIterator(0);
    int lBracesBeforeOffset = 0;
    int lBracesAfterOffset = 0;
    int rBracesBeforeOffset = 0;
    int rBracesAfterOffset = 0;
    for (; !iterator.atEnd(); iterator.advance()) {
      IElementType tokenType = iterator.getTokenType();
      if (!tokenType.getLanguage().equals(language) || !braceMatcher.isStructuralBrace(iterator, chars, fileType)) {
        continue;
      }

      boolean beforeOffset = iterator.getStart() < offset;

      if (braceMatcher.isLBraceToken(iterator, chars, fileType)) {
        if (beforeOffset) {
          lBracesBeforeOffset++;
        }
        else {
          lBracesAfterOffset++;
        }
      }
      else if (braceMatcher.isRBraceToken(iterator, chars, fileType)) {
        if (beforeOffset) {
          rBracesBeforeOffset++;
        }
        else {
          rBracesAfterOffset++;
        }
      }
    }

    return lBracesBeforeOffset - rBracesBeforeOffset - (rBracesAfterOffset - lBracesAfterOffset);
  }
}


text:
#ifndef CZMAP_H
#define CZMAP_H

#include "czrect.h"

struct czmap;
typedef struct czmap czmap;

typedef void (*czwalkfunc)(czrect rect, void * data, void * priv);
typedef void (*czdestroyfunc)(void * data);

typedef enum czmap_copy_status {
    CZMAP_COPY_OK,
    CZMAP_COPY_NOSPACE
} czmap_copy_status;

czmap * czmap_create(unsigned width, unsigned height);
void czmap_destroy(czmap * map, czdestroyfunc func);
czrect czmap_lease(czmap * map, unsigned width, unsigned height, void * data);
void czmap_foreach(czmap * map, czwalkfunc func, void * priv);
czmap_copy_status czmap_copy(czmap * src, czmap * dst);

#endif


text:
"use strict";

var fs = require('fs');
var MemoryStream = require('memorystream');
var path = require('path');
var should = require('should');
var sprite = require('../index.js');

describe('spritemaker', function() {
	it('sprites two equally sized items (svg output)', function(done) {
		var expected = fs.readFileSync(__dirname + '/svg/test1/output.svg', 'utf-8');

		var files = [
			'svg/rect-10-blue.svg',
			'svg/rect-10-red.svg'
		];

		var files2 = files.map(function(item) {
			return {
				stream: fs.createReadStream(__dirname + '/' + item),
				id: path.basename(item, '.svg')
			};
		});

		var generated = MemoryStream.createWriteStream();

		var output = sprite(files2);

		output.pipe(generated);
		output.on('end', function() {
			generated.toString().should.eql(expected);
			done();
		});
	});

	it('sprites two equally sized items (packed event)', function(done) {
		var expected = fs.readFileSync(__dirname + '/svg/test1/output.svg', 'utf-8');

		var files = [
			'svg/rect-10-blue.svg',
			'svg/rect-10-red.svg'
		];

		var files2 = files.map(function(item) {
			return {
				stream: fs.createReadStream(__dirname + '/' + item),
				id: path.basename(item, '.svg')
			};
		});

		var generated = MemoryStream.createWriteStream();

		var output = sprite(files2);
		output.on('packed', function(data) {
			data.width.should.eql(20);
			data.height.should.eql(10);
			data.items.should.have.property('length')
			data.items[0].should.eql({
				id: 'rect-10-blue',
				x: 0,
				y: 0,
				width: 10,
				height: 10
			});
			data.items[1].should.eql({
				id: 'rect-10-red',
				x: 10,
				y: 0,
				width: 10,
				height: 10
			});
			done();
		});
	});
});


text:
<?xml version="1.0"?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://jboss.org/schema/arquillian"
  xsi:schemaLocation="http://jboss.org/schema/arquillian
    http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

  <extension qualifier="docker">
    <property name="machineName">dev</property>
    <property name="dockerContainersFile">docker-compose.yml</property>
    <property name="cubeSpecificProperties">
      helloworld:
        await:
          strategy: sleeping
          sleepTime: 2 s
    </property>
  </extension>

  <extension qualifier="graphene">
    <property name="url">http://helloworld:80</property>
  </extension>

</arquillian>


text:
NationBuilder
=============

`NationBuilder supports OAuth2`_ as their authentication mechanism. Follow these
steps in order to use it:

- Register a new application at your `Nation Admin panel`_ (define the `Callback
  URL` to ``http://example.com/complete/nationbuilder/`` where ``example.com``
  is your domain).

- Fill the ``Client ID`` and ``Client Secret`` values from the newly created
  application::

    SOCIAL_AUTH_NATIONBUILDER_KEY = ''
    SOCIAL_AUTH_NATIONBUILDER_SECRET = ''

- Also define your NationBuilder slug::

    SOCIAL_AUTH_NATIONBUILDER_SLUG = 'your-nationbuilder-slug'

- Enable the backend in ``AUTHENTICATION_BACKENDS`` setting::

    AUTHENTICATION_BACKENDS = (
        ...
        'social.backends.nationbuilder.NationBuilderOAuth2'
        ...
    )

.. _Nation Admin panel: https://psa.nationbuilder.com/admin/apps
.. _NationBuilder supports OAuth2: http://nationbuilder.com/api_quickstart


text:
namespace nwc_toolkit {

class HtmlAttribute {
 public:
  HtmlAttribute() : name_(), value_() {}

  const String &name() const {
    return name_;
  }
  const String &value() const {
    return value_;
  }

  void set_name(const String &name) {
    name_ = name;
  }
  void set_value(const String &value) {
    value_ = value;
  }

  void Clear() {
    name_.Clear();
    value_.Clear();
  }

 private:
  String name_;
  String value_;

  // Copyable.
};

}  // namespace nwc_toolkit

#endif  // NWC_TOOLKIT_HTML_ATTRIBUTE_H_


text:
#ifndef __EFI_COMPONENT_NAME_H__
#define __EFI_COMPONENT_NAME_H__

///
/// The global ID for the Component Name Protocol.
///
#define EFI_COMPONENT_NAME_PROTOCOL_GUID \
  { \
    0x107a772c, 0xd5e1, 0x11d4, {0x9a, 0x46, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d } \
  }

typedef struct _EFI_COMPONENT_NAME_PROTOCOL  EFI_COMPONENT_NAME_PROTOCOL;

/**
  Retrieves a Unicode string that is the user-readable name of the EFI Driver.

  @param  This       A pointer to the EFI_COMPONENT_NAME_PROTOCOL instance.
  @param  Language   A pointer to a three-character ISO 639-2 language identifier.
                     This is the language of the driver name that that the caller
                     is requesting, and it must match one of the languages specified
                     in SupportedLanguages.  The number of languages supported by a
                     driver is up to the driver writer.
  @param  DriverName A pointer to the Unicode string to return.  This Unicode string
                     is the name of the driver specified by This in the language
                     specified by Language.

  @retval EFI_SUCCESS           The Unicode string for the Driver specified by This
                                and the language specified by Language was returned
                                in DriverName.
  @retval EFI_INVALID_PARAMETER Language is NULL.
  @retval EFI_INVALID_PARAMETER DriverName is NULL.
  @retval EFI_UNSUPPORTED       The driver specified by This does not support the
                                language specified by Language.

**/
typedef
EFI_STATUS
(EFIAPI *EFI_COMPONENT_NAME_GET_DRIVER_NAME)(
  IN EFI_COMPONENT_NAME_PROTOCOL           *This,
  IN  CHAR8                                *Language,
  OUT CHAR16                               **DriverName
  );

/**
  Retrieves a Unicode string that is the user readable name of the controller
  that is being managed by an EFI Driver.

  @param  This             A pointer to the EFI_COMPONENT_NAME_PROTOCOL instance.
  @param  ControllerHandle The handle of a controller that the driver specified by
                           This is managing.  This handle specifies the controller
                           whose name is to be returned.
  @param  ChildHandle      The handle of the child controller to retrieve the name
                           of.  This is an optional parameter that may be NULL.  It
                           will be NULL for device drivers.  It will also be NULL
                           for a bus drivers that wish to retrieve the name of the
                           bus controller.  It will not be NULL for a bus driver
                           that wishes to retrieve the name of a child controller.
  @param  Language         A pointer to a three character ISO 639-2 language
                           identifier.  This is the language of the controller name
                           that the caller is requesting, and it must match one
                           of the languages specified in SupportedLanguages.  The
                           number of languages supported by a driver is up to the
                           driver writer.
  @param  ControllerName   A pointer to the Unicode string to return.  This Unicode
                           string is the name of the controller specified by
                           ControllerHandle and ChildHandle in the language specified
                           by Language, from the point of view of the driver specified
                           by This.

  @retval EFI_SUCCESS           The Unicode string for the user-readable name in the
                                language specified by Language for the driver
                                specified by This was returned in DriverName.
  @retval EFI_INVALID_PARAMETER ControllerHandle is NULL.
  @retval EFI_INVALID_PARAMETER ChildHandle is not NULL and it is not a valid EFI_HANDLE.
  @retval EFI_INVALID_PARAMETER Language is NULL.
  @retval EFI_INVALID_PARAMETER ControllerName is NULL.
  @retval EFI_UNSUPPORTED       The driver specified by This is not currently managing
                                the controller specified by ControllerHandle and
                                ChildHandle.
  @retval EFI_UNSUPPORTED       The driver specified by This does not support the
                                language specified by Language.

**/
typedef
EFI_STATUS
(EFIAPI *EFI_COMPONENT_NAME_GET_CONTROLLER_NAME)(
  IN EFI_COMPONENT_NAME_PROTOCOL                              *This,
  IN  EFI_HANDLE                                              ControllerHandle,
  IN  EFI_HANDLE                                              ChildHandle        OPTIONAL,
  IN  CHAR8                                                   *Language,
  OUT CHAR16                                                  **ControllerName
  );

///
/// This protocol is used to retrieve user readable names of drivers
/// and controllers managed by UEFI Drivers.
///
struct _EFI_COMPONENT_NAME_PROTOCOL {
  EFI_COMPONENT_NAME_GET_DRIVER_NAME      GetDriverName;
  EFI_COMPONENT_NAME_GET_CONTROLLER_NAME  GetControllerName;
  ///
  /// A Null-terminated ASCII string that contains one or more
  /// ISO 639-2 language codes. This is the list of language codes
  /// that this protocol supports.
  ///
  CHAR8                                   *SupportedLanguages;
};

extern EFI_GUID gEfiComponentNameProtocolGuid;

#endif


text:
const Storage = require('./../storage.js');

class DemoStorage extends Storage {

}

module.exports = new DemoStorage();


text:
package org.jclouds.orion.internal;

import org.jclouds.apis.BaseApiLiveTest;
import org.jclouds.orion.OrionApi;

/**
 * @author Timur Sungur
 */
public class BaseOrionApiLiveTest extends BaseApiLiveTest<OrionApi> {

	public BaseOrionApiLiveTest() {
		this.provider = "orion";
	}

}


text:
package com.github.sviperll.text;

/**
 * Can be rendered.
 *

 * <tt>{@code Renderable<Html> }</tt> is supposed to generate
 * html output.
 *
 * @param <T> marks given renderable with it's format
 *
 * @author Victor Nazarov <asviraspossible@gmail.com>
 */
public interface Renderable<T> {

    /**
     * Creates Renderer object that can be called to write out actual rendered text.
     *

     * Any appendable can be used as argument: StringBuilder, Writer, OutputStream
     *
     * @param appendable appendable to write rendered text to
     * @return Renderer object
     */
    Renderer createRenderer(Appendable appendable);
}


text:
Implements the Windmill Chess Engine into the Symfony Framework.

[![Build Status](https://img.shields.io/travis/cleentfaar/CLWindmillBundle/master.svg?style=flat-square)](https://travis-ci.org/cleentfaar/CLWindmillBundle)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/cleentfaar/CLWindmillBundle.svg?style=flat-square)](https://scrutinizer-ci.com/g/cleentfaar/CLWindmillBundle/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/cleentfaar/CLWindmillBundle.svg?style=flat-square)](https://scrutinizer-ci.com/g/cleentfaar/CLWindmillBundle)
[![Latest Version](https://img.shields.io/github/release/cleentfaar/CLWindmillBundle.svg?style=flat-square)](https://github.com/cleentfaar/CLWindmillBundle/releases)
[![Total Downloads](https://img.shields.io/packagist/dt/cleentfaar/windmill-bundle.svg?style=flat-square)](https://packagist.org/packages/cleentfaar/CLWindmillBundle)

# Features

- Play and store chess games through easy-to-use services (check out the [GameController](https://github.com/cleentfaar/CLWindmillBundle/tree/master/Controller/GameController.php))
- Storage currently only has `file` and `orm` adapters, but you can easily add your own (check out the [OrmAdapter](https://github.com/cleentfaar/windmill/tree/master/Storage/Adapter/OrmAdapter.php) for an example).
- Custom Twig extension with some useful methods so you can display chess games anywhere in your templates (check out the [game-template](https://github.com/cleentfaar/CLWindmillBundle/tree/master/Resources/views/Game/index.html.twig)).
- [Console commands](https://github.com/cleentfaar/CLWindmillBundle/tree/master/Resources/doc/commands.md) so you can even play a game of chess through the Symfony Console!

Check out the documentation below for more information on using these features.

## Documentation

Check out [the index](https://github.com/cleentfaar/CLWindmillBundle/tree/master/Resources/doc/index.md).

Don't forget to also check out the [library's documentation](https://github.com/cleentfaar/windmill) which this bundle
implements! It contains more detailed information on the many components (or will do so soon anyway!).

## Why the bundle?

The aim of this bundle is to make it easier to work with the many (decoupled, but related) services inside the engine by
using the same DIC and templating patterns that are already provided by the framework. Since I use the Symfony Framework
for almost all of my own projects, it has become much easier to just adopt my work on their fundamentals.

Like my other projects, I'm also using this to learn working with some techniques I haven't used before.

For this project, a few of them are:
- Make it easy to configure different templates for different sections of a chess game
- Check out other goals in the library's documentation [here](https://github.com/cleentfaar/windmill).


text:
/* Includes ------------------------------------------------------------------*/

#include "main.h"

/** @addtogroup X_NUCLEO_IKS01A1_Examples
  * @{
  */

/** @addtogroup SINGLE_DOUBLE_TAP
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
typedef enum
{
  MODE_DEFAULT    = 0,
  MODE_SINGLE_TAP = 1,
  MODE_DOUBLE_TAP = 2
} Mode_t;

/* Private define ------------------------------------------------------------*/

#define SINGLE_TAP_INDICATION_DELAY  100  /* LED is ON for this period [ms]. */
#define DOUBLE_TAP_INDICATION_DELAY  100  /* LED is ON for this period [ms]. */
#define INDICATION_WAIT_DELAY        100  /* LED is locked OFF for this period [ms]. */

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/

static volatile uint8_t mems_event_detected  = 0;

static volatile uint8_t single_tap_mode_request = 1;
static volatile uint8_t double_tap_mode_request = 0;
static volatile uint8_t default_mode_request    = 0;

static Mode_t mode = MODE_DEFAULT;

static void *LSM6DS3_X_0_handle = NULL;

/* Private function prototypes -----------------------------------------------*/
static void initializeAllSensors( void );
static void enableAllSensors( void );

/* Private functions ---------------------------------------------------------*/

/**
 * @brief  Main function is to show how to detect the single and double tap events using the sensor expansion board and a STM32 Nucleo board.
 *         After application is started, the user can try to tap the STM32 Nucleo board; when the single tap is detected,
 *         the LED is switched on for a while. Press the user button to pass from the single tap detection to the double tap detection feature.
 *         When the double tap is detected, the LED is switched on twice for a while. Press again the user button to disable the single/double tap detection feature.
 *         Press the user button to enable again the single tap detection feature.
 * @param  None
 * @retval Integer
 */
int main( void )
{

  ACCELERO_Event_Status_t status;

  /* STM32F4xx HAL library initialization:
  - Configure the Flash prefetch, instruction and Data caches
  - Configure the Systick to generate an interrupt each 1 msec
  - Set NVIC Group Priority to 4
  - Global MSP (MCU Support Package) initialization
  */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize LED */
  BSP_LED_Init( LED2 );

  /* Initialize button */
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);

  /* Initialize all sensors */
  initializeAllSensors();
  /* Enable all sensors */
  enableAllSensors();

  while (1)
  {

    if ( mems_event_detected == 1 )
    {
      mems_event_detected = 0;

      if(mode == MODE_SINGLE_TAP)
      {
        if ( BSP_ACCELERO_Get_Event_Status_Ext( LSM6DS3_X_0_handle, &status ) == COMPONENT_OK )
        {
          if ( status.TapStatus != 0 )
          {
            BSP_LED_On( LED2 );
            HAL_Delay( SINGLE_TAP_INDICATION_DELAY );
            BSP_LED_Off( LED2 );
            HAL_Delay( INDICATION_WAIT_DELAY );
          }
        }
      }
      else if(mode == MODE_DOUBLE_TAP)
      {
        if ( BSP_ACCELERO_Get_Event_Status_Ext( LSM6DS3_X_0_handle, &status ) == COMPONENT_OK )
        {
          if ( status.DoubleTapStatus != 0 )
          {
            BSP_LED_On( LED2 );
            HAL_Delay( DOUBLE_TAP_INDICATION_DELAY );
            BSP_LED_Off( LED2 );
            HAL_Delay( INDICATION_WAIT_DELAY );
            BSP_LED_On( LED2 );
            HAL_Delay( DOUBLE_TAP_INDICATION_DELAY );
            BSP_LED_Off( LED2 );
            HAL_Delay( INDICATION_WAIT_DELAY );
          }
        }
      }
    }

    if ( single_tap_mode_request == 1 )
    {
      if ( BSP_ACCELERO_Enable_Single_Tap_Detection_Ext( LSM6DS3_X_0_handle, INT1_PIN ) == COMPONENT_OK )
      {
        mode = MODE_SINGLE_TAP;
        single_tap_mode_request = 0;
      }
    }

    if ( double_tap_mode_request == 1 )
    {
      if ( BSP_ACCELERO_Disable_Single_Tap_Detection_Ext( LSM6DS3_X_0_handle ) == COMPONENT_OK )
      {
        if ( BSP_ACCELERO_Enable_Double_Tap_Detection_Ext( LSM6DS3_X_0_handle, INT1_PIN ) == COMPONENT_OK )
        {
          mode = MODE_DOUBLE_TAP;
          double_tap_mode_request = 0;
        }
      }
    }

    if ( default_mode_request == 1 )
    {
      if ( BSP_ACCELERO_Disable_Double_Tap_Detection_Ext( LSM6DS3_X_0_handle ) == COMPONENT_OK )
      {
        mode = MODE_DEFAULT;
        default_mode_request = 0;
      }
    }
  }
}

/**
 * @brief  Initialize all sensors
 * @param  None
 * @retval None
 */
static void initializeAllSensors( void )
{

  if(BSP_ACCELERO_Init( LSM6DS3_X_0, &LSM6DS3_X_0_handle ) == COMPONENT_ERROR)
  {
    /* LSM6DS3 not detected, switch on LED2 and go to infinity loop */
    BSP_LED_On( LED2 );
    while (1)
    {}
  }
}

/**
 * @brief  Enable all sensors
 * @param  None
 * @retval None
 */
static void enableAllSensors( void )
{

  BSP_ACCELERO_Sensor_Enable( LSM6DS3_X_0_handle );
}

/**
 * @brief  EXTI line detection callbacks
 * @param  GPIO_Pin: Specifies the pins connected EXTI line
 * @retval None
 */
void HAL_GPIO_EXTI_Callback( uint16_t GPIO_Pin )
{

  /* User button. */
  if(GPIO_Pin == KEY_BUTTON_PIN)
  {
    if ( BSP_PB_GetState( BUTTON_KEY ) == GPIO_PIN_RESET )
    {
      if ( mode == MODE_DEFAULT )
      {
        single_tap_mode_request = 1;
      }

      else if ( mode == MODE_SINGLE_TAP )
      {
        double_tap_mode_request = 1;
      }

      else if ( mode == MODE_DOUBLE_TAP )
      {
        default_mode_request = 1;
      }

      /* ERROR. */
      else
      {
        Error_Handler();
      }
    }
  }

  /* Single tap or double tap detection (available only for LSM6DS3 sensor). */
  else if ( GPIO_Pin == M_INT1_PIN )
  {
    mems_event_detected = 1;
  }

  /* ERROR. */
  else
  {
    Error_Handler();
  }
}

/**
 * @brief  This function is executed in case of error occurrence
 * @param  None
 * @retval None
 */
void Error_Handler( void )
{

  while (1)
  {}
}

#ifdef  USE_FULL_ASSERT

/**
 * @brief  Reports the name of the source file and the source line number
 *   where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed( uint8_t* file, uint32_t line )
{

  /* User can add his own implementation to report the file name and line number,
  ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {}
}
#endif

/**
 * @}
 */

/**
 * @}
 */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
namespace ChalmersxTools.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class AddCoordinateEarthSpheresImages : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(AddCoordinateEarthSpheresImages));

        string IMigrationMetadata.Id
        {
            get { return "201601221152483_AddCoordinateEarthSpheresImages"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
module.exports = memo;

// like async memoize but, does not memoize errors and does works for async functions that do not take parameters
function memo(asyncFn) {
  let queue = [];
  let result;

  function doWork() {
    asyncFn(function(err, r) {
      if (!err) {
        result = r;
      }
      queue.forEach(fn => fn(err, result));
      queue = [];
    });
  }

  function memoized(fn) {
    if (result) {
      setImmediate(() => fn(null, result));
      return;
    }
    queue.push(fn);
    if (queue.length === 1) {
      doWork();
    }
  }

  return memoized;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;

namespace ThreadSync
{
    public partial class MainPage : UserControl
    {
        SynchronizationContext _sync;

        public MainPage()
        {
            InitializeComponent();
            _sync = SynchronizationContext.Current;
        }

        private void goButton_Click(object sender, RoutedEventArgs e)
        {
            goButton.IsEnabled = false;
            int count = Convert.ToInt32(valueNumericUpDown.Value);
            Thread worker = new Thread(DoWork);
            worker.Name = "My Worker Thread";
            worker.Start(count);
        }

        // Executed on a worker thread
        void DoWork(object arg)
        {
            // Flag
            bool cancelled = false;

            // Wait handle
            var wait = new AutoResetEvent(false);

            int count = (int)arg;
            for (int i = 0; i < count; i++)
            {
                // Pause
                Thread.Sleep(500);

                // Get max
                int max = 0;
                //Dispatcher.BeginInvoke(() =>
                //    {
                //        int.TryParse(maxTextBox.Text, out max);
                //        wait.Set();
                //    });
                _sync.Post(o =>
                {
                    int.TryParse(maxTextBox.Text, out max);
                    wait.Set();
                }, null);
                wait.WaitOne();

                // See if we're at the max
                int val = (i + 1) * 10;
                if (val == max)
                {
                    // Prompt the user to continue
                    //Dispatcher.BeginInvoke(() =>
                    //{
                    //    QueryUserDialog dialog = new QueryUserDialog();
                    //    dialog.Closed += (s, ea) =>
                    //    {
                    //        // Set the flag
                    //        cancelled = (dialog.DialogResult == false);

                    //        // Signal the wait handle
                    //        wait.Set();
                    //    };
                    //    dialog.Show();
                    //});
                    _sync.Post(o =>
                    {
                        QueryUserDialog dialog = new QueryUserDialog();
                        dialog.Closed += (s, ea) =>
                        {
                            // Set the flag
                            cancelled = (dialog.DialogResult == false);

                            // Signal the wait handle
                            wait.Set();
                        };
                        dialog.Show();
                    }, null);

                    // Here we want to pause for the user
                    wait.WaitOne();

                    // Exit loop if cancelled
                    if (cancelled) break;
                }

                // Marshall call to the UI thread to set result
                //Dispatcher.BeginInvoke((Action<int>)(n => resultLabel.Text = n.ToString()), val);
                _sync.Post(n => resultLabel.Content = n.ToString(), val);
            }

            //Dispatcher.BeginInvoke(() => goButton.IsEnabled = true);
            _sync.Post(o => goButton.IsEnabled = true, null);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_main_download"
        android:icon="@mipmap/ic_action_download"
        android:title="@string/download"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/menu_main_search"
        android:icon="@mipmap/ic_action_search"
        android:title="@string/search"
        app:showAsAction="ifRoom" />

    <!-- <item
        android:id="@+id/menu_main_notify"
        android:icon="@drawable/ic_action_notify"
        android:title="@string/search"
        app:showAsAction="ifRoom" /> -->

    <!--<item
        android:id="@+id/menu_main_about"
        android:title="@string/about"
        app:showAsAction="never" />-->

    <!-- <item
        android:id="@+id/menu_main_exit"
        android:title="@string/exit"
        app:showAsAction="never" /> -->

</menu>


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GameRayBurst.FtLinq.Tests
{
    class CustomizableList<T> : IList<T>
    {
        public virtual IEnumerator<T> GetEnumerator()
        {
            throw new AssertFailedException();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public virtual void Add(T item)
        {
            throw new AssertFailedException();
        }

        public virtual void Clear()
        {
            throw new AssertFailedException();
        }

        public virtual bool Contains(T item)
        {
            throw new AssertFailedException();
        }

        public virtual void CopyTo(T[] array, int arrayIndex)
        {
            throw new AssertFailedException();
        }

        public virtual bool Remove(T item)
        {
            throw new AssertFailedException();
        }

        public virtual int Count
        {
            get { throw new AssertFailedException(); }
        }

        public virtual bool IsReadOnly
        {
            get { throw new AssertFailedException(); }
        }

        public virtual int IndexOf(T item)
        {
            throw new AssertFailedException();
        }

        public virtual void Insert(int index, T item)
        {
            throw new NotImplementedException();
        }

        public virtual void RemoveAt(int index)
        {
            throw new AssertFailedException();
        }

        public virtual T this[int index]
        {
            get { throw new AssertFailedException(); }
            set { throw new AssertFailedException(); }
        }
    }
}


text:
(function () {
var nonbreaking = (function () {
  'use strict';

  var global = tinymce.util.Tools.resolve('tinymce.PluginManager');

  var stringRepeat = function (string, repeats) {
    var str = '';
    for (var index = 0; index < repeats; index++) {
      str += string;
    }
    return str;
  };
  var isVisualCharsEnabled = function (editor) {
    return editor.plugins.visualchars ? editor.plugins.visualchars.isEnabled() : false;
  };
  var insertNbsp = function (editor, times) {
    var nbsp = isVisualCharsEnabled(editor) ? ' ' : ' ';
    editor.insertContent(stringRepeat(nbsp, times));
    editor.dom.setAttrib(editor.dom.select('span.mce-nbsp'), 'data-mce-bogus', '1');
  };
  var $_7trhbvhtjkmcwpiv = { insertNbsp: insertNbsp };

  var register = function (editor) {
    editor.addCommand('mceNonBreaking', function () {
      $_7trhbvhtjkmcwpiv.insertNbsp(editor, 1);
    });
  };
  var $_5ig86ghsjkmcwpiu = { register: register };

  var global$1 = tinymce.util.Tools.resolve('tinymce.util.VK');

  var getKeyboardSpaces = function (editor) {
    var spaces = editor.getParam('nonbreaking_force_tab', 0);
    if (typeof spaces === 'boolean') {
      return spaces === true ? 3 : 0;
    } else {
      return spaces;
    }
  };
  var $_3yn1oxhwjkmcwpix = { getKeyboardSpaces: getKeyboardSpaces };

  var setup = function (editor) {
    var spaces = $_3yn1oxhwjkmcwpix.getKeyboardSpaces(editor);
    if (spaces > 0) {
      editor.on('keydown', function (e) {
        if (e.keyCode === global$1.TAB && !e.isDefaultPrevented()) {
          if (e.shiftKey) {
            return;
          }
          e.preventDefault();
          e.stopImmediatePropagation();
          $_7trhbvhtjkmcwpiv.insertNbsp(editor, spaces);
        }
      });
    }
  };
  var $_evh9pjhujkmcwpiw = { setup: setup };

  var register$1 = function (editor) {
    editor.addButton('nonbreaking', {
      title: 'Nonbreaking space',
      cmd: 'mceNonBreaking'
    });
    editor.addMenuItem('nonbreaking', {
      icon: 'nonbreaking',
      text: 'Nonbreaking space',
      cmd: 'mceNonBreaking',
      context: 'insert'
    });
  };
  var $_4xbhqnhxjkmcwpiz = { register: register$1 };

  global.add('nonbreaking', function (editor) {
    $_5ig86ghsjkmcwpiu.register(editor);
    $_4xbhqnhxjkmcwpiz.register(editor);
    $_evh9pjhujkmcwpiw.setup(editor);
  });
  function Plugin () {
  }

  return Plugin;

}());
})();


text:
require 'spec_helper'

describe Hutch::ErrorHandlers::Honeybadger do
  let(:error_handler) { Hutch::ErrorHandlers::Honeybadger.new }

  describe '#handle' do
    let(:error) do
      begin
        raise "Stuff went wrong"
      rescue RuntimeError => err
        err
      end
    end

    it "logs the error to Honeybadger" do
      message_id = "1"
      payload = "{}"
      consumer = double
      ex = error
      message = {
        :error_class => ex.class.name,
          :error_message => "#{ ex.class.name }: #{ ex.message }",
          :backtrace => ex.backtrace,
          :context => {
            :message_id => message_id,
            :consumer => consumer
          },
          :parameters => {
            :payload => payload
          }
      }
      expect(::Honeybadger).to receive(:notify_or_ignore).with(message)
      error_handler.handle(message_id, payload, consumer, ex)
    end
  end
end


text:
package com.lamfire.simplecache;

public class Caches {

    public static <K, V> Cache<K, V> makeFifoCache(int maxElementsInCache, long timeToLiveMillis) {
        return new FIFOCache<K, V>(maxElementsInCache, timeToLiveMillis);
    }

    public static <K, V> Cache<K, V> makeLruCache(int maxElementsInCache, long timeToLiveMillis) {
        return new LRUCache<K, V>(maxElementsInCache, timeToLiveMillis);
    }
}


text:
{% extends 'pages/base.html' %}

{% block prerender %}
  <link rel="prerender" href="/library">
{% endblock prerender %}

{% block maintitle %}
  I18N_SPLASH_PAGE_TITLE
{% endblock maintitle %}

{% block header_js %}
  {{ super() }}
{% endblock %}

{% block navbar_breadcrumb %}
{% endblock navbar_breadcrumb %}

{% block content %}

Volunteer teaching on your own schedule

          Create online lessons at a time that suits you.

            <img ng-src="<[getStaticImageUrl('/splash/books.svg')]>" class="oppia-splash-books" style="margin-left: -250px; width: 500px; top: 95px;" alt="">

            <img ng-src="<[getStaticSubjectImageUrl('Humor')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Combinatorics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Cooking')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Government')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Architecture')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('History')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Microbiology')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Engineering')]>" class="oppia-splash-background-icon" alt="">

            <img ng-src="<[getStaticSubjectImageUrl('Algorithms')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Economics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Computing')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Reading')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Art')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Creativity')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Physics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Language')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Arithmetic')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Chess')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Astronomy')]>" class="oppia-splash-background-icon" alt="">

            <img ng-src="<[getStaticSubjectImageUrl('Religion')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Mathematics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Philosophy')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Humor')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Combinatorics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Cooking')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Government')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Architecture')]>" class="oppia-splash-background-icon" alt="">

            <img ng-src="<[getStaticSubjectImageUrl('Genetics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Space')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Algebra')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Music')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Chemistry')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Poetry')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Puzzles')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Calculus')]>" class="oppia-splash-background-icon" alt="">

            <img ng-src="<[getStaticSubjectImageUrl('Business')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Geography')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Biology')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Genetics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Space')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Algebra')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Music')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Chemistry')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Poetry')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Puzzles')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Calculus')]>" class="oppia-splash-background-icon" alt="">

            <img ng-src="<[getStaticSubjectImageUrl('Business')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Geography')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Biology')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Genetics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Space')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Algebra')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Music')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Chemistry')]>" class="oppia-splash-background-icon" alt="">

            <img ng-src="<[getStaticSubjectImageUrl('Economics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Algorithms')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Creativity')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Astronomy')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Chess')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Arithmetic')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Language')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Physics')]>" class="oppia-splash-background-icon" alt="">

            <img ng-src="<[getStaticSubjectImageUrl('Combinatorics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Humor')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Philosophy')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Mathematics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Religion')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Cooking')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Engineering')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Microbiology')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('History')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Architecture')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Government')]>" class="oppia-splash-background-icon" alt="">

            <img ng-src="<[getStaticSubjectImageUrl('Art')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Reading')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Computing')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Economics')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Algorithms')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Creativity')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Astronomy')]>" class="oppia-splash-background-icon" alt="">
            <img ng-src="<[getStaticSubjectImageUrl('Chess')]>" class="oppia-splash-background-icon" alt="">

          <button type="button"
                  ng-if="!userIsLoggedIn"
                  ng-click="onRedirectToLogin('/creator_dashboard?mode=create')"
                  class="btn oppia-splash-button oppia-splash-button-create oppia-transition-200"
                  style="left: -webkit-calc(130px + 15%); left: -moz-calc(130px + 15%); left: -o-calc(130px + 15%); left: calc(130px + 15%); bottom: 210px; z-index: 10;"
                  translate="I18N_ACTION_CREATE_LESSON">
          </button>
          <button type="button"
                  ng-if="userIsLoggedIn"
                  ng-click="onClickCreateExplorationButton()"
                  class="btn oppia-splash-button oppia-splash-button-create oppia-transition-200"
                  style="left: -webkit-calc(130px + 15%); left: -moz-calc(130px + 15%); left: -o-calc(130px + 15%); left: calc(130px + 15%); bottom: 210px; z-index: 10;"
                  translate="I18N_ACTION_CREATE_LESSON">
          </button>
          <button type="button" ng-click="onClickBrowseLibraryButton()"
                  class="btn oppia-splash-button oppia-splash-button-browse oppia-transition-200"
                  style="left: -webkit-calc(130px + 15%); left: -moz-calc(130px + 15%); left: -o-calc(130px + 15%); left: calc(130px + 15%); bottom: 150px; font-size: 0.93em; z-index: 10;"
                  translate="I18N_ACTION_BROWSE_LESSONS">
          </button>

            <img ng-src="<[getStaticImageUrl('/splash/bullet1icon.svg')]>" class="oppia-splash-overlapping-image-1" alt="">

            If you want to volunteer your time to teach, but have a busy
            schedule, creating online lessons lets you reach students without
            needing to fit their schedules. Students can go through your lessons
            whenever they want.

            <img ng-src="<[getStaticImageUrl('/splash/bullet2icon.svg')]>" alt="">

            It's easy and free to publish a lesson in Oppia. Just sign up and
            get started. You can come back and improve the lesson any time.

            <img ng-src="<[getStaticImageUrl('/splash/bullet3icon.svg')]>" alt="">

            You can also see students' progress, and use this information to
            refine your lessons.

{% endblock %}

{% block footer %}
  {% include 'pages/footer.html' %}
{% endblock %}

{% block footer_js %}
  {{ super() }}

{% endblock footer_js %}


text:
package at.bestsolution.framework.grid.emf;

import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;

import at.bestsolution.framework.grid.XGridCellMetaData;

/**
 * Meta data impl
 *
 * @param <R>
 *            row type
 */
public class GridCellMetaData<R> implements XGridCellMetaData<R> {

	@NonNull
	private final String topic;

	@Nullable
	private final Object value;

	@Nullable
	private final Object data;

	@NonNull
	private final R rowValue;

	/**
	 * Create a meta data object
	 *
	 * @param topic
	 *            the topic
	 * @param data
	 *            the data
	 * @param rowValue
	 *            the row value
	 * @param value
	 *            the value
	 */
	public GridCellMetaData(@NonNull String topic, Object data, @NonNull R rowValue, Object value) {
		this.topic = topic;
		this.data = data;
		this.value = value;
		this.rowValue = rowValue;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <V> @Nullable V getCellValue() {
		return (V) value;
	}

	@Override
	public @NonNull R getRowValue() {
		return rowValue;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <M> @Nullable M getMetaData() {
		return (M) data;
	}

	@Override
	public @NonNull String getTopic() {
		return topic;
	}

	@Override
	public String toString() {
		return "GridCellMetaData [topic=" + topic + ", value=" + value + ", data=" + data + ", rowValue=" + rowValue + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
	}
}


text:
def query_db(conn, query, args=(), one=False):
    cur = conn.execute(query, args)
    rv = cur.fetchall()
    cur.close()
    return (rv[0] if rv else None) if one else rv


text:
/**
 * @author Sergey Burlak
 * @version $Revision$
 */
package javax.swing.plaf.basic;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;

import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.JToolTip;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.ToolTipUI;

import org.apache.harmony.x.swing.Utilities;

public class BasicToolTipUI extends ToolTipUI {
    private static BasicToolTipUI toolTipUI;

    private JToolTip tooltip;
    private Color foregroundInactiveColor;
    private Color backgroundInactiveColor;

    public static ComponentUI createUI(final JComponent c) {
        if (toolTipUI == null) {
            toolTipUI = new BasicToolTipUI();
        }

        return toolTipUI;
    }

    public void installUI(final JComponent c) {
        tooltip = (JToolTip)c;

        installDefaults(tooltip);
        installListeners(tooltip);
    }

    public void uninstallUI(final JComponent c){
        installDefaults(tooltip);
        installListeners(tooltip);

        tooltip = null;
    }

    protected void installDefaults(final JComponent c) {
        LookAndFeel.installColorsAndFont(c, "ToolTip.background", "ToolTip.foreground", "ToolTip.font");
        LookAndFeel.installBorder(c, "ToolTip.border");

        backgroundInactiveColor = UIManager.getColor("ToolTip.backgroundInactive");
        foregroundInactiveColor = UIManager.getColor("ToolTip.foregroundInactive");
    }

    protected void uninstallDefaults(final JComponent c) {
        Utilities.uninstallColorsAndFont(c);
        LookAndFeel.uninstallBorder(c);

        backgroundInactiveColor = null;
        foregroundInactiveColor = null;
    }

    protected void installListeners(final JComponent c) {
    }

    protected void uninstallListeners(final JComponent c) {
    }

    public void paint(final Graphics g, final JComponent c) {
        JComponent component = tooltip.getComponent();
        if (component != null && component.isEnabled() || backgroundInactiveColor == null) {
            g.setColor(tooltip.getBackground());
            LookAndFeel.installBorder(c, "ToolTip.border");
        } else {
            g.setColor(backgroundInactiveColor);
            LookAndFeel.installBorder(c, "ToolTip.borderInactive");
        }
        g.fillRect(0, 0, tooltip.getWidth(), tooltip.getHeight());

        String tipText = tooltip.getTipText();
        FontMetrics fm = Utilities.getFontMetrics(tooltip);
        Dimension stringSize = Utilities.getStringSize(tipText, fm);
        int textX = component instanceof AbstractButton && ((AbstractButton)component).getMnemonic() != 0
                        ? 4 : (tooltip.getWidth() - stringSize.width) / 2;
        int textY = fm.getAscent();
        Color foreground = component != null && component.isEnabled() || foregroundInactiveColor == null
                                ? tooltip.getForeground()
                                : foregroundInactiveColor;
        Utilities.drawString(g, tipText, textX, textY, fm, foreground, -1);
    }

    public Dimension getPreferredSize(final JComponent c) {
        if (tooltip == null) {
            tooltip = (JToolTip)c;
        }
        Font f = c.getFont();
        if (f == null) {
            return new Dimension();
        }
        Dimension result = Utilities.getStringSize(tooltip.getTipText(), c.getFontMetrics(f));
        result.width += 6;

        return Utilities.addInsets(result, tooltip.getInsets());
    }

    public Dimension getMinimumSize(final JComponent c) {
        return getPreferredSize(c);
    }

    public Dimension getMaximumSize(final JComponent c) {
        return getPreferredSize(c);
    }
}


text:
<?php
/*
Server-side PHP file upload code for HTML5 File Drag & Drop demonstration
Featured on SitePoint.com
Developed by Craig Buckler (@craigbuckler) of OptimalWorks.net
*/
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);

if ($fn) {

	// AJAX call
	file_put_contents(
		'./images/' . $fn,
		file_get_contents('php://input')
	);
	echo "$fn uploaded";
	exit();

}
else {
	echo "$fn not uploaded";
	// form submit
	$files = $_FILES['fileselect'];

	foreach ($files['error'] as $id => $err) {
		if ($err == UPLOAD_ERR_OK) {
			$fn = $files['name'][$id];
			move_uploaded_file(
				$files['tmp_name'][$id],
				'./images/' . $fn
			);
			echo "
File $fn uploaded.
";
		}
	}

}


text:
package de.oliver_heger.linedj.io

import java.nio.file.Path

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

/**
  * Test class for ''PathUtils''.
  */
class PathUtilsSpec extends AnyFlatSpec with Matchers {
  "PathUtils" should "extract an extension from a file name" in {
    val File = "test.txt"

    PathUtils extractExtension File should be("txt")
  }

  it should "return the extension if a name contains multiple dots" in {
    val File = "/my/music/1. Test.Music.mp3"

    PathUtils extractExtension File should be("mp3")
  }

  it should "return an empty extension if a file does not have an extension" in {
    PathUtils extractExtension "fileWithoutExtension" should be("")
  }

  it should "convert a string to a Path" in {
    val Name = "music.mp3"

    val path = PathUtils asPath Name
    path.getFileName.toString should be(Name)
  }

  it should "enable implicit conversions from string to Path" in {
    val Name = "testFile.txt"

    import PathUtils._
    val path: Path = Name
    path.toString should be(Name)
  }
}


text:
package org.cloudfoundry.util.tuple;

public interface Predicate2<T1, T2> {

    boolean test(T1 t1, T2 t2);

}


text:
// http://www.w3.org/TR/mediacapture-streams/#navigatorusermedia
#ifndef _WEBRTC_EVERYWHERE_COMMON_NAVIGATORUSERMEDIA_H_
#define _WEBRTC_EVERYWHERE_COMMON_NAVIGATORUSERMEDIA_H_

#include "_Config.h"
#include "_Common.h"

class _Buffer;
class _MediaStreamConstraints;

class WEBRTC_EVERYWHERE_API _NavigatorUserMedia
{
public:
	// void getUserMedia (MediaStreamConstraints? constraints, NavigatorUserMediaSuccessCallback successCallback, NavigatorUserMediaErrorCallback errorCallback);
	static void getUserMedia(const _MediaStreamConstraints* constraints = NULL, _NavigatorUserMediaSuccessCallback successCallback = nullPtr, _NavigatorUserMediaErrorCallback errorCallback = nullPtr);
};

#endif /* _WEBRTC_EVERYWHERE_COMMON_NAVIGATORUSERMEDIA_H_ */


text:
help(
[[
This module loads Graphviz 2.38.0 into the environment. Graphviz is an
application for visualizing graph data.

]])

whatis("Loads the Graphviz visualization software")

local version = "2.38.0"
local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/graphviz/"..version

prepend_path("PATH", pathJoin(base, "bin"))
prepend_path("CPATH",  pathJoin(base, "include"))
prepend_path("LIBRARY_PATH",  pathJoin(base, "lib"))
family('graphviz')