text:
/**
 * @fileoverview Tests for no-undef rule.
 * @author Mark Macdonald
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const rule = require("../../../lib/rules/no-undef"),
    RuleTester = require("../../../lib/testers/rule-tester");

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

const ruleTester = new RuleTester();

ruleTester.run("no-undef", rule, {
    valid: [
        "var a = 1, b = 2; a;",
        "/*global b*/ function f() { b; }",
        { code: "function f() { b; }", globals: { b: false } },
        { code: "function f() { b; }", global: { b: false } },
        "/*global b a:false*/  a;  function f() { b; a; }",
        "function a(){}  a();",
        "function f(b) { b; }",
        "var a; a = 1; a++;",
        "var a; function f() { a = 1; }",
        "/*global b:true*/ b++;",
        "/*eslint-env browser*/ window;",
        "/*eslint-env browser*/ window;",
        "/*eslint-env node*/ require(\"a\");",
        "Object; isNaN();",
        "toString()",
        "hasOwnProperty()",
        "function evilEval(stuffToEval) { var ultimateAnswer; ultimateAnswer = 42; eval(stuffToEval); }",
        "typeof a",
        "typeof (a)",
        "var b = typeof a",
        "typeof a === 'undefined'",
        "if (typeof a === 'undefined') {}",
        { code: "function foo() { var [a, b=4] = [1, 2]; return {a, b}; }", parserOptions: { ecmaVersion: 6 } },
        { code: "var toString = 1;", parserOptions: { ecmaVersion: 6 } },
        { code: "function myFunc(...foo) {  return foo;}", parserOptions: { ecmaVersion: 6 } },
        { code: "var React, App, a=1; React.render(<App attr={a} />);", parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
        { code: "var console; [1,2,3].forEach(obj => {\n  console.log(obj);\n});", parserOptions: { ecmaVersion: 6 } },
        { code: "var Foo; class Bar extends Foo { constructor() { super();  }}", parserOptions: { ecmaVersion: 6 } },
        { code: "import Warning from '../lib/warning'; var warn = new Warning('text');", parserOptions: { sourceType: "module" } },
        { code: "import * as Warning from '../lib/warning'; var warn = new Warning('text');", parserOptions: { sourceType: "module" } },
        { code: "var a; [a] = [0];", parserOptions: { ecmaVersion: 6 } },
        { code: "var a; ({a} = {});", parserOptions: { ecmaVersion: 6 } },
        { code: "var a; ({b: a} = {});", parserOptions: { ecmaVersion: 6 } },
        { code: "var obj; [obj.a, obj.b] = [0, 1];", parserOptions: { ecmaVersion: 6 } },
        { code: "URLSearchParams;", env: { browser: true } },
        { code: "Intl;", env: { browser: true } },
        { code: "IntersectionObserver;", env: { browser: true } },
        { code: "Credential;", env: { browser: true } },
        { code: "requestIdleCallback;", env: { browser: true } },
        { code: "customElements;", env: { browser: true } },
        { code: "PromiseRejectionEvent;", env: { browser: true } },

        // Notifications of readonly are removed: https://github.com/eslint/eslint/issues/4504
        { code: "/*global b:false*/ function f() { b = 1; }" },
        { code: "function f() { b = 1; }", global: { b: false } },
        { code: "/*global b:false*/ function f() { b++; }" },
        { code: "/*global b*/ b = 1;" },
        { code: "/*global b:false*/ var b = 1;" },
        { code: "Array = 1;" },

        // new.target: https://github.com/eslint/eslint/issues/5420
        { code: "class A { constructor() { new.target; } }", parserOptions: { ecmaVersion: 6 } },

        // Experimental,
        {
            code: "var {bacon, ...others} = stuff; foo(others)",
            parserOptions: {
                ecmaVersion: 6,
                ecmaFeatures: {
                    experimentalObjectRestSpread: true
                }
            },
            globals: { stuff: false, foo: false }
        }
    ],
    invalid: [
        { code: "a = 1;", errors: [{ message: "'a' is not defined.", type: "Identifier" }] },
        { code: "if (typeof anUndefinedVar === 'string') {}", options: [{ typeof: true }], errors: [{ message: "'anUndefinedVar' is not defined.", type: "Identifier" }] },
        { code: "var a = b;", errors: [{ message: "'b' is not defined.", type: "Identifier" }] },
        { code: "function f() { b; }", errors: [{ message: "'b' is not defined.", type: "Identifier" }] },
        { code: "window;", errors: [{ message: "'window' is not defined.", type: "Identifier" }] },
        { code: "require(\"a\");", errors: [{ message: "'require' is not defined.", type: "Identifier" }] },
        { code: "var React; React.render(<img attr={a} />);", errors: [{ message: "'a' is not defined." }], parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
        { code: "var React, App; React.render(<App attr={a} />);", errors: [{ message: "'a' is not defined." }], parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
        { code: "[a] = [0];", parserOptions: { ecmaVersion: 6 }, errors: [{ message: "'a' is not defined." }] },
        { code: "({a} = {});", parserOptions: { ecmaVersion: 6 }, errors: [{ message: "'a' is not defined." }] },
        { code: "({b: a} = {});", parserOptions: { ecmaVersion: 6 }, errors: [{ message: "'a' is not defined." }] },
        { code: "[obj.a, obj.b] = [0, 1];", parserOptions: { ecmaVersion: 6 }, errors: [{ message: "'obj' is not defined." }, { message: "'obj' is not defined." }] },

        // Experimental
        {
            code: "const c = 0; const a = {...b, c};",
            parserOptions: {
                ecmaVersion: 6,
                ecmaFeatures: {
                    experimentalObjectRestSpread: true
                }
            },
            errors: [{ message: "'b' is not defined." }]
        }
    ]
});


text:
package com.thoughtworks.go.server.service.dd.reporting;

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

import com.thoughtworks.go.config.materials.PackageMaterialConfig;
import com.thoughtworks.go.config.materials.ScmMaterialConfig;
import com.thoughtworks.go.domain.PipelineTimelineEntry;
import com.thoughtworks.go.domain.materials.MaterialConfig;

public class ReportingRootFanInNode extends ReportingFanInNode {
    private static List<Class<? extends MaterialConfig>> ROOT_NODE_TYPES = new ArrayList<>();
    PipelineTimelineEntry.Revision scmRevision;

    static {
        ROOT_NODE_TYPES.add(ScmMaterialConfig.class);
        ROOT_NODE_TYPES.add(PackageMaterialConfig.class);
    }

    ReportingRootFanInNode(MaterialConfig material) {
        super(material);
        for (Class<? extends MaterialConfig> clazz : ROOT_NODE_TYPES) {
            if (clazz.isAssignableFrom(material.getClass())) {
                return;
            }
        }
        throw new RuntimeException("Not a valid root node material type");
    }
}

redpajama_set_name: RedPajamaGithub


text:
""" This module provide support for tests in our framework.
SBROOT, TESTROOT and BUILTROOT allow
tests to correctly find support files etc.

The built/buildscripts directory is added to the python path.

Standard test tags are defined as decorators for use by the build system.
"""

'''
new test tags should have the attribute all added to them so that they can be run when
the command "sb test -A all" is used
'''

import os
import sys

def skipUnlessLocationAt(*locations):
    '''this decorator skips a test if it is not run from a machine
    with a setup file that has a location configured to a location in locations
    this is useful for connector tests that require a machine on the internal network'''
    import global_vars
    #if isinstance(locations, (str, unicode)):
        #if global_vars.location == locations
            #return lambda func: func
    if global_vars.location in locations:
        return lambda func: func
    return unittest.skip('location not one of the following %s or you have not configured ' \
                         + 'your location with sb test --setup' % locations)

def checkin(test):
    ''' super short tests that must pass before check-in occurs '''
    setattr(test, 'checkin', True)
    setattr(test, 'all', True)
    return test

def officialbuild(test):
    ''' short tests that must pass before a publish occurs '''
    setattr(test, 'officialbuild', True)
    setattr(test, 'all', True)
    return test

def refinement(test, ticketNumber=None):
    ''' longer tests that run regularly (nightly)
    the system test team will work on a way of reporting and dealing with failed refinement tests
    if a test is known to fail a ticket number can be associated with it'''
    setattr(test, 'refinement', True)
    setattr(test, 'ticketNumber', ticketNumber)
    setattr(test, 'all', True)
    return test

def advanced(test):
    '''This test tag is for stress tests and other long tests. these tests must be started manually.
    when these tests are run and what is expected of these tests is determined during a team's
    planning and during interlock '''
    setattr(test, 'advanced', True)
    setattr(test, 'all', True)
    return test

def release(test):
    ''' tests that verify that the release was sucessfull
    for example testing that the mirrors were correctly updated'''
    setattr(test, 'release', True)
    setattr(test, 'all', True)
    return testing

def performance(test):
    '''This test tag is for performance tests
    shorter performance tests that record their results in a file or database
    should be tagged as reusable in addition to being tagged as performance'''
    setattr(test, 'performance', True)
    setattr(test, 'all', True)
    return test

def interactive(test):
    '''This test tag is for tests that need user interaction to run'''
    setattr(test, 'interactive', True)
    setattr(test, 'all', True)
    return test

def modesensitive(test):
    '''This test tag is for tests that are sensitive to mode'''
    setattr(test, 'modesensitive', True)
    setattr(test, 'all', True)
    return test

def shareable(test):
    raise DeprecationWarning('use checkin tag instead of shareable tag')

def reusable(test):
    raise DeprecationWarning('use officialbuild tag instead of reusable tag')

def releaseable(test):
    raise DeprecationWarning('use refinement tag instead of releaseable tag')

_my_dir = os.path.dirname(os.path.abspath(__file__)).replace('\\', '/')
SBROOT = os.path.abspath(os.path.join(_my_dir, '../..')).replace('\\', '/')
TESTROOT = SBROOT + '/test'
RUNROOT = SBROOT + '/run'
CODEROOT = SBROOT + '/code'


text:
class JqtouchHelloworldGenerator < Rails::Generators::Base

  source_root File.expand_path("../lib/jqtouch", __FILE__)

  def create_initializer_file
    insert_into_file "config/routes.rb", "  get 'helloworld', to: 'jqtouch_pages#helloworld'\n", after: "::Application.routes.draw do\n"
    create_file "app/controllers/jqtouch_pages_controller.rb", "
class JqtouchPagesController < ApplicationController
  def helloworld
  end
end
"
    copy_file "helloworld.html", "app/views/jqtouch_pages/helloworld.html.erb"
  end
end


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import chr

import sys
import os
import re
import socket
import tempfile
import shutil
import getpass
import mock

from test import prompty
from test import MockProc
from test import UnitTestWrapper

class StandardFunctionTests(UnitTestWrapper):

    def test_user(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual(getpass.getuser(), c._call("user"))

    def test_hostname(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual(socket.gethostname().split(".")[0], c._call("hostname"))

    def test_hostnamefull(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual(socket.gethostname(), c._call("hostnamefull"))

    def test_workingdir(self):
        origcwd = os.getcwd()
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        os.chdir(os.path.expanduser("~"))
        os.environ["PWD"] = os.getcwd()
        self.assertEqual(r"~", c._call("workingdir"))
        tmpDir = tempfile.mkdtemp()
        os.chdir(tmpDir)
        os.environ["PWD"] = os.getcwd()
        self.assertEqual(tmpDir, c._call("workingdir"))
        # Cleanup
        os.chdir(origcwd)
        os.environ["PWD"] = os.getcwd()
        shutil.rmtree(tmpDir)

    def test_workingdirbase(self):
        origcwd = os.getcwd()
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        tmpDir = tempfile.mkdtemp()
        os.chdir(tmpDir)
        os.environ["PWD"] = os.getcwd()
        self.assertEqual(os.path.basename(tmpDir), c._call("workingdirbase"))
        os.chdir("/usr/local")
        os.environ["PWD"] = os.getcwd()
        self.assertEqual(r"local", c._call("workingdirbase"))
        # Cleanup
        os.chdir(origcwd)
        os.environ["PWD"] = os.getcwd()
        shutil.rmtree(tmpDir)

    def test_dollar(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual(r"$", c._call("dollar"))
        self.assertEqual(r"#", c._call("dollar", 0))

    def test_specialChars(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        chars = [
                 ("newline",            "\n"),
                 ("carriagereturn",     "\r"),
                 ("space",              " "),
                 ("backslash",          "\\"),
                 ("percent",            "%"),
                 ("opencurly",          "{"),
                 ("closecurly",         "}"),
                 ("opensquare",         "["),
                 ("closesquare",        "]"),
                 ("escape",             "\033")
                ]
        for char in chars:
            self.assertEqual(char[1], c._call(char[0]))

    def test_uniChar(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual('a', c._call("unichar", "97"))
        self.assertEqual('b', c._call("unichar", "0x62"))
        self.assertEqual('c', c._call("unichar", "0o143"))

    def test_lower(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual('lower', c._call("lower", "lower"))
        self.assertEqual('mixed', c._call("lower", "MiXEd"))
        self.assertEqual('all_upper with spaces', c._call("lower", "ALL_UPPER WITH SPACES"))

    def test_join(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual('one:fish', c._call("join", ":", "one", "fish"))
        self.assertEqual('one/fish/cheese', c._call("join", "/", "one", "fish", "cheese"))
        self.assertEqual('', c._call("join", "/"))
        self.assertRaises(TypeError, c._call, "join")

    @mock.patch('prompty.status.subprocess')
    def test_justify(self, mock_sp):
        # Set up mock
        output = (
            "54 13",
            "",
            0,
            None
        )
        mock_sp.Popen.return_value = MockProc(output)

        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual('|     |     |', c._call("justify", "|", "|", "|"))
        self.assertEqual('|-----|=====|', c._call("justify", "|", "|", "|", "-", "="))
        self.assertEqual('            |', c._call("right", "|"))
        self.assertEqual('lt@@@cen   rt', c._call("justify", "lt", "cen", "rt", "@"))

    def test_smiley(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        c.addFunctionsFromModule(prompty.colours)
        c.status.exitCode = 0
        self.assertIn(":)", c._call("smiley"))
        c.status.exitCode = 1
        self.assertIn(":(", c._call("smiley"))

    def test_powerline(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        c.addFunctionsFromModule(prompty.colours)
        self.assertIn("test", c._call("powerline", "test"))
        self.assertIn(chr(0xe0b0), c._call("powerline", "test"))

    def test_date(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertTrue(bool(re.match(r"^[a-zA-z]+ [a-zA-z]+ [0-9]+$", c._call("date"))))

    def test_datefmt(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertTrue(bool(re.match(r"^[0-9:]+$", c._call("datefmt"))))
        self.assertTrue(bool(re.match(r"^hello$", c._call("datefmt", "hello"))))
        self.assertTrue(bool(re.match(r"^[0-9]{2}$", c._call("datefmt", "#d"))))

    def test_isRealPath(self):
        origcwd = os.getcwd()
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertTrue(c._call("isrealpath"))
        tmpDir = tempfile.mkdtemp()
        link = os.path.join(tmpDir, "link")
        os.symlink(tmpDir, link)
        os.chdir(link)
        os.environ["PWD"] = link
        self.assertFalse(c._call("isrealpath"))
        # Cleanup
        os.chdir(origcwd)
        os.environ["PWD"] = os.getcwd()
        shutil.rmtree(tmpDir)

class ExpressionFunctionTests(UnitTestWrapper):
    def test_equal(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual(True, c._call("equals", "1", "1"))

    def test_max(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual("2", c._call("max", "2", "1"))
        self.assertEqual("1", c._call("max", "1", "1"))
        self.assertEqual("2", c._call("max", "1", "2"))

    def test_if(self):
        c = prompty.functionContainer.FunctionContainer()
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual("1", c._call("ifexpr", "True", "1", "2"))
        self.assertEqual("2", c._call("ifexpr", "False", "1", "2"))
        self.assertEqual("1", c._call("ifexpr", "True", "1"))
        self.assertEqual("", c._call("ifexpr", "0", "1"))
        self.assertEqual("1", c._call("ifexpr", "1", "1"))

    def test_exitSuccess(self):
        c = prompty.functionContainer.FunctionContainer(prompty.status.Status(0))
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual(True, c._call("exitsuccess"))
        c = prompty.functionContainer.FunctionContainer(prompty.status.Status(1))
        c.addFunctionsFromModule(prompty.functions)
        self.assertEqual(False, c._call("exitsuccess"))


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('adventure', '0048_auto_20180304_1832'),
    ]

    operations = [
        migrations.AddField(
            model_name='adventure',
            name='featured_month',
            field=models.CharField(blank=True, max_length=7, null=True),
        ),
        migrations.AddField(
            model_name='adventure',
            name='date_published',
            field=models.DateField(blank=True, null=True),
        ),
    ]


text:
import os
import json
from ebstall.core import Core
import ebstall.util as util
from ebstall.consts import *
from ebstall.errors import *
from ebstall.config import Config
from datetime import datetime
import shutil
import errno

__author__ = 'dusanklinec'

class SoftHsmV1Config(object):
    """
    Class for configuring SoftHSMv1 instance for EB
    """
    CONFIG_FILE = '/etc/softhsm.conf'
    CONFIG_FILE_BACKUP_DIR = '/etc/softhsm.old'
    SOFTHSM_DB_DIR = '/var/lib/softhsm'
    SOFTHSM_DB_BACKUP_DIR = '/var/lib/softhsm.old'
    SOFTHSM_SO_PATH = '/usr/lib64/softhsm/libsofthsm.so'

    DEFAULT_SLOT_CONFIG = {
            'slot': 0,
            'db': '/var/lib/softhsm/slot0.db',
            'host': 'site2.enigmabridge.com',
            'port': 11110,
            'enrollPort': 11112,
            'apikey': 'TEST_API',
            'genRSA': True,

            'retry': {
                'maxRetry': 6,
                'jitterBase': 250,
                'jitterRand': 100
            },

            'createTpl': {
                'environment': 'dev',
                'maxtps': 'one',
                'core': 'empty',
                'credit': 32000
            }
        }

    def __init__(self, config_file=CONFIG_FILE, config=None, config_template=None, *args, **kwargs):
        self.config_file = config_file
        self.json = None
        self.config = config
        self.config_template = config_template

    def config_file_exists(self):
        """
        Returns true if the SoftHSMv1 config file exists
        :return:
        """
        return os.path.isfile(self.CONFIG_FILE)

    def load_config_file(self, config_file=None):
        """
        Tries to load & parse SoftHSMv1 config file
        If file does not exist or parsing failed exception is raised

        :param config_file:
        :return:
        """
        if config_file is not None:
            self.config_file = config_file
        if self.config_file is None:
            raise ValueError('Config file is None')

        with open(self.config_file, 'r') as f:
            read_lines = [x.strip() for x in f.read().split('\n')]
            lines = []
            for line in read_lines:
                if line.startswith('//'):
                    continue
                lines.append(line)

            self.json = json.loads(lines)

    def backup_current_config_file(self):
        """
        Copies current configuration file to a new file - backup.
        softhsm.conf -> 0001_softhsm.conf

        Used when generating a new SoftHSM configuration file, to
        preserve the old one if user accidentally reinitializes the system.
        :return:
        """
        cur_name = self.CONFIG_FILE

        if os.path.exists(cur_name):
            util.make_or_verify_dir(self.CONFIG_FILE_BACKUP_DIR)
            return util.file_backup(cur_name, chmod=None, backup_dir=self.CONFIG_FILE_BACKUP_DIR)

        return None

    def configure(self, config=None):
        """
        Generates SoftHSMv1 configuration from the AMI config.
        :return:
        """
        if config is not None:
            self.config = config
        if self.config is None:
            raise ValueError('Configuration is not defined')

        slot_cfg = self.config_template if self.config_template is not None else self.DEFAULT_SLOT_CONFIG

        endpoint_process = config.resolve_endpoint(purpose=SERVER_PROCESS_DATA, protocol=PROTOCOL_RAW)[0]
        endpoint_enroll = config.resolve_endpoint(purpose=SERVER_ENROLLMENT, protocol=PROTOCOL_RAW)[0]
        if endpoint_process.host != endpoint_enroll.host:
            raise ValueError('Process host is different from the enrollment host. SoftHSM needs to be updated')

        slot_cfg['apikey'] = config.apikey
        slot_cfg['host'] = endpoint_process.host
        slot_cfg['port'] = endpoint_process.port
        slot_cfg['enrollPort'] = endpoint_enroll.port

        # Server environment?
        if 'environment' in endpoint_process.server:
            slot_cfg['createTpl']['environment'] = endpoint_process.server['environment']

        root = {'slots': [slot_cfg]}
        self.json = root
        pass

    def write_config(self):
        """
        Writes current configuration to the file.
        :return:
        """
        conf_name = self.CONFIG_FILE
        with os.fdopen(os.open(conf_name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644), 'w') as config_file:
            config_file.write('// \n')
            config_file.write('// SoftHSM configuration file for Enigma Bridge \n')
            config_file.write('// Config file generated: %s\n' % datetime.now().strftime("%Y-%m-%d %H:%M"))
            config_file.write('// \n')
            config_file.write(json.dumps(self.json, indent=2) + "\n\n")
        return conf_name

    def backup_previous_token_dir(self):
        """
        Backs up the previous token database
        :return:
        """
        if os.path.exists(self.SOFTHSM_DB_DIR):
            util.make_or_verify_dir(self.SOFTHSM_DB_BACKUP_DIR)
            backup_slot_dir = util.dir_backup(self.SOFTHSM_DB_DIR, chmod=None, backup_dir=self.SOFTHSM_DB_BACKUP_DIR)
            return backup_slot_dir

        return None

    def init_token(self, user=None):
        """
        Initializes a new SoftHSM token created by the configuration
        :param user: user to initialize token under
        :return:
        """
        util.make_or_verify_dir(self.SOFTHSM_DB_DIR, mode=0o755)
        cmd = 'softhsm --init-token --slot 0 --pin 0000 --so-pin 0000 --label ejbca'

        if user is None:
            out, err = util.run_script(cmd.split(' '))
            return out, err

        else:
            util.chown(self.SOFTHSM_DB_DIR, user, user)
            cmd_sudo = ['sudo', '-E', '-H', '-u', user, '/bin/bash', '-c', cmd]
            return util.run_script(cmd_sudo)

    def chown_tokens(self, user):
        """
        Changes the owner of the tokens
        :param user:
        :return:
        """
        if not os.path.exists(self.SOFTHSM_DB_DIR):
            return

        util.chown(self.SOFTHSM_DB_DIR, user, user)
        tokens = os.listdir(self.SOFTHSM_DB_DIR)
        for token in tokens:
            util.chown(token, user, user)

    def get_so_path(self):
        return self.SOFTHSM_SO_PATH


text:
package ch.hoene.perzist.source.relational.fieldtype;

import ch.hoene.perzist.access.creator.Creator;
import ch.hoene.perzist.source.relational.FieldPersistable;

public class FieldPersistableAsString<RESULT> extends FieldPersistable<RESULT, String>
{
    public FieldPersistableAsString(String name, Creator<String, RESULT> mapping)
    {
        super(name, mapping);
    }

    public FieldPersistableAsString(FieldPersistable<RESULT, String> fieldPersistable)
    {
        super(fieldPersistable);
    }

    @Override
    public <R> R accept(FieldVisitor<R, ? extends RESULT> visitor)
    {
        return visitor.visit(this);
    }
}


text:
package org.osgi.util.function;

/**
 * A predicate that accepts a single argument and produces a boolean result.
 * <p>
 * This is a functional interface and can be used as the assignment target for a lambda expression or method reference.
 *
 * @param <T> The type of the predicate input.
 */
@org.osgi.annotation.versioning.ConsumerType
public interface Predicate<T> {
    /**
     * Evaluates this predicate on the specified argument.
     *
     * @param t The input to this predicate.
     * @return true if the specified argument is accepted by this predicate; false otherwise.
     */
    boolean test(T t);
}


text:
class ChangeEnforcesOnUserLocationsTable < ActiveRecord::Migration
  def self.up
    execute "ALTER TABLE user_locations DROP CONSTRAINT enforce_dims_geom"
    execute "ALTER TABLE user_locations DROP CONSTRAINT enforce_srid_geom"
  end

  def self.down
    execute "ALTER TABLE user_locations ADD CONSTRAINT enforce_dims_geom CHECK (st_ndims(geom) = 3)"
    execute "ALTER TABLE user_locations ADD CONSTRAINT enforce_srid_geom CHECK (st_srid(geom) = 4326)"
  end
end


text:
package org.wisdom.test.parents;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.wisdom.api.http.MimeTypes;
import org.wisdom.api.http.Results;
import org.wisdom.api.http.Status;

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

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

/**
 * Check the basic behavior of the Wisdom Test class.
 */
public class WisdomTestTest {

    WisdomTest test = new WisdomTest();

    @Test
    public void testStatus() throws Exception {
        Action.ActionResult result = new Action.ActionResult(Results.ok(), null);
        assertThat(test.status(result)).isEqualTo(Status.OK);

        result = new Action.ActionResult(Results.notFound(), null);
        assertThat(test.status(result)).isEqualTo(Status.NOT_FOUND);

        result = new Action.ActionResult(Results.forbidden(), null);
        assertThat(test.status(result)).isEqualTo(Status.FORBIDDEN);
    }

    @Test
    public void testContentType() throws Exception {
        Action.ActionResult result = new Action.ActionResult(Results.ok(), null);
        // Not set.
        assertThat(test.contentType(result)).isNull();

        result = new Action.ActionResult(Results.ok().html(), null);
        assertThat(test.contentType(result)).isEqualTo(MimeTypes.HTML);

        result = new Action.ActionResult(Results.ok().json(), null);
        assertThat(test.contentType(result)).isEqualTo(MimeTypes.JSON);

        result = new Action.ActionResult(Results.ok().as("acme/acme"), null);
        assertThat(test.contentType(result)).isEqualTo("acme/acme");
    }

    @Test
    public void testJson() throws Exception {
        // Regular Json node
        final String json = "{\"a\":\"1\",\"property\":\"default value\"," +
                "\"bundle\":\"org.acme.demo.solution\"}";
        ObjectNode node = WisdomTest.MAPPER.readValue(json, ObjectNode.class);
        Action.ActionResult result = new Action.ActionResult(Results.ok(node), null);
        assertThat(test.json(result).toString()).isEqualTo(json);

        Map.Entry<String, Integer> entry = new HashMap.SimpleEntry<>("key", 1);
        result = new Action.ActionResult(Results.ok(entry).json(), null);
        assertThat(test.json(result).get("key").asInt()).isEqualTo(1);

        try {
            result = new Action.ActionResult(Results.ok("
Hello
"), null);
            test.json(result);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
            assertThat(e.getCause()).isInstanceOf(ClassCastException.class);
        }
    }

    @Test
    public void testJsonarray() throws Exception {
        // Regular Json node
        String json = "[\"1\",\"2\"]";
        ArrayNode node = WisdomTest.MAPPER.readValue(json, ArrayNode.class);
        Action.ActionResult result = new Action.ActionResult(Results.ok(node), null);
        assertThat(test.jsonarray(result).size()).isEqualTo(2);
        assertThat(test.jsonarray(result).get(0).asInt()).isEqualTo(1);

        List<String> list = ImmutableList.of("a", "b");
        result = new Action.ActionResult(Results.ok(list).json(), null);
        assertThat(test.jsonarray(result).size()).isEqualTo(2);
        assertThat(test.jsonarray(result).get(0).asText()).isEqualTo("a");

        try {
            result = new Action.ActionResult(Results.ok("
Hello
"), null);
            test.jsonarray(result);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
            assertThat(e.getCause()).isInstanceOf(ClassCastException.class);
        }

        try {
            json = "{\"a\":\"1\",\"property\":\"default value\"," +
                    "\"bundle\":\"org.acme.demo.solution\"}";
            result = new Action.ActionResult(Results.ok(json), null);
            test.jsonarray(result);
            fail("IllegalArgumentException expected");
        } catch (IllegalArgumentException e) {
            assertThat(e.getCause()).isInstanceOf(ClassCastException.class);
        }
    }

    @Test
    public void testToString() throws Exception {
        Action.ActionResult result = new Action.ActionResult(Results.ok("
Hello
"), null);
        assertThat(test.toString(result)).isEqualTo("
Hello
");

        String json = "{\"a\":\"1\",\"property\":\"default value\"," +
                "\"bundle\":\"org.acme.demo.solution\"}";
        ObjectNode node = WisdomTest.MAPPER.readValue(json, ObjectNode.class);
        result = new Action.ActionResult(Results.ok(node), null);
        assertThat(test.toString(result)).isEqualTo(json);
    }

    @Test
    public void testToBytes() throws Exception {
        Action.ActionResult result = new Action.ActionResult(Results.ok("
Hello
"), null);
        assertThat(test.toBytes(result)).isNotEmpty();

        String json = "{\"a\":\"1\",\"property\":\"default value\"," +
                "\"bundle\":\"org.acme.demo.solution\"}";
        ObjectNode node = WisdomTest.MAPPER.readValue(json, ObjectNode.class);
        result = new Action.ActionResult(Results.ok(node), null);
        assertThat(test.toBytes(result)).isNotEmpty();
    }
}


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

-->
<config>
    <modules>
        <Yireo_NewRelic>
            <version>1.3.0</version>
        </Yireo_NewRelic>
    </modules>

    <global>
        <blocks>
            <newrelic>
                <class>Yireo_NewRelic_Block</class>
            </newrelic>
        </blocks>
        <helpers>
            <newrelic>
                <class>Yireo_NewRelic_Helper</class>
            </newrelic>
        </helpers>
        <models>
            <newrelic>
                <class>Yireo_NewRelic_Model</class>
            </newrelic>
        </models>

        <events>
            <adminhtml_cache_flush_all>
                <observers>
                    <newrelic_log_adminhtml_cache_flush_all>
                        <type>singleton</type>
                        <class>newrelic/observer_adminhtml_cache_flushAll</class>
                        <method>execute</method>
                    </newrelic_log_adminhtml_cache_flush_all>
                </observers>
            </adminhtml_cache_flush_all>

            <adminhtml_cache_flush_system>
                <observers>
                    <newrelic_log_adminhtml_cache_flush_system>
                        <type>singleton</type>
                        <class>newrelic/observer_adminhtml_cache_flushSystem</class>
                        <method>execute</method>
                    </newrelic_log_adminhtml_cache_flush_system>
                </observers>
            </adminhtml_cache_flush_system>

            <adminhtml_cache_refresh_type>
                <observers>
                    <newrelic_log_adminhtml_cache_refresh_type>
                        <type>singleton</type>
                        <class>newrelic/observer_adminhtml_cache_refreshType</class>
                        <method>execute</method>
                    </newrelic_log_adminhtml_cache_refresh_type>
                </observers>
            </adminhtml_cache_refresh_type>

            <controller_action_postdispatch_adminhtml_process_massReindex>
                <observers>
                    <newrelic_log_controller_action_postdispatch_adminhtml_process_massReindex>
                        <class>newrelic/observer_adminhtml_process_massReindex</class>
                        <method>execute</method>
                    </newrelic_log_controller_action_postdispatch_adminhtml_process_massReindex>
                </observers>
            </controller_action_postdispatch_adminhtml_process_massReindex>

            <controller_action_postdispatch_adminhtml_process_reindexProcess>
                <observers>
                    <newrelic_log_controller_action_postdispatch_adminhtml_process_reindexProcess>
                        <class>newrelic/observer_adminhtml_process_reindexProcess</class>
                        <method>execute</method>
                    </newrelic_log_controller_action_postdispatch_adminhtml_process_reindexProcess>
                </observers>
            </controller_action_postdispatch_adminhtml_process_reindexProcess>

            <controller_action_predispatch>
                <observers>
                    <newrelic_initialise>
                        <type>singleton</type>
                        <class>newrelic/observer_initialise</class>
                        <method>execute</method>
                    </newrelic_initialise>
                </observers>
            </controller_action_predispatch>

            <controller_action_postdispatch>
                <observers>
                    <newrelic_addRequestData>
                        <type>singleton</type>
                        <class>newrelic/observer_addRequestData</class>
                        <method>execute</method>
                    </newrelic_addRequestData>
                </observers>
            </controller_action_postdispatch>

            <model_save_after>
                <observers>
                    <newrelic_log_model_save_after>
                        <type>singleton</type>
                        <class>Yireo_NewRelic_Model_Observer_Model_SaveAfter</class>
                        <method>execute</method>
                    </newrelic_log_model_save_after>
                </observers>
            </model_save_after>

            <model_delete_after>
                <observers>
                    <newrelic_log_model_delete_after>
                        <type>singleton</type>
                        <class>Yireo_NewRelic_Model_Observer_Model_DeleteAfter</class>
                        <method>execute</method>
                    </newrelic_log_model_delete_after>
                </observers>
            </model_delete_after>
        </events>
    </global>

    <frontend>
        <layout>
            <updates>
                <newrelic module="newrelic">
                    <file>newrelic.xml</file>
                </newrelic>
            </updates>
        </layout>
    </frontend>

    <adminhtml>
        <acl>
            <resources>
                <admin>
                    <children>
                        <system>
                            <children>
                                <config>
                                    <children>
                                        <newrelic translate="title" module="newrelic">
                                            <title>NewRelic</title>
                                        </newrelic>
                                    </children>
                                </config>
                            </children>
                        </system>
                    </children>
                </admin>
            </resources>
        </acl>
    </adminhtml>

    <crontab>
        <events>
            <always>
                <observers>
                    <newrelic_cron_observer>
                        <class>newrelic/observer_crontab</class>
                        <method>execute</method>
                    </newrelic_cron_observer>
                </observers>
            </always>
        </events>
    </crontab>

    <default>
        <newrelic>
            <settings>
                <enabled>1</enabled>
                <track_controller>1</track_controller>
                <real_user_monitoring>0</real_user_monitoring>
                <xmit>1</xmit>
            </settings>
        </newrelic>
    </default>
</config>


text:
package spinoco.protocol.kafka.codec

import scodec.bits.BitVector
import scodec.{Attempt, Codec}
import scodec.codecs._
import shapeless.{::, HNil}
import spinoco.protocol.kafka._
import spinoco.protocol.common.util._
import spinoco.protocol.kafka.Request.{FetchRequest, MetadataRequest, OffsetsRequest, ProduceRequest}

object MessageCodec {

  /** enodes supplied request **/
  val requestCodec: Codec[RequestMessage] =
    variableSizeBytes(int32, impl.requestContentCodec)

  /**
    * Decodes response correlation id plus the bytes of the response
    * Once correlationId is known, then original request may be identified
    * and then `responseCodecFor` may be used to actually decode the message-
    */
  val responseCorrelationCodec:Codec[(Int,BitVector)] =
    variableSizeBytes(int32, ("Correlation Id" | int32) ~ bits )

  /** decodes concrete response **/
  def responseCodecFor(version: ProtocolVersion.Value, apiKey:ApiKey.Value):Codec[Response] = {
    apiKey match {
      case ApiKey.FetchRequest => FetchCodec.responseCodec(version).upcast
      case ApiKey.MetadataRequest => MetadataCodec.metadataResponseCodec.upcast
      case ApiKey.ProduceRequest => ProduceCodec.produceResponseCodec(version).upcast
      case ApiKey.OffsetRequest => OffsetCodec.responseCodec(version).upcast
    }
  }

  object impl {

    val apiKeyCodec:Codec[ApiKey.Value] =
      int16.exmap(
        code => attempt(ApiKey(code))
        , k => Attempt.successful(k.id)
      )

    type RequestHeader = ApiKey.Value :: Int :: Int :: String :: HNil
    val requestHeaderCodec : Codec[RequestHeader] = {
      "Request Header" | (
        ("Api Key"        | apiKeyCodec) ::
        ("Api Version"    | int16) ::
        ("Correlation Id" | int32) ::
        ("Client Id"      | kafkaRequiredString)
      )
    }

    val requestContentCodec: Codec[RequestMessage] = {
      def encode(rm:RequestMessage):(RequestHeader, Request) = {
        val key = ApiKey.forRequest(rm.request)
        val version: Int = rm.request match {
          case _: ProduceRequest => rm.version match {
            case ProtocolVersion.Kafka_0_8 => 0
            case ProtocolVersion.Kafka_0_9 => 1
            case ProtocolVersion.Kafka_0_10 |
                 ProtocolVersion.Kafka_0_10_1 |
                 ProtocolVersion.Kafka_0_10_2 => 2
          }

          case _: FetchRequest => rm.version match {
            case ProtocolVersion.Kafka_0_8 => 0
            case ProtocolVersion.Kafka_0_9 => 1
            case ProtocolVersion.Kafka_0_10 |
                 ProtocolVersion.Kafka_0_10_1 => 2
            case ProtocolVersion.Kafka_0_10_2 => 3
          }

          case _: MetadataRequest => 0

          case _: OffsetsRequest => 0
        }
        (key :: version :: rm.correlationId :: rm.clientId :: HNil, rm.request)
      }
      def decode(header:RequestHeader, request:Request): RequestMessage = {
        val version :: correlation :: clientId :: HNil = header.tail
        val protocolVersion = request match {
          case _: ProduceRequest => version match {
            case 0 => ProtocolVersion.Kafka_0_8
            case 1 => ProtocolVersion.Kafka_0_9
            case _ => ProtocolVersion.Kafka_0_10
          }
          case _: FetchRequest =>  version match {
            case 0 => ProtocolVersion.Kafka_0_8
            case 1 => ProtocolVersion.Kafka_0_9
            case 2 => ProtocolVersion.Kafka_0_10
            case 3 | _ => ProtocolVersion.Kafka_0_10_2
          }
          case _: MetadataRequest => ProtocolVersion.Kafka_0_8
          case _: OffsetsRequest => ProtocolVersion.Kafka_0_8
        }
        RequestMessage(protocolVersion, correlation, clientId, request)
      }

      requestHeaderCodec.flatZip[Request] {
        case api :: version :: _ =>
          api match {
            case ApiKey.ProduceRequest => ProduceCodec.requestCodec.upcast
            case ApiKey.FetchRequest => FetchCodec.requestCodec(version).upcast
            case ApiKey.MetadataRequest => MetadataCodec.requestCodec.upcast
            case ApiKey.OffsetRequest => OffsetCodec.requestCodec(version).upcast
          }
      }.xmap(decode _ tupled,encode)
    }

  }

}


text:
export HomeController from './Home/controller'
export MediaController from './Media/controller'
export StarredController from './Starred/controller'
export DiscoverController from './Discover/controller'


text:
typealias CRS Union(Nothing, Dict{String,Any})
# TODO: Handle full CRS spec

# Position
# (x, y, [z, ...]) - meaning of additional elements undefined.
# In an object's contained geometries, Positions must have uniform dimensions.
# A bbox must match that dimensionality.
# Both requirements are currently unchecked.
typealias Position Vector{Float64}

# Abstract Interfaces

abstract AbstractGeoJSON

hasbbox(obj::AbstractGeoJSON) = isdefined(obj, :bbox)
hascrs(obj::AbstractGeoJSON) = isdefined(obj, :crs)
bbox(obj::AbstractGeoJSON) = obj.bbox
crs(obj::AbstractGeoJSON) = obj.crs

abstract Geometry <: AbstractGeoJSON

# Geometry Objects

type Point <: Geometry
    coordinates::Position
    # optional
    bbox::Vector{Float64}
    crs::CRS

    Point(coordinates = Float64[]; kwargs...) = fill_options!(new(coordinates); kwargs...)
end

type MultiPoint <: Geometry
    coordinates::Vector{Position}
    # optional
    bbox::Vector{Float64}
    crs::CRS

    MultiPoint(coordinates = Position[]; kwargs...) = fill_options!(new(coordinates); kwargs...)
end

type LineString <: Geometry
    coordinates::Vector{Position} # two or more positions
    # optional
    bbox::Vector{Float64}
    crs::CRS

    LineString(coordinates = Position[]; kwargs...) = fill_options!(new(coordinates); kwargs...)
end

type MultiLineString <: Geometry
    coordinates::Vector{Vector{Position}} # vector{vector of two or more positions}
    # optional
    bbox::Vector{Float64}
    crs::CRS

    MultiLineString(coordinates = Vector{Position}[]; kwargs...) = fill_options!(new(coordinates); kwargs...)
end

type Polygon <: Geometry
    coordinates::Vector{Vector{Position}} # vector{'LinearRing' vectors, exterior ring first}
    # optional
    bbox::Vector{Float64}
    crs::CRS

    Polygon(coordinates = Vector{Position}[]; kwargs...) = fill_options!(new(coordinates); kwargs...)
end

type MultiPolygon <: Geometry
    coordinates::Vector{Vector{Vector{Position}}} # vector{vector{'LinearRing' vectors, exterior ring first}}
    # optional
    bbox::Vector{Float64}
    crs::CRS

    MultiPolygon(coordinates = Vector{Vector{Position}}[]; kwargs...) = fill_options!(new(coordinates); kwargs...)
end

type GeometryCollection <: Geometry
    geometries::Vector{Geometry}
    # optional
    bbox::Vector{Float64}
    crs::CRS

    GeometryCollection(geometries = Geometry[]; kwargs...) =
        fill_options!(new(geometries); kwargs...)
end

# Feature Objects

type Feature <: AbstractGeoJSON
    geometry::Union(Nothing, Geometry)
    properties::Union(Nothing, Dict{String,Any})
    # optional
    id
    bbox::Vector{Float64}
    crs::CRS

    Feature(geometry::Union(Nothing, Geometry)=nothing, properties::Union(Nothing, Dict{String,Any})=nothing; kwargs...) =
        fill_options!(new(geometry, properties); kwargs...)
end
hasid(obj::Feature) = isdefined(obj, :id)

type FeatureCollection <: AbstractGeoJSON
    features::Vector{Feature}
    # optional
    bbox::Vector{Float64}
    crs::CRS

    FeatureCollection(features::Vector{Feature} = Feature[]; kwargs...) =
        fill_options!(new(features); kwargs...)
end

# Helper Functions

function fill_options!(obj::AbstractGeoJSON, param::String, value)
    if param == "id"
        obj.id = value
    elseif param == "bbox"
        obj.bbox = value
    elseif param == "crs"
        obj.crs = value
    end
    obj
end

function fill_options!(obj::AbstractGeoJSON, param::Symbol, value)
    if param == :id
        obj.id = value
    elseif param == :bbox
        obj.bbox = value
    elseif param == :crs
        obj.crs = value
    end
    obj
end

function fill_options!(obj::AbstractGeoJSON; kwargs...)
    for (param, value) in kwargs
        fill_options!(obj, param, value)
    end
    obj
end

function fill_options!(obj::AbstractGeoJSON, kwargs::Dict{String,Any})
    for (param, value) in kwargs
        fill_options!(obj, param, value)
    end
    obj
end

# Additional Constructors (Dict -> GeoJSON)

function GeometryCollection(obj::Dict{String,Any})
    collection = GeometryCollection()
    geometries = obj["geometries"]
    sizehint!(collection.geometries, length(geometries))
    for geometry in geometries
        push!(collection.geometries, dict2geojson(geometry))
    end
    fill_options!(collection, obj)
end

for geom in (:MultiPolygon, :Polygon, :MultiLineString, :LineString, :MultiPoint, :Point)
    @eval $(geom)(obj::Dict{String,Any}) = fill_options!($(geom)(obj["coordinates"]), obj)
end

function Feature(obj::Dict{String,Any})
    feature = Feature(dict2geojson(obj["geometry"]), obj["properties"])
    if haskey(obj, "id")
        feature.id = obj["id"]
    end
    fill_options!(feature, obj)
end

function FeatureCollection(obj::Dict{String,Any})
    features = obj["features"]
    collection = FeatureCollection(Feature[])
    sizehint!(collection.features, length(features))
    for feature in features
        push!(collection.features, Feature(feature))
    end
    fill_options!(collection, obj)
end

# Implement GEO interface

for (geom,attributes) in ((MultiPolygon, (:coordinates,)),
                          (Polygon, (:coordinates,)),
                          (MultiLineString, (:coordinates,)),
                          (LineString, (:coordinates,)),
                          (MultiPoint, (:coordinates,)),
                          (Point, (:coordinates,)),
                          (GeometryCollection, (:geometries,)),
                          (Feature, (:geometry, :properties, :id)),
                          (FeatureCollection, (:features,)))
    for attr in attributes
        @eval $(attr)(obj::$geom) = obj.$(attr)
    end
end


text:
- Report issues or feature requests on [GitHub Issues](https://github.com/pboling/js-cookie-calibre/issues).
- If reporting a bug, please add a [simplified example](http://sscce.org/).

## Pull requests
- Create a new topic branch for every separate change you make.
- Create a test case if you are fixing a bug or implementing an important feature.
- Make sure the build runs successfully.

## Development

### Tools
We use the following tools for development:

- [Qunit](http://qunitjs.com/) for tests.
- [NodeJS](http://nodejs.org/download/) required to run grunt.
- [Grunt](http://gruntjs.com/getting-started) for task management.

### Getting started
Install [NodeJS](http://nodejs.org/).
Install globally grunt-cli using the following command:

    $ npm install -g grunt-cli

Browse to the project root directory and install the dev dependencies:

    $ npm install -d

To execute the build and tests run the following command in the root of the project:

    $ grunt

You should see a green message in the console:

    Done, without errors.

### Tests
You can also run the tests in the browser.
Start a test server from the project root:

    $ grunt connect:tests

This will automatically open the test suite at http://127.0.0.1:10000 in the default browser, with livereload enabled.

_Note: we recommend cleaning all the browser cookies before running the tests, that can avoid false positive failures._

### Automatic build
You can build automatically after a file change using the following command:

    $ grunt watch

## Integration with server-side

js-cookie-calibre allows integrating the encoding test suite with solutions written in other server-side languages. To integrate successfully, the server-side solution need to execute the `test/encoding.html` file in it's integration testing routine with a web automation tool, like [Selenium](http://www.seleniumhq.org/). js-cookie-calibre test suite exposes an API to make this happen.

### ?integration_baseurl

Specify the base url to pass the cookies into the server through a query string. If `integration_baseurl` query is not present, then js-cookie-calibre will assume there's no server.

### window.global_test_results

After the test suite has finished, js-cookie-calibre exposes the global `window.global_test_results` property containing an Object Literal that represents the [QUnit's details](http://api.qunitjs.com/QUnit.done/). js-cookie-calibre also adds an additional property representing an Array containing the tests data.

### Handling requests

When js-cookie-calibre encoding tests are executed, it will request a url in the server through an iframe representing each test being run. js-cookie-calibre expects the server to handle the input and return the proper `Set-Cookie` headers in the response. js-cookie-calibre will then read the response and verify if the encoding is consistent with js-cookie-calibre default encoding mechanism

js-cookie-calibre will send some requests to the server from the baseurl in the format `/encoding?name=<cookie>`, where `<cookie>` represents the cookie-name to be read from the request.

The server should handle those requests, internally parsing the cookie from the request and writing it again. It must set an `application/json` content type containing an object literal in the content body with `name` and `value` keys, each representing the cookie-name and cookie-value decoded by the server-side implementation.

If the server fails to respond with this specification in any request, the related QUnit test will fail. This is to make sure the server-side implementation will always be in sync with js-cookie-calibre encoding tests for maximum compatibility.


text:
/* This file performs the following test: start, read, stop and again functionality

   - It attempts to use the following three counters. It may use less depending on
     hardware counter resource limitations. These are counted in the default counting
     domain and default granularity, depending on the platform. Usually this is
     the user domain (PAPI_DOM_USER) and thread context (PAPI_GRN_THR).
     + PAPI_FP_INS or PAPI_TOT_INS if PAPI_FP_INS doesn't exist
     + PAPI_TOT_CYC

     1
   - Start counters
   - Do flops
   - Stop counters

     2
   - Start counters
   - Do flops
   - Stop counters (should duplicate above)

     3
   - Reset counters (should be redundant if stop works properly)
   - Start counters
   - Do flops
   - Stop counters

     4
   - Start counters
   - Do flops/2
   - Read counters (flops/2;counters keep counting)

     5
   - Do flops/2
   - Read counters (2flops/2; counters keep counting)

     6
   - Do flops/2
   - Read counters (3*flops/2; counters keep counting)
   - Accum counters (2*(3*flops.2); counters clear and counting)

     7
   - Do flops/2
   - Read counters (flops/2; counters keep counting)

     8
   - Reset (counters set to zero; still counting)
   - Stop counters (flops/2; counters stopped)

     9
   - Reset (counters set to zero; still counting)
   - Do flops/2
   - Stop counters (flops/2; counters stopped)

     9
   - Reset (counters set to zero and stopped)
   - Read counters (should be zero)
*/

#include "papi_test.h"

int main(int argc, char **argv)
{
  int retval, num_tests = 9, num_events, tmp, i;
   long long **values;
   int EventSet=PAPI_NULL;
   int PAPI_event, mask;
   char event_name[PAPI_MAX_STR_LEN], add_event_str[PAPI_MAX_STR_LEN];
   const PAPI_hw_info_t *hw_info;

   tests_quiet(argc, argv);     /* Set TESTS_QUIET variable */

   retval = PAPI_library_init(PAPI_VER_CURRENT);
   if (retval != PAPI_VER_CURRENT)
      test_fail(__FILE__, __LINE__, "PAPI_library_init", retval);

   hw_info = PAPI_get_hardware_info();
   if (hw_info == NULL)
     test_fail(__FILE__, __LINE__, "PAPI_get_hardware_info", 2);

   /* add PAPI_TOT_CYC and one of the events in PAPI_FP_INS, PAPI_FP_OPS or
      PAPI_TOT_INS, depending on the availability of the event on the
      platform */
   EventSet = add_two_events(&num_events, &PAPI_event, hw_info, &mask);

   retval = PAPI_event_code_to_name(PAPI_event, event_name);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_event_code_to_name", retval);
   sprintf(add_event_str, "PAPI_add_event[%s]", event_name);

   values = allocate_test_space(num_tests, num_events);

/*===== Test 1: Start/Stop =======================*/
   retval = PAPI_start(EventSet);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);

   do_flops(NUM_FLOPS);

   retval = PAPI_stop(EventSet, values[0]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

/*===== Test 2 Start/Stop =======================*/
   retval = PAPI_start(EventSet);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);

   do_flops(NUM_FLOPS);

   retval = PAPI_stop(EventSet, values[1]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

/*===== Test 3: Reset/Start/Stop =======================*/
   retval = PAPI_reset(EventSet);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_reset", retval);

   retval = PAPI_start(EventSet);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);

   do_flops(NUM_FLOPS);

   retval = PAPI_stop(EventSet, values[2]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

/*===== Test 4: Start/Read =======================*/
   retval = PAPI_start(EventSet);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_start", retval);

   do_flops(NUM_FLOPS/2);

   retval = PAPI_read(EventSet, values[3]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_read", retval);

/*===== Test 5: Read =======================*/
   do_flops(NUM_FLOPS/2);

   retval = PAPI_read(EventSet, values[4]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_read", retval);

/*===== Test 6: Read/Accum =======================*/
   do_flops(NUM_FLOPS/2);

   retval = PAPI_read(EventSet, values[5]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_read", retval);
   retval = PAPI_accum(EventSet, values[5]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_accum", retval);

/*===== Test 7: Read =======================*/
   do_flops(NUM_FLOPS/2);

   retval = PAPI_read(EventSet, values[6]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_read", retval);

/*===== Test 8 Reset/Stop =======================*/
   retval = PAPI_reset(EventSet);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_reset", retval);

   do_flops(NUM_FLOPS/2);

   retval = PAPI_stop(EventSet, values[7]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_stop", retval);

/*===== Test 9: Reset/Read =======================*/
   retval = PAPI_reset(EventSet);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_reset", retval);

   retval = PAPI_read(EventSet, values[8]);
   if (retval != PAPI_OK)
      test_fail(__FILE__, __LINE__, "PAPI_read", retval);

   remove_test_events(&EventSet, mask);

   printf("Test case: Start/Stop/Read/Accum/Reset.\n");
   printf("----------------------------------------------------------------\n");
   tmp = PAPI_get_opt(PAPI_DEFDOM, NULL);
   printf("Default domain is: %d (%s)\n", tmp, stringify_all_domains(tmp));
   tmp = PAPI_get_opt(PAPI_DEFGRN, NULL);
   printf("Default granularity is: %d (%s)\n", tmp, stringify_granularity(tmp));
   printf("Using %d iterations of c += a*b\n", NUM_FLOPS);
   printf
     ("-------------------------------------------------------------------------\n");

   sprintf(add_event_str, "%s:", event_name);
   printf("                           %s    PAPI_TOT_CYC\n", event_name);
   printf("1. start,ops,stop          %10lld      %10lld\n",values[0][0],values[0][1]);
   printf("2. start,ops,stop          %10lld      %10lld\n",values[1][0],values[1][1]);
   printf("3. reset,start,ops,stop    %10lld      %10lld\n",values[2][0],values[2][1]);
   printf("4. start,ops/2,read        %10lld      %10lld\n",values[3][0],values[3][1]);
   printf("5. ops/2,read              %10lld      %10lld\n",values[4][0],values[4][1]);
   printf("6. ops/2,accum             %10lld      %10lld\n",values[5][0],values[5][1]);
   printf("7. ops/2,read              %10lld      %10lld\n",values[6][0],values[6][1]);
   printf("8. reset,ops/2,stop        %10lld      %10lld\n",values[7][0],values[7][1]);
   printf("9. reset,read              %10lld      %10lld\n",values[8][0],values[8][1]);
   printf ("-------------------------------------------------------------------------\n");
   printf("Verification:\n");
   printf("Row 1 approximately equals rows 2 and 3 \n");
   printf("Row 4 approximately equals 1/2 of row 3\n");
   printf("Row 5 approximately equals twice row 4\n");
   printf("Row 6 approximately equals 6 times row 4\n");
   printf("Rows 7 and 8 approximately equal row 4\n");
   printf("Row 9 equals 0\n");
   printf("%% difference between %s 1 & 2: %.2f\n",add_event_str,100.0*(float)(values[0])[0]/(float)(values[1])[0]);
   printf("%% difference between %s 1 & 2: %.2f\n","PAPI_TOT_CYC",100.0*(float)(values[0])[1]/(float)(values[1])[1]);

   for (i=0;i<=1;i++)
     {
       if (!approx_equals(values[0][i],values[1][i]))
         test_fail(__FILE__, __LINE__, ((i == 0) ? add_event_str : "PAPI_TOT_CYC"), 1);
       if (!approx_equals(values[1][i],values[2][i]))
         test_fail(__FILE__, __LINE__, ((i == 0) ? add_event_str : "PAPI_TOT_CYC"), 1);
       if (!approx_equals(values[2][i],values[3][i]*2.0))
         test_fail(__FILE__, __LINE__, ((i == 0) ? add_event_str : "PAPI_TOT_CYC"), 1);
       if (!approx_equals(values[2][i],values[4][i]))
         test_fail(__FILE__, __LINE__, ((i == 0) ? add_event_str : "PAPI_TOT_CYC"), 1);
       if (!approx_equals(values[5][i],values[3][i]*6.0))
         test_fail(__FILE__, __LINE__, ((i == 0) ? add_event_str : "PAPI_TOT_CYC"), 1);
       if (!approx_equals(values[6][i],values[3][i]))
         test_fail(__FILE__, __LINE__, ((i == 0) ? add_event_str : "PAPI_TOT_CYC"), 1);
       if (!approx_equals(values[7][i],values[3][i]))
         test_fail(__FILE__, __LINE__, ((i == 0) ? add_event_str : "PAPI_TOT_CYC"), 1);
       if (values[8][i] != 0LL)
         test_fail(__FILE__, __LINE__, ((i == 0) ? add_event_str : "PAPI_TOT_CYC"), 1);
     }

   test_pass(__FILE__, values, num_tests);
   exit(1);
}


text:
<?php
namespace Ibrows\RestBundle\Tests\Unit\Listener;

use Ibrows\RestBundle\Listener\IfNonMatchResponseListener;
use PHPUnit_Framework_MockObject_MockObject;
use PHPUnit_Framework_TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class IfNoneMatchResponseListenerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var HttpKernelInterface|PHPUnit_Framework_MockObject_MockObject
     */
    private $kernel;

    public function setUp()
    {
        $this->kernel = self::createMock(HttpKernelInterface::class);
    }

    public function testMatching()
    {
        $listener = $this->getListener();

        /** @var Response|PHPUnit_Framework_MockObject_MockObject $response */
        $response = self::createMock(Response::class);

        $request = new Request();

        $response
            ->expects($this->once())
            ->method('isNotModified')
            ->with($request);

        $event = $this->getEvent($request, $response);

        $listener->onKernelResponse($event);
    }

    public function testNotMatching()
    {
        $listener = $this->getListener();

        /** @var Response|PHPUnit_Framework_MockObject_MockObject $response */
        $response = self::createMock(Response::class);

        $request = new Request();

        $response
            ->method('isNotModified')
            ->with($request)
            ->willReturn(false);

        $response
            ->expects($this->never())
            ->method('setNotModified');

        $event = $this->getEvent($request, $response);

        $listener->onKernelResponse($event);
    }

    /**
     * @param Request  $request
     * @param Response $response
     * @return FilterResponseEvent
     */
    private function getEvent(Request $request, Response $response)
    {
        return new FilterResponseEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response);
    }

    /**
     * @return IfNonMatchResponseListener
     */
    private function getListener()
    {
        return new IfNonMatchResponseListener([]);
    }
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginStart="18dp"
        android:layout_marginEnd="18dp"
        android:gravity="center_vertical"
        android:textSize="@dimen/font_size_normal" />

</FrameLayout>


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


text:
<?php

namespace CentralNews\Service;

use CentralNews\Exception;

class Client
{
    const URL = 'url';
    const TOKEN = 'token';
    const USER = 'user';
    const PASSWORD = 'password';
    const ENCODING = 'encoding';

    /** @var \CentralNews\Model\SubscriberManager */
    protected $subscriberManager;

    /** @var \CentralNews\Model\OrderManager */
    protected $orderManager;

    /** @var \CentralNews\Model\EventManager */
    protected $eventManager;

    /** @var \CentralNews\Model\Manager */
    protected $manager;

    /** @var array */
    protected $params;

    /** @var SoapClient */
    protected $soapClient;

    /** @var array */
    protected $headers;

    /**
     * @param array $params
     */
    public function __construct(array $params)
    {
        $this->params = $params;

        $this->setHeaders(array(
            SoapClient::PASSWORD => $params[self::PASSWORD],
            SoapClient::TOKEN => $params[self::TOKEN],
            SoapClient::USER => $params[self::USER],
        ));

        $this->soapClient = $this->createSoapClient();
    }

    protected function createSoapClient()
    {
        $client = new SoapClient();
        $client->setUrl($this->getParam(self::URL, 'http://localhost'));
        $client->setEncoding($this->getParam(self::ENCODING, 'UTF-8'));
        $client->setHeaders($this->headers);
        return $client;
    }

    protected function getParam($name, $default = null)
    {
        return isset($this->params[$name]) ? $this->params[$name] : $default;
    }

    /**
     * @param string $name
     * @return mixed
     * @throws Exception\InvalidArgumentException
     */
    public function __get($name)
    {
        $getter = 'get' . ucfirst($name);
        if (method_exists($this, $getter)) {
            return $this->$getter();
        }

        throw new Exception\InvalidArgumentException;
    }

    /**
     * @return \CentralNews\Model\SubscriberManager
     */
    public function getSubscriberManager()
    {
        if (!$this->subscriberManager) {
            $this->subscriberManager = $this->createSubscriberManager();
        }
        return $this->subscriberManager;
    }

    /**
     * @return \CentralNews\Model\SubscriberManager
     */
    protected function createSubscriberManager()
    {
        return new \CentralNews\Model\SubscriberManager($this->soapClient);
    }

    /**
     * @return \CentralNews\Model\OrderManager
     */
    public function getOrderManager()
    {
        if (!$this->orderManager) {
            $this->orderManager = $this->createOrderManager();
        }
        return $this->orderManager;
    }

    /**
     * @return \CentralNews\Model\OrderManager
     */
    protected function createOrderManager()
    {
        return new \CentralNews\Model\OrderManager($this->soapClient);
    }

    /**
     * @return \CentralNews\Model\EventManager
     */
    public function getEventManager()
    {
        if (!$this->eventManager) {
            $this->eventManager = $this->createEventManager();
        }
        return $this->eventManager;
    }

    /**
     * @return \CentralNews\Model\EventManager
     */
    protected function createEventManager()
    {
        return new \CentralNews\Model\EventManager($this->soapClient);
    }

    /**
     * @return \CentralNews\Model\Manager
     */
    public function getManager()
    {
        if (!$this->manager) {
            $this->manager = $this->createManager();
        }
        return $this->manager;
    }

    /**
     * @return \CentralNews\Model\Manager
     */
    protected function createManager()
    {
        return new \CentralNews\Model\Manager($this->soapClient);
    }

    /**
     * @param \CentralNews\Service\Request $request
     * @return \CentralNews\Service\Response
     */
    public function sendRequest(Request $request)
    {
        return $this->getManager()->sendRequest($request);
    }

    public function setHeaders(array $headers)
    {
        $this->headers = $headers;
    }

    /**
     * @param string $email
     * @return bool
     */
    public static function isEmail($email)
    {
        $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]";
        $localPart = "(?:\"(?:[ !\\x23-\\x5B\\x5D-\\x7E]*|\\\\[ -~])+\"|$atom+(?:\\.$atom+)*)";
        $alpha = "a-z\x80-\xFF";
        $domain = "[0-9$alpha](?:[-0-9$alpha]{0,61}[0-9$alpha])?";
        $topDomain = "[$alpha](?:[-0-9$alpha]{0,17}[$alpha])?";
        return (bool) preg_match("(^$localPart@(?:$domain\\.)+$topDomain\\z)i", $email);
    }

}


text:
import { EventEmitter } from 'events';
import requireAll       from 'require-all';
import Resolver         from './resolver';
import Singleton        from './singleton';

function parseRequires(requires) {
  let parsed = {}
  Object.keys(requires).forEach(function(key) {
    let isModule = ( typeof requires[key].default === "function" )
    let nodeName = isModule ? requires[key].default.name : key // Store by classname
    parsed[nodeName] = {
      type: isModule ? "module" : "branch",
      contents: isModule ? requires[key] : parseRequires(requires[key])
    }
  })
  return parsed;
}

export default class Container extends EventEmitter {
  constructor(path) {
    super()
    this._modules   = parseRequires(requireAll({recursive: true, dirname: path}))
    this._singleton = new Singleton()
    this._resolver  = new Resolver(this._modules, this._singleton)
  }
  create(className, ...args) {
    return new (this._resolver.injectDeps(className))(...args)
  }
  singleton(className, ...args) {
    if (this._singleton.isSingleton(className)) {
      throw new Error (`Singleton "${className}" already declared`)
    }
    return new (this._singleton.create(className, this._resolver.injectDeps(className), ...args))
  }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TrackingDetails.cs" company="Naos">
//    Copyright (c) Naos 2017. All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Naos.MessageBus.Persistence
{
    using Naos.MessageBus.Domain;
    using Naos.Telemetry.Domain;

    /// <summary>
    /// Model class to track information by tracking code.
    /// </summary>
    public class TrackingDetails
    {
        /// <summary>
        /// Gets the recipient.
        /// </summary>
        public DiagnosticsTelemetry Recipient { get; internal set; }

        /// <summary>
        /// Gets or sets the message of the exception.
        /// </summary>
        public string ExceptionMessage { get; set; }

        /// <summary>
        /// Gets or sets the exception serialized using <see cref="ParcelTrackingSerializationExtensions" /> (not guaranteed that is can deserialize).
        /// </summary>
        public string ExceptionSerializedAsString { get; set; }

        /// <summary>
        /// Gets the status.
        /// </summary>
        public ParcelStatus Status { get; internal set; }

        /// <summary>
        /// Gets the envelope.
        /// </summary>
        public Envelope Envelope { get; internal set; }
    }
}


text:
module SakuraChan
  module Pictures
    extend Discordrb::Commands::CommandContainer
    def self.isblacklist?(command)
      Config.commands_blacklist.include?(command.to_s)
    end

    def self.channeliswhitelist?(channel)
      Config.commands_channels_whitelist.include?(channel)
    end

    image_dir = {
      computer_fun: 'images/computerfun'
    }

    image_dir.each do |name, dir|
      command(name, max_args: 0) do |event|
        if Pictures.isblacklist?(event.command.name) && !Pictures.channeliswhitelist?(event.channel.name)
          event.respond('Sorry this is not permitted in this channel, go to another channel!')
          break
        else
          # check whether or not the dir exists & whether or not it has images
          if !File.exist?(dir)

            # there's no dir, tell it to the user of the program
            event.respond("The image directory for the command **#{name}** does not exist!")
            return
          elsif (Dir.entries(dir) - %w[. ..]).empty?
            event.respond("There are no images in the directory for the command **#{name}**!")
            return
          end

          # Shows that the bot is typing
          event.channel.start_typing

          files = []
          # Selects everything that is a file
          files = Dir[dir + '/*'].select { |e| File.file?(e) }
          file = files.sample
          puts "Selected the image \"#{file}\" for command '#{name}'."
          event.channel.send_file File.new([file.to_s].sample)
        end
      end
    end
  end
end


text:
package com.cnpc.framework.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.Map;

/**
 * SessionUtil session 工具类
 *
 * @author billJiang 2016年3月26日 下午10:12:16
 */
public class SessionUtil {

    public static Session getSession() {

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        return session;
    }

    public static String getUserId() {
        return SecurityUtils.getSubject().getPrincipal().toString();
    }

}


text: from _Evt import *