text:
import {oneLineTrim} from 'common-tags';
import {BaseHrefWebpackPlugin} from './base-href-webpack-plugin';

function mockCompiler(indexHtml: string, callback: Function) {
  return {
    plugin: function (event: any, compilerCallback: Function) {
      const compilation = {
        plugin: function (hook: any, compilationCallback: Function) {
          const htmlPluginData = {
            html: indexHtml
          };
          compilationCallback(htmlPluginData, callback);
        }
      };
      compilerCallback(compilation);
    }
  };
}

describe('base href webpack plugin', () => {
  const html = oneLineTrim`

  `;

  it('should do nothing when baseHref is null', () => {
    const plugin = new BaseHrefWebpackPlugin({ baseHref: null });

    const compiler = mockCompiler(html, (x: any, htmlPluginData: any) => {
      expect(htmlPluginData.html).toEqual('');
    });
    plugin.apply(compiler);
  });

  it('should insert base tag when not exist', function () {
    const plugin = new BaseHrefWebpackPlugin({ baseHref: '/' });
    const compiler = mockCompiler(html, (x: any, htmlPluginData: any) => {
        expect(htmlPluginData.html).toEqual(oneLineTrim`

            <base href="/">

        `);
      });

    plugin.apply(compiler);
  });

  it('should replace href attribute when base tag already exists', function () {
    const plugin = new BaseHrefWebpackPlugin({ baseHref: '/myUrl/' });

    const compiler = mockCompiler(oneLineTrim`
          <base href="/" target="_blank">

        `, (x: any, htmlPluginData: any) => {
      expect(htmlPluginData.html).toEqual(oneLineTrim`
          <base href="/myUrl/" target="_blank">

        `);
    });
    plugin.apply(compiler);
  });
});


text:
var o = require('../lib/o.js');
var test = require('tap').test;

test('basic', function (t) {
    t.is( o.definedType.check(1), true, 'number is defined' );
    t.is( o.definedType.check(null), true, 'null is defined' );
    t.is( o.definedType.check(undefined), false, 'undefined is not defined' );
    t.end();
});

redpajama_set_name: RedPajamaGithub


text:
import gzip
import os
from conary_test import rephelp
import tempfile

from conary.build import packagerecipe, manifest
from conary.lib import util, magic

renamePolicy = """
import os
from conary.build import policy
from conary.lib import util

class BogusRename(policy.DestdirPolicy):
    def doFile(self, path):
        realPath = util.joinPaths(self.recipe.macros.destdir, path)
        if os.path.isdir(realPath) and os.listdir(realPath):
            return
        newPath = realPath + '-1'
        os.rename(realPath, newPath)
        self.recipe.recordMove(realPath, newPath)
"""

class ManifestTest(rephelp.RepositoryHelper):
    def setUp(self):
        rephelp.RepositoryHelper.setUp(self)
        self.destdir = os.path.join(self.tmpDir, '_ROOT_')
        util.mkdirChain(self.destdir)
        self.policyCount = 0
        self.policyDirs = []

    def tearDown(self):
        for path in self.policyDirs:
            util.rmtree(path)
        util.rmtree(self.destdir)
        rephelp.RepositoryHelper.tearDown(self)

    def touch(self, fn, contents = ''):
        if os.path.exists(fn):
            return
        util.mkdirChain(os.path.dirname(fn))
        f = open(fn, 'w')
        f.write(contents)
        f.close()

    def addPolicy(self, policyStr):
        tmpPolicyDir = tempfile.mkdtemp()
        self.policyDirs.append(tmpPolicyDir)
        policyFn = os.path.join(tmpPolicyDir, 'policy%d.py' % self.policyCount)
        self.policyCount += 1
        f = open(policyFn, 'w')
        f.write(policyStr)
        f.close()
        self.cfg.policyDirs.append(tmpPolicyDir)

    def getRecipe(self):
        class DummyPackageRecipe(packagerecipe.PackageRecipe):
            def __init__(x):
                x.name = 'package'
                x.version = '1.0'
                packagerecipe.PackageRecipe.__init__(x, self.cfg, None, None)
                x._loadSourceActions(lambda y: True)
                x.loadPolicy()
                x.macros.destdir = self.destdir
        return DummyPackageRecipe()

    def getLegacyRecipe(self):
        def recordMove(*args, **kwargs):
            raise AttributeError("recordMove didn't exists in legacy recipes")
        r = self.getRecipe()
        r.recordMove = recordMove
        return r

    def testExplicitRecord(self):
        r = self.getRecipe()
        man = manifest.ExplicitManifest('foo:runtime', r)
        path = '/foo'
        man.recordPaths(path)
        self.assertEquals(man.manifestPaths, set(['/foo']))

    def testExtraSepRecord1(self):
        r = self.getRecipe()
        man = manifest.ExplicitManifest('foo:runtime', r)
        path = '//foo'
        man.recordPaths(path)
        self.assertEquals(man.manifestPaths, set(['/foo']))

    def testExtraSepRecord2(self):
        r = self.getRecipe()
        man = manifest.ExplicitManifest('foo:runtime', r)
        path = '/' + r.macros.destdir + '//foo'
        man.recordPaths(path)
        self.assertEquals(man.manifestPaths, set(['/foo']))

    def testDestDirTranslate(self):
        r = self.getRecipe()
        man = manifest.ExplicitManifest('foo', r)
        path = os.path.join(self.destdir, 'foo')
        man.recordPaths(path)
        self.assertEquals(man.manifestPaths, set(['/foo']))

    def testRemoveSep(self):
        r = self.getRecipe()
        man = manifest.ExplicitManifest('foo', r)
        path = os.path.sep + os.path.join(self.destdir, 'foo')
        man.recordPaths(path)
        self.assertEquals(man.manifestPaths, set(['/foo']))

    def testWalk(self):
        r = self.getRecipe()
        man = manifest.ExplicitManifest('foo', r)
        path = os.path.sep + os.path.join(self.destdir, 'foo')
        man.recordPaths(path)
        man.walk(init = True)
        self.assertEquals(man.fileSet, set(['/foo']))

        # repeat test to ensure behavior is invariant of init param
        man.fileSet = set()
        man.manifestPaths = set()
        man.recordPaths(path)
        man.walk(init = False)
        self.assertEquals(man.fileSet, set(['/foo']))

    def testCreate(self):
        r = self.getRecipe()
        man = manifest.ExplicitManifest('foo', r)
        path = os.path.sep + os.path.join(self.destdir, 'foo')
        man.recordPaths(path)
        man.manifestsDir = tempfile.mkdtemp()
        try:
            man.manifestFile = os.path.join(man.manifestsDir,
                    os.path.basename(man.manifestFile))
            man.create()
            self.assertEquals('/foo\n', open(man.manifestFile).read())
        finally:
            util.rmtree(man.manifestsDir)

    def testLoad(self):
        r = self.getRecipe()
        r._pathTranslations.append(('/foo', '/bar'))
        man = manifest.ExplicitManifest('foo', r)
        path = os.path.sep + os.path.join(self.destdir, 'foo')
        man.recordPaths(path)
        man.manifestsDir = tempfile.mkdtemp()
        try:
            man.manifestFile = os.path.join(man.manifestsDir,
                    os.path.basename(man.manifestFile))
            man.create()
            regexp = man.load()
        finally:
            util.rmtree(man.manifestsDir)
        self.assertFalse(regexp.match('/foo'))
        self.assertFalse(not regexp.match('/bar'))

    def testTranslatePath(self):
        r = self.getRecipe()
        r._pathTranslations.append(('/foo', '/bar'))
        man = manifest.ExplicitManifest('foo', r)
        self.assertEquals(man.translatePath('/foo'), '/bar')

    def testDocRemap(self):
        recipestr1 = """
class RenamedDocs(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()

    def setup(self):
        # these files should end up in the foo package (CNY-1679)
        # we're looking to prove that Doc followed a PackageSpec through
        # the path translation process
        self.addSource('sourcefile')
        self.Doc('sourcefile', package = 'foo')
"""
        self.addPolicy(renamePolicy)
        (built, d) = self.buildRecipe(recipestr1, "RenamedDocs")

        # first prove the package spec for Doc worked.
        self.assertEquals(len(built), 1)
        self.assertEquals(built[0][0], 'foo:supdoc')

        repos = self.openRepository()
        trvNVF = repos.findTrove(None, built[0])
        trv = repos.getTrove(*trvNVF[0])
        fileInfo = [x for x in trv.iterFileList()][0]

        # prove the name was changed
        self.assertEquals(fileInfo[1], '/usr/share/doc/test-0/sourcefile-1')

    def testInstallRemap(self):
        recipestr1 = """
class RenamedInstalls(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()

    def setup(self):
        # these files should end up in the foo package (CNY-1679)
        # we're looking to prove that Install followed a PackageSpec through
        # the path translation process
        self.addSource('sourcefile')
        self.Install('sourcefile', '/foo', package = 'foo')
"""
        self.addPolicy(renamePolicy)
        (built, d) = self.buildRecipe(recipestr1, "RenamedInstalls")

        # first prove the package spec for Install worked.
        self.assertEquals(len(built), 1)
        self.assertEquals(built[0][0], 'foo:runtime')

        repos = self.openRepository()
        trvNVF = repos.findTrove(None, built[0])
        trv = repos.getTrove(*trvNVF[0])
        fileInfo = [x for x in trv.iterFileList()][0]

        # prove the name was changed
        self.assertEquals(fileInfo[1], '/foo-1')

    def testJavaDocRemap(self):
        recipestr1 = """
class RenamedJavaDocs(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()

    def setup(self):
        # these files should end up in the foo package (CNY-1679)
        # we're looking to prove that JavaDoc followed a PackageSpec through
        # the path translation process
        self.addSource('sourcefile')
        self.JavaDoc('sourcefile', package = 'foo')
"""
        self.addPolicy(renamePolicy)
        (built, d) = self.buildRecipe(recipestr1, "RenamedJavaDocs")

        # first prove the package spec for JavaDoc worked.
        self.assertEquals(len(built), 1)
        self.assertEquals(built[0][0], 'foo:doc')

        repos = self.openRepository()
        trvNVF = repos.findTrove(None, built[0])
        trv = repos.getTrove(*trvNVF[0])
        fileInfo = [x for x in trv.iterFileList()][0]

        # prove the name was changed
        self.assertEquals(fileInfo[1], '/usr/share/javadoc/test-0/sourcefile-1')

    def testMakeDirsRemap(self):
        recipestr1 = """
class RenamedDirs(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()

    def setup(self):
        # these files should end up in the foo package (CNY-1679)
        # we're looking to prove that MakeDirs followed a PackageSpec through
        # the path translation process
        self.MakeDirs('/foo', package = 'foo')
        self.ExcludeDirectories(exceptions = '/foo-1')
"""
        self.addPolicy(renamePolicy)
        (built, d) = self.buildRecipe(recipestr1, "RenamedDirs")

        # first prove the package spec for MakeDirs worked.
        self.assertEquals(len(built), 1)
        self.assertEquals(built[0][0], 'foo:runtime')

        repos = self.openRepository()
        trvNVF = repos.findTrove(None, built[0])
        trv = repos.getTrove(*trvNVF[0])
        fileInfo = [x for x in trv.iterFileList()][0]

        # prove the name was changed
        self.assertEquals(fileInfo[1], '/foo-1')

    def testMakeFIFORemap(self):
        recipestr1 = """
class MkFIFO(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()

    def setup(self):
        # these files should end up in the foo package (CNY-1679)
        # we're looking to prove that MakeFIFO followed a PackageSpec through
        # the path translation process
        self.MakeFIFO('/foo', package = 'foo')
"""
        self.addPolicy(renamePolicy)
        (built, d) = self.buildRecipe(recipestr1, "MkFIFO")

        # first prove the package spec for MakeFIFO worked.
        self.assertEquals(len(built), 1)
        self.assertEquals(built[0][0], 'foo:runtime')

        repos = self.openRepository()
        trvNVF = repos.findTrove(None, built[0])
        trv = repos.getTrove(*trvNVF[0])
        fileInfo = [x for x in trv.iterFileList()][0]

        # prove the name was changed
        self.assertEquals(fileInfo[1], '/foo-1')

    def testSymlinkDirRemap(self):
        recipestr1 = """
class SymlinkDirRemap(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()

    def setup(self):
        # these files should end up in the foo package (CNY-1679)
        # we're looking to prove that Symlink followed a PackageSpec through
        # the path translation process
        self.Symlink('/foo', '/foo/symlink', package = 'foo')
"""
        self.addPolicy(renamePolicy)
        (built, d) = self.buildRecipe(recipestr1, "SymlinkDirRemap")

        # first prove the package spec for Symlink worked.
        self.assertEquals(len(built), 1)
        self.assertEquals(built[0][0], 'foo:runtime')

        repos = self.openRepository()
        trvNVF = repos.findTrove(None, built[0])
        trv = repos.getTrove(*trvNVF[0])
        fileInfo = [x for x in trv.iterFileList()][0]

        # prove the name was changed
        self.assertEquals(fileInfo[1], '/foo/symlink-1')

    def testSymlinkFileRemap(self):
        recipestr1 = """
class SymlinkFileRemap(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()

    def setup(self):
        # these files should end up in the foo package (CNY-1679)
        # we're looking to prove that Symlink followed a PackageSpec through
        # the path translation process
        self.Create('/foo/file', package = 'foo')
        # we have to know that the target of our symlink is going to be renamed
        self.Symlink('/foo/file-1', '/foo/symlink', package = 'foo')
"""
        self.addPolicy(renamePolicy)
        (built, d) = self.buildRecipe(recipestr1, "SymlinkFileRemap")

        # first prove the package spec for Symlink worked.
        self.assertEquals(len(built), 1)
        self.assertEquals(built[0][0], 'foo:runtime')

        repos = self.openRepository()
        trvNVF = repos.findTrove(None, built[0])
        trv = repos.getTrove(*trvNVF[0])
        fileNames = [x[1] for x in trv.iterFileList()]

        # prove the name was changed
        self.assertFalse('/foo/symlink-1' not in fileNames)

    def testLinkFileRemap(self):
        recipestr1 = """
class LinkFileRemap(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()

    def setup(self):
        # these files should end up in the foo package (CNY-1679)
        # we're looking to prove that Link followed a PackageSpec through
        # the path translation process
        self.Create('/foo/file', package = 'foo')
        # we have to know that the target of our link is going to be renamed
        self.Link('/foo/link', '/foo/file', package = 'foo')
"""
        self.addPolicy(renamePolicy)
        (built, d) = self.buildRecipe(recipestr1, "LinkFileRemap")

        # first prove the package spec for Symlink worked.
        self.assertEquals(len(built), 1)
        self.assertEquals(built[0][0], 'foo:runtime')

        repos = self.openRepository()
        trvNVF = repos.findTrove(None, built[0])
        trv = repos.getTrove(*trvNVF[0])
        fileNames = [x[1] for x in trv.iterFileList()]

        # prove the name was changed
        self.assertFalse('/foo/link-1' not in fileNames)

    def testXInetdServiceRemap(self):
        recipestr1 = """
class XInetdServiceRemap(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()

    def setup(self):
        # these files should end up in the foo package (CNY-1679)
        # we're looking to prove that XInetdService followed a PackageSpec through
        # the path translation process
        self.XInetdService('foo', 'bogus description', type = 'test',
                protocol = 'tcp', package = 'foo')
"""
        self.addPolicy(renamePolicy)
        (built, d) = self.buildRecipe(recipestr1, "XInetdServiceRemap")

        # first prove the package spec for XInetdService worked.
        self.assertEquals(len(built), 1)
        self.assertEquals(built[0][0], 'foo:config')

        repos = self.openRepository()
        trvNVF = repos.findTrove(None, built[0])
        trv = repos.getTrove(*trvNVF[0])
        fileInfo = [x for x in trv.iterFileList()][0]

        # prove the name was changed
        self.assertEquals(fileInfo[1], '/etc/xinetd.d/foo-1')

    def testFixupManpagePaths(self):
        recipestr0 = """
class TestFilesInMandir(PackageRecipe):
    name = 'test'
    version = '0'
    clearBuildReqs()
    def setup(self):
        # this test exercises the FixupManpagePaths policy in conjunction with
        # package spec
        self.Create('%(mandir)s/foo.1', package = 'manpage')
"""
        self.reset()
        (built, d) = self.buildRecipe(recipestr0, "TestFilesInMandir")
        self.assertEquals(built[0][0], 'manpage:doc')

    def testFixupManpagePathsLegacyCompat(self):
        # prove that conary-policy will work with older versions of conary
        r = self.getLegacyRecipe()
        filePath = os.path.join(self.destdir, 'usr', 'share', 'man', 'foo.1')
        newPath = os.path.join(self.destdir,
                'usr', 'share', 'man', 'man1', 'foo.1')
        util.mkdirChain(os.path.dirname(newPath))
        self.touch(filePath)
        r.FixupManpagePaths(filePath)
        # we want to run just this policy
        self.captureOutput(r._policyMap['FixupManpagePaths'].doProcess, r)

        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))

        # we expect that the move wasn't recorded
        self.assertEquals(r._pathTranslations, [])

    def testFixObsoletePathsLegacyCompat(self):
        # prove that conary-policy will work with older versions of conary
        r = self.getLegacyRecipe()
        filePath = os.path.join(self.destdir, 'usr', 'info', 'foo')
        newPath = os.path.join(self.destdir,
                'usr', 'share', 'info', 'foo')
        util.mkdirChain(os.path.dirname(newPath))
        self.touch(filePath)
        r.FixObsoletePaths(filePath)
        # we want to run just this policy
        self.captureOutput(r._policyMap['FixObsoletePaths'].doProcess, r)

        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))

        # we expect that the move wasn't recorded
        self.assertEquals(r._pathTranslations, [])

    def testFixMultilibPathsLegacyCompat(self):
        # prove that conary-policy will work with older versions of conary
        r = self.getLegacyRecipe()
        path = os.path.join(os.path.sep, 'lib', 'foo.so')
        filePath = util.joinPaths(self.destdir, path)
        newPath = os.path.join(self.destdir, 'libXX', 'foo.so')
        symlinkPath = os.path.join(os.path.sep, 'lib', 'symlink.so')

        self.touch(filePath, contents = '\x7fELF fake of course...')
        os.symlink('foo.so', util.joinPaths(self.destdir, symlinkPath))

        r.macros.lib = 'libXX'
        r.FixupMultilibPaths()
        # we want to run just this policy
        m = magic.Magic(path, self.destdir)
        m.name = 'ELF'
        r.magic = {}
        r.magic[path] = m
        r.magic[symlinkPath] = m
        r._policyMap['FixupMultilibPaths'].test = lambda *args, **kwargs: True
        r._policyMap['FixupMultilibPaths'].dirmap = \
                {'/usr/lib' : '/usr/libXX', '/lib' : '/libXX'}
        self.captureOutput(r._policyMap['FixupMultilibPaths'].doProcess, r)

        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))
        self.assertFalse(os.path.exists(util.joinPaths(self.destdir, symlinkPath)))
        self.assertFalse(not os.path.exists(util.joinPaths(self.destdir,
            'libXX', 'symlink.so')))

        # we expect that the move wasn't recorded
        self.assertEquals(r._pathTranslations, [])

    def testFixMultilibPaths(self):
        # prove that conary-policy will work with older versions of conary
        r = self.getRecipe()
        path = os.path.join(os.path.sep, 'lib', 'foo.so')
        filePath = util.joinPaths(self.destdir, path)
        newPath = os.path.join(self.destdir, 'libXX', 'foo.so')
        symlinkPath = os.path.join(os.path.sep, 'lib', 'symlink.so')

        self.touch(filePath, contents = '\x7fELF fake of course...')
        os.symlink('foo.so', util.joinPaths(self.destdir, symlinkPath))

        r.macros.lib = 'libXX'
        r.FixupMultilibPaths()
        # we want to run just this policy
        m = magic.Magic(path, self.destdir)
        m.name = 'ELF'
        r.magic = {}
        r.magic[path] = m
        r.magic[symlinkPath] = m
        r._policyMap['FixupMultilibPaths'].test = lambda *args, **kwargs: True
        r._policyMap['FixupMultilibPaths'].dirmap = \
                {'/usr/lib' : '/usr/libXX', '/lib' : '/libXX'}
        self.captureOutput(r._policyMap['FixupMultilibPaths'].doProcess, r)

        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))
        self.assertFalse(os.path.exists(util.joinPaths(self.destdir, symlinkPath)))
        self.assertFalse(not os.path.exists(util.joinPaths(self.destdir,
            'libXX', 'symlink.so')))

        # we expect that the move was recorded
        # the order foo vs symlink get evaluated isn't stable. sorting here
        # doesn't hurt anything
        self.assertEquals(sorted(r._pathTranslations),
                sorted([('/lib/foo.so', '/libXX/foo.so'),
                    ('/lib/symlink.so', '/libXX/symlink.so')]))

    def testNormalizePkgConfigLegacy(self):
        r = self.getLegacyRecipe()
        path = os.path.join(os.path.sep, r.macros.datadir, 'pkgconfig', 'foo')
        filePath = util.joinPaths(self.destdir, path)
        newPath = util.joinPaths(self.destdir,
                r.macros.libdir, 'pkgconfig', 'foo')
        self.touch(filePath)
        r.NormalizePkgConfig()
        self.captureOutput(r._policyMap['NormalizePkgConfig'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))

        # we expect that no move was recorded
        self.assertEquals(r._pathTranslations, [])

    def testNormalizePkgConfig(self):
        r = self.getRecipe()
        path = os.path.join(os.path.sep, r.macros.datadir, 'pkgconfig', 'foo')
        filePath = util.joinPaths(self.destdir, path)
        newPath = util.joinPaths(self.destdir,
                r.macros.libdir, 'pkgconfig', 'foo')
        self.touch(filePath)
        r.NormalizePkgConfig()
        self.captureOutput(r._policyMap['NormalizePkgConfig'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))

        # we expect that no move was recorded
        self.assertEquals(r._pathTranslations,
                [('/usr/share/pkgconfig/foo',
                    r.macros.libdir + '/pkgconfig/foo')])

    def testNormalizeManPages(self):
        r = self.getRecipe()
        path = os.path.join(os.path.sep, r.macros.mandir, 'man1', 'foo.1.gz')
        path2 = os.path.join(os.path.sep,
                r.macros.mandir, 'man1', 'bar.1.bz2')
        filePath = util.joinPaths(self.destdir, path)
        filePath2 = util.joinPaths(self.destdir, path2)
        self.touch(filePath)
        self.touch(filePath2[:-4], contents = 'text')
        g = gzip.open(filePath, 'w')
        g.write('some comrpessed data')
        g.close()
        self.captureOutput(os.system, 'bzip2 %s' % filePath2[:-4])
        r.NormalizeManPages()
        self.captureOutput(r._policyMap['NormalizeManPages'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(not os.path.exists(filePath))
        self.assertFalse(not os.path.exists(filePath2[:-4] + '.gz'))
        self.assertFalse(os.path.exists(filePath2))

        # we expect that moves were recorded
        # the order foo/bar get evaluated isn't stable. we'll just sort for
        # test purposes
        self.assertEquals(sorted(r._pathTranslations),
                sorted([('/usr/share/man/man1/foo.1.gz',
                    '/usr/share/man/man1/foo.1'),
                 ('/usr/share/man/man1/bar.1.bz2',
                     '/usr/share/man/man1/bar.1'),
                 ('/usr/share/man/man1/bar.1',
                     '/usr/share/man/man1/bar.1.gz'),
                 ('/usr/share/man/man1/foo.1',
                     '/usr/share/man/man1/foo.1.gz')]))

    def testNormalizeManPagesLegacy(self):
        r = self.getLegacyRecipe()
        path = os.path.join(os.path.sep, r.macros.mandir, 'man1', 'foo.1.gz')
        path2 = os.path.join(os.path.sep,
                r.macros.mandir, 'man1', 'bar.1.bz2')
        filePath = util.joinPaths(self.destdir, path)
        filePath2 = util.joinPaths(self.destdir, path2)
        self.touch(filePath)
        self.touch(filePath2[:-4], contents = 'text')
        g = gzip.open(filePath, 'w')
        g.write('some comrpessed data')
        g.close()
        self.captureOutput(os.system, 'bzip2 %s' % filePath2[:-4])
        r.NormalizeManPages()
        self.captureOutput(r._policyMap['NormalizeManPages'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(not os.path.exists(filePath))
        self.assertFalse(not os.path.exists(filePath2[:-4] + '.gz'))
        self.assertFalse(os.path.exists(filePath2))

        # we expect that no moves were recorded
        self.assertEquals(r._pathTranslations, [])

    def testNormalizeInfoPagesLegacy(self):
        r = self.getLegacyRecipe()
        path = os.path.join(os.path.sep, r.macros.infodir, 'man1', 'foo.gz')
        filePath = util.joinPaths(self.destdir, path)
        newPath = os.path.join(os.path.sep, r.macros.infodir, 'foo.gz')
        self.touch(filePath)
        g = gzip.open(filePath, 'w')
        g.write('some comrpessed data')
        g.close()
        r.NormalizeInfoPages()
        m = magic.Magic(path, self.destdir)
        m.name = 'gzip'
        m.contents['compression'] = 5
        r.magic = {}
        r.magic[path] = m
        r.magic[newPath] = m
        r._policyMap['NormalizeInfoPages'].doProcess(r)
        #self.captureOutput(r._policyMap['NormalizeInfoPages'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(os.path.exists(filePath))
        self.assertFalse(not os.path.exists(util.joinPaths(self.destdir, newPath)))

        # we expect that no moves were recorded
        self.assertEquals(r._pathTranslations, [])

    def testNormalizeInfoPages(self):
        r = self.getRecipe()
        path = os.path.join(os.path.sep, r.macros.infodir, 'man1', 'foo.gz')
        filePath = util.joinPaths(self.destdir, path)
        newPath = os.path.join(os.path.sep, r.macros.infodir, 'foo.gz')
        self.touch(filePath)
        g = gzip.open(filePath, 'w')
        g.write('some comrpessed data')
        g.close()
        r.NormalizeInfoPages()
        m = magic.Magic(path, self.destdir)
        m.name = 'gzip'
        m.contents['compression'] = 5
        r.magic = {}
        r.magic[path] = m
        r.magic[newPath] = m
        r._policyMap['NormalizeInfoPages'].doProcess(r)
        #self.captureOutput(r._policyMap['NormalizeInfoPages'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(os.path.exists(filePath))
        self.assertFalse(not os.path.exists(util.joinPaths(self.destdir, newPath)))

        # we expect that moves were recorded
        self.assertEquals(r._pathTranslations,
                [('/usr/share/info/man1/foo.gz', '/usr/share/info/foo.gz')])

    def testNormalizeBz2InfoPages(self):
        r = self.getRecipe()
        path = os.path.join(os.path.sep, r.macros.infodir, 'man1', 'foo.bz2')
        filePath = util.joinPaths(self.destdir, path)
        newPath = os.path.join(os.path.sep, r.macros.infodir, 'foo.gz')
        self.touch(filePath[:-4])
        self.captureOutput(os.system, 'bzip2 %s' % filePath[:-4])

        r.NormalizeInfoPages()
        m = magic.Magic(path, self.destdir)
        m.name = 'bzip'
        m.contents['compression'] = 5
        r.magic = {}
        r.magic[path] = m
        r.magic[newPath] = m
        r.magic[newPath[:-3] + '.bz2'] = m
        r._policyMap['NormalizeInfoPages'].doProcess(r)
        #self.captureOutput(r._policyMap['NormalizeInfoPages'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(os.path.exists(filePath))
        self.assertFalse(not os.path.exists(util.joinPaths(self.destdir, newPath)))

        # we expect that moves were recorded
        self.assertEquals(r._pathTranslations,
                [('/usr/share/info/man1/foo.bz2',
                    '/usr/share/info/foo.bz2'),
                 ('/usr/share/info/foo.bz2',
                     '/usr/share/info/foo.gz')])

    def testNormalizeInitscriptLocationLegacy(self):
        r = self.getLegacyRecipe()
        path = os.path.join(os.path.sep, 'etc', 'rc.d', 'init.d', 'foo')
        filePath = util.joinPaths(self.destdir, path)
        newPath = os.path.join(self.destdir, 'foo', 'foo')
        self.touch(filePath)
        r.macros.initdir = '/foo'
        r.NormalizeInitscriptLocation()
        self.captureOutput( \
                r._policyMap['NormalizeInitscriptLocation'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))

        # we expect that no move was recorded
        self.assertEquals(r._pathTranslations, [])

    def testNormalizeInitscriptLocation(self):
        r = self.getRecipe()
        path = os.path.join(os.path.sep, 'etc', 'rc.d', 'init.d', 'foo')
        filePath = util.joinPaths(self.destdir, path)
        newPath = os.path.join(self.destdir, 'foo', 'foo')
        self.touch(filePath)
        r.macros.initdir = '/foo'
        r.NormalizeInitscriptLocation()
        self.captureOutput( \
                r._policyMap['NormalizeInitscriptLocation'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))

        # we expect that no move was recorded
        self.assertEquals(r._pathTranslations,
                [('/etc/rc.d/init.d/foo', '/foo/foo')])

    def testNormalizeAppDefaultsLegacy(self):
        r = self.getLegacyRecipe()
        path = os.path.join(os.path.sep, 'etc', 'X11', 'app-defaults', 'foo')
        filePath = util.joinPaths(self.destdir, path)
        newPath = os.path.join(self.destdir, 'usr', 'X11R6', 'lib', 'X11', 'app-defaults', 'foo')
        self.touch(filePath)
        r.NormalizeAppDefaults()
        self.captureOutput( \
                r._policyMap['NormalizeAppDefaults'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))

        # we expect that no move was recorded
        self.assertEquals(r._pathTranslations, [])

    def testNormalizeAppDefaults(self):
        r = self.getRecipe()
        path = os.path.join(os.path.sep, 'etc', 'X11', 'app-defaults', 'foo')
        filePath = util.joinPaths(self.destdir, path)
        newPath = os.path.join(self.destdir, 'usr', 'X11R6', 'lib', 'X11', 'app-defaults', 'foo')
        self.touch(filePath)
        r.NormalizeAppDefaults()
        self.captureOutput( \
                r._policyMap['NormalizeAppDefaults'].doProcess, r)
        # prove the policy did move the file
        self.assertFalse(not os.path.exists(newPath))
        self.assertFalse(os.path.exists(filePath))

        # we expect that no move was recorded
        self.assertEquals(r._pathTranslations,
                [('/etc/X11/app-defaults/foo',
                    '/usr/X11R6/lib/X11/app-defaults/foo')])


text:
package com.suelake.habbo.access.sql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import com.blunk.storage.sql.SQLDataQuery;
import com.suelake.habbo.access.UserRegistrationFinder;

public class SQLUserRegistrationFinder extends UserRegistrationFinder implements SQLDataQuery
{
	@Override
	public Vector<?> query(Connection conn) throws SQLException
	{
		// Execute query
		PreparedStatement query = conn.prepareStatement("SELECT users.name FROM users_access JOIN users ON users.id = users_access.userid WHERE ip = ? AND registration = ?;");
		query.setString(1, super.ip);
		query.setBoolean(2, true);
		ResultSet result = query.executeQuery();

		// Parse results
		Vector<String> names = new Vector<String>(1);
		while(result.next())
		{
			names.add(result.getString("name"));
		}
		return names;
	}

	@Override
	public void execute(Connection conn) throws SQLException
	{

	}
}


text:
package io.reactivex.internal.operators.maybe;

import static org.junit.Assert.*;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

import org.junit.Test;

import io.reactivex.*;
import io.reactivex.disposables.Disposables;
import io.reactivex.exceptions.TestException;
import io.reactivex.functions.*;
import io.reactivex.internal.functions.Functions;
import io.reactivex.observers.TestObserver;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.processors.PublishProcessor;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.*;

public class MaybeAmbTest {

    @Test
    public void ambLots() {
        List<Maybe<Integer>> ms = new ArrayList<Maybe<Integer>>();

        for (int i = 0; i < 32; i++) {
            ms.add(Maybe.<Integer>never());
        }

        ms.add(Maybe.just(1));

        Maybe.amb(ms)
        .test()
        .assertResult(1);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void ambFirstDone() {
        Maybe.amb(Arrays.asList(Maybe.just(1), Maybe.just(2)))
        .test()
        .assertResult(1);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void dispose() {
        PublishProcessor<Integer> pp1 = PublishProcessor.create();
        PublishProcessor<Integer> pp2 = PublishProcessor.create();

        TestObserver<Integer> to = Maybe.amb(Arrays.asList(pp1.singleElement(), pp2.singleElement()))
        .test();

        assertTrue(pp1.hasSubscribers());
        assertTrue(pp2.hasSubscribers());

        to.dispose();

        assertFalse(pp1.hasSubscribers());
        assertFalse(pp2.hasSubscribers());
    }

    @SuppressWarnings("unchecked")
    @Test
    public void innerErrorRace() {
        for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
            List<Throwable> errors = TestHelper.trackPluginErrors();
            try {
                final PublishProcessor<Integer> pp0 = PublishProcessor.create();
                final PublishProcessor<Integer> pp1 = PublishProcessor.create();

                final TestObserver<Integer> to = Maybe.amb(Arrays.asList(pp0.singleElement(), pp1.singleElement()))
                .test();

                final TestException ex = new TestException();

                Runnable r1 = new Runnable() {
                    @Override
                    public void run() {
                        pp0.onError(ex);
                    }
                };

                Runnable r2 = new Runnable() {
                    @Override
                    public void run() {
                        pp1.onError(ex);
                    }
                };

                TestHelper.race(r1, r2);

                to.assertFailure(TestException.class);

                if (!errors.isEmpty()) {
                    TestHelper.assertUndeliverable(errors, 0, TestException.class);
                }
            } finally {
                RxJavaPlugins.reset();
            }
        }
    }

    @Test
    public void disposeNoFurtherSignals() {
        @SuppressWarnings("unchecked")
        TestObserver<Integer> to = Maybe.ambArray(new Maybe<Integer>() {
            @Override
            protected void subscribeActual(
                    MaybeObserver<? super Integer> observer) {
                observer.onSubscribe(Disposables.empty());
                observer.onSuccess(1);
                observer.onSuccess(2);
                observer.onComplete();
            }
        }, Maybe.<Integer>never())
        .test();

        to.cancel();

        to.assertResult(1);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void noWinnerSuccessDispose() throws Exception {
        for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
            final AtomicBoolean interrupted = new AtomicBoolean();
            final CountDownLatch cdl = new CountDownLatch(1);

            Maybe.ambArray(
                Maybe.just(1)
                    .subscribeOn(Schedulers.single())
                    .observeOn(Schedulers.computation()),
                Maybe.never()
            )
            .subscribe(new Consumer<Object>() {
                @Override
                public void accept(Object v) throws Exception {
                    interrupted.set(Thread.currentThread().isInterrupted());
                    cdl.countDown();
                }
            });

            assertTrue(cdl.await(500, TimeUnit.SECONDS));
            assertFalse("Interrupted!", interrupted.get());
        }
    }

    @SuppressWarnings("unchecked")
    @Test
    public void noWinnerErrorDispose() throws Exception {
        final TestException ex = new TestException();
        for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
            final AtomicBoolean interrupted = new AtomicBoolean();
            final CountDownLatch cdl = new CountDownLatch(1);

            Maybe.ambArray(
                Maybe.error(ex)
                    .subscribeOn(Schedulers.single())
                    .observeOn(Schedulers.computation()),
                Maybe.never()
            )
            .subscribe(Functions.emptyConsumer(), new Consumer<Throwable>() {
                @Override
                public void accept(Throwable e) throws Exception {
                    interrupted.set(Thread.currentThread().isInterrupted());
                    cdl.countDown();
                }
            });

            assertTrue(cdl.await(500, TimeUnit.SECONDS));
            assertFalse("Interrupted!", interrupted.get());
        }
    }

    @SuppressWarnings("unchecked")
    @Test
    public void noWinnerCompleteDispose() throws Exception {
        for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
            final AtomicBoolean interrupted = new AtomicBoolean();
            final CountDownLatch cdl = new CountDownLatch(1);

            Maybe.ambArray(
                Maybe.empty()
                    .subscribeOn(Schedulers.single())
                    .observeOn(Schedulers.computation()),
                Maybe.never()
            )
            .subscribe(Functions.emptyConsumer(), Functions.emptyConsumer(), new Action() {
                @Override
                public void run() throws Exception {
                    interrupted.set(Thread.currentThread().isInterrupted());
                    cdl.countDown();
                }
            });

            assertTrue(cdl.await(500, TimeUnit.SECONDS));
            assertFalse("Interrupted!", interrupted.get());
        }
    }

    @Test
    public void nullSourceSuccessRace() {
        for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
            List<Throwable> errors = TestHelper.trackPluginErrors();

            try {

                final Subject<Integer> ps = ReplaySubject.create();
                ps.onNext(1);

                @SuppressWarnings("unchecked")
                final Maybe<Integer> source = Maybe.ambArray(ps.singleElement(),
                        Maybe.<Integer>never(), Maybe.<Integer>never(), null);

                Runnable r1 = new Runnable() {
                    @Override
                    public void run() {
                        source.test();
                    }
                };

                Runnable r2 = new Runnable() {
                    @Override
                    public void run() {
                        ps.onComplete();
                    }
                };

                TestHelper.race(r1, r2);

                if (!errors.isEmpty()) {
                    TestHelper.assertError(errors, 0, NullPointerException.class);
                }
            } finally {
                RxJavaPlugins.reset();
            }
        }
    }
}


text:
<?php

namespace	cs\DB;
use			cs\DB;
abstract class _Abstract {
				/**
				 * Is connection established
				 *
				 * @var bool
				 */
	protected	$connected	= false,
				/**
				 * DB type, may be used for constructing requests, accounting particular features of current DB (lowercase name)
				 *
				 * @var bool
				 */
				$db_type	= false,
				/**
				 * Current DB
				 *
				 * @var string
				 */
				$database,
				/**
				 * Current prefix
				 *
				 * @var string
				 */
				$prefix,
				/**
				 * Total time of requests execution
				 *
				 * @var int
				 */
				$time,
				/**
				 * Array for storing of data of the last executed request
				 *
				 * @var array
				 */
				$query		= [
					'time'		=> '',
					'text'		=> ''
				],
				/**
				 * Array for storing data of all executed requests
				 *
				 * @var array
				 */
				$queries	= [
					'num'		=> '',
					'time'		=> [],
					'text'		=> []
				],
				/**
				 * Connection time
				 *
				 * @var int
				 */
				$connecting_time,
				/**
				 * Asynchronous request
				 *
				 * @var bool
				 */
				$async		= false;
	/**
	 * Connecting to the DB
	 *
	 * @param string	$database
	 * @param string	$user
	 * @param string	$password
	 * @param string	$host
	 * @param string	$charset
	 * @param string	$prefix
	 */
	abstract function __construct ($database, $user = '', $password = '', $host = 'localhost', $charset = 'utf8', $prefix = '');
	/**
	 * Query
	 *
	 * SQL request into DB
	 *
	 * @abstract
	 *
	 * @param string|string[]		$query	SQL query string or array, may be a format string in accordance with the first parameter of sprintf() function
	 * @param string|string[]		$params	May be array of arguments for formatting of $query

	 * 										or string - in this case it will be first argument for formatting of $query
	 * @param string				$param	if $params</s> is string - this parameter will be second argument for formatting of $query.
	 * 										If you need more arguments - add them after this one, function will accept them.
	 *
	 * @return bool|object|resource
	 */
	function q ($query, $params = [], $param = null) {
		$query	= str_replace('[prefix]', $this->prefix, $query);
		switch (func_num_args()) {
			default:
				$params	= array_slice(func_get_args(), 1);
			break;
			case 0:
				return false;
			case 1:
			case 2:
				if (!is_array($params)) {
					$params	= [$params];
				}
			break;
		}
		if (!empty($params)) {
			unset($param);
			foreach ($params as &$param) {
				$param	= $this->s($param, false);
			}
			unset($param);
		}
		if (is_array($query) && !empty($query)) {
			$return = true;
			foreach ($query as &$q) {
				if (is_array($q)) {
					if (count($q) > 1) {
						$params	= array_slice($q, 1);
					}
					$q		= $q[0];
				}
				$return = $return && $this->q(empty($params) ? $q : vsprintf($q, $params));
			}
			return $return;
		}
		if(!$query) {
			return true;
		}
		$this->query['time']		= microtime(true);
		$this->query['text']		= empty($params) ? $query : vsprintf($query, $params);
		if (DEBUG) {
			$this->queries['text'][]	= $this->query['text'];
		}
		$result						= $this->q_internal($this->query['text']);
		$this->query['time']		= round(microtime(true) - $this->query['time'], 6);
		$this->time					+= $this->query['time'];
		if (DEBUG) {
			$this->queries['time'][]	= $this->query['time'];
		}
		++$this->queries['num'];
		$db							= DB::instance();
		$db->time					+= $this->query['time'];
		++$db->queries;
		return $result;
	}
	/**
	 * Asynchronous, Query
	 *
	 * Asynchronous SQL request into DB (if is not supported - ordinary request will me executed).
	 * Result of execution can't be obtained, so, use it, for example, for deleting some non-critical data
	 *
	 * @abstract
	 *
	 * @param string|string[]		$query	SQL query string, may be a format string in accordance with the first parameter of sprintf() function
	 * @param string|string[]		$params	May be array of arguments for formatting of $query

	 * 										or string - in this case it will be first argument for formatting of $query
	 * @param string				$param	if $params</s> is string - this parameter will be second argument for formatting of $query.
	 * 										If you need more arguments - add them after this one, function will accept them.
	 *
	 * @return bool|object|resource
	 */
	function aq ($query, $params = [], $param = null) {
		$this->async	= true;
		$result			= call_user_func_array([$this, 'q'], func_get_args());
		$this->async	= false;
		return $result;
	}
	/**
	 * SQL request into DB
	 *
	 * @abstract
	 *
	 * @param string|string[] $query
	 *
	 * @return bool|object|resource
	 */
	abstract protected function q_internal ($query);
	/**
	 * Number
	 *
	 * Getting number of selected rows
	 *
	 * @abstract
	 *
	 * @param object|resource $query_result
	 *
	 * @return bool|int
	 */
	abstract function n ($query_result);
	/**
	 * Fetch
	 *
	 * Fetch a result row as an associative array
	 *
	 * @abstract
	 *
	 * @param object|resource		$query_result
	 * @param bool					$single_column	If true function will return not array with one element, but directly its value
	 * @param bool					$array			If true returns array of associative arrays of all fetched rows
	 * @param bool					$indexed		If false - associative array will be returned
	 *
	 * @return array|bool|string
	 */
	abstract function f ($query_result, $single_column = false, $array = false, $indexed = false);
	/**
	 * Fetch, Array
	 *
	 * Similar to ::f() method, with parameter $array = true
	 *
	 * @param object|resource		$query_result
	 * @param bool					$single_column	If true function will return not array with one element, but directly its value
	 * @param bool					$indexed		If false - associative array will be returned
	 *
	 * @return array|bool|string
	 */
	function fa ($query_result, $single_column = false, $indexed = false) {
		return $this->f($query_result, $single_column, true, $indexed);
	}
	/**
	 * Fetch, Single
	 *
	 * Similar to ::f() method, with parameter $single_column = true
	 *
	 * @param object|resource	$query_result
	 * @param bool				$array			If true returns array of associative arrays of all fetched rows
	 * @param bool				$indexed		If false - associative array will be returned
	 *
	 * @return array|bool
	 */
	function fs ($query_result, $array = false, $indexed = false) {
		return $this->f($query_result, true, $array, $indexed);
	}
	/**
	 * Fetch, Array, Single
	 *
	 * Combination of ::fa() and ::fs() methods
	 *
	 * @param object|resource	$query_result
	 * @param bool				$indexed		If false - associative array will be returned
	 *
	 * @return array|bool
	 */
	function fas ($query_result, $indexed = false) {
		return $this->fa($query_result, true, $indexed);
	}
	/**
	 * Query, Fetch
	 *
	 * Combination of ::q() and ::f() methods
	 *
	 * @param array|string			$query			SQL query string, or you can put all parameters, that ::q() function can accept in form of array
	 * @param bool					$single_column	If true function will return not array with one element, but directly its value
	 * @param bool					$array			If true returns array of associative arrays of all fetched rows
	 * @param bool					$indexed		If false - associative array will be returned
	 *
	 * @return array|bool|string
	 */
	function qf ($query, $single_column = false, $array = false, $indexed = false) {
		list($query, $params)	= $this->q_prepare($query);
		if (!$query) {
			return false;
		}
		return $this->f($this->q($query, $params), $single_column, $array, $indexed);
	}
	/**
	 * Query, Fetch, Array
	 *
	 * Combination of ::q() and ::fa() methods
	 *
	 * @param array|string			$query			SQL query string, or you can put all parameters, that ::q() function can accept in form of array
	 * @param bool					$single_column	If true function will return not array with one element, but directly its value
	 * @param bool					$indexed		If false - associative array will be returned
	 *
	 * @return array|bool|string
	 */
	function qfa ($query, $single_column = false, $indexed = false) {
		list($query, $params)	= $this->q_prepare($query);
		if (!$query) {
			return false;
		}
		return $this->fa($this->q($query, $params), $single_column, $indexed);
	}
	/**
	 * Query, Fetch, Single
	 *
	 * Combination of ::q() and ::fs() methods
	 *
	 * @param array|string	$query			SQL query string, or you can put all parameters, that ::q() function can accept in form of array
	 * @param bool			$array			If true returns array of associative arrays of all fetched rows
	 * @param bool			$indexed		If false - associative array will be returned
	 *
	 * @return array|bool
	 */
	function qfs ($query, $array = false, $indexed = false) {
		list($query, $params)	= $this->q_prepare($query);
		if (!$query) {
			return false;
		}
		return $this->fs($this->q($query, $params), $array, $indexed);
	}
	/**
	 * Query, Fetch, Array, Single
	 *
	 * Combination of ::q() and ::fas() methods
	 *
	 * @param array|string	$query			SQL query string, or you can put all parameters, that ::q() function can accept in form of array
	 * @param bool			$indexed		If false - associative array will be returned
	 *
	 * @return array|bool
	 */
	function qfas ($query, $indexed = false) {
		list($query, $params)	= $this->q_prepare($query);
		if (!$query) {
			return false;
		}
		return $this->fas($this->q($query, $params), $indexed);
	}
	/**
	 * Query preparing for ::q*() methods
	 *
	 * @param array|string|string[]	$query
	 *
	 * @return array						array($query, $params)
	 */
	protected function q_prepare ($query) {
		$params	= [];
		if (is_array($query) && !empty($query)) {
			if (count($query) == 2) {
				$params	= $query[1];
			} elseif (count($query) > 2) {
				$params	= array_slice($query, 1);
			}
			$query	= $query[0];
		}
		return [
			$query,
			$params
		];
	}
	/**
	 * Method for simplified inserting of several rows
	 *
	 * @param string	$query
	 * @param array[]	$params	Array of array of parameters for inserting
	 * @param bool		$join	If true - inserting of several rows will be combined in one query. For this, be sure, that your query has keyword VALUES
	 * 							in uppercase. Part of query after this keyword will be multiplied with coma separator.
	 *
	 * @return bool
	 */
	function insert ($query, $params, $join = true) {
		if (!$query || !$params) {
			return false;
		}
		if ($join) {
			$query		= explode('VALUES', $query, 2);
			$query[1]	= explode(')', $query[1]);
			$query		= [
				$query[0],
				$query[1][0].')',
				$query[1][1]
			];
			if (!isset($query[1]) || !$query[1]) {
				return false;
			}
			$query[1]	.= str_repeat(",$query[1]", count($params) - 1);
			$query		= $query[0].'VALUES'.$query[1].$query[2];
			$params_	= [];
			foreach ($params as $p) {
				$params_	= array_merge($params_, $p);
			}
			unset($params, $p);
			return (bool)$this->q($query, $params_);
		} else {
			$result	= true;
			foreach ($params as $p) {
				$result	= $result && (bool)$this->q($query, $p);
			}
			return $result;
		}
	}
	/**
	 * Id
	 *
	 * Get id of last inserted row
	 *
	 * @abstract
	 *
	 * @return int
	 */
	abstract function id ();
	/**
	 * Affected
	 *
	 * Get number of affected rows during last query
	 *
	 * @abstract
	 *
	 * @return int
	 */
	abstract function affected ();
	/**
	 * Free result memory
	 *
	 * @abstract
	 *
	 * @param object|resource $query_result
	 *
	 * @return bool
	 */
	abstract function free ($query_result);
	/**
	 * Get columns list of table
	 *
	 * @param string $table
	 * @param bool|string $like
	 *
	 * @return array|bool
	 */
	function columns ($table, $like = false) {
		if(!$table) {
			return false;
		}
		if ($like) {
			$like		= $this->s($like);
			$columns	= $this->qfa("SHOW COLUMNS FROM `$table` LIKE $like");
		} else {
			$columns	= $this->qfa("SHOW COLUMNS FROM `$table`");
		}
		foreach ($columns as &$column) {
			$column = $column['Field'];
		}
		return $columns;
	}
	/**
	 * Get tables list
	 *
	 * @param bool $like
	 *
	 * @return array|bool
	 */
	function tables ($like = false) {
		if ($like) {
			$like		= $this->s($like);
			return $this->qfa("SHOW TABLES FROM `$this->database` LIKE $like");
		} else {
			return $this->qfa("SHOW TABLES FROM `$this->database`");
		}
	}
	/**
	 * Safe
	 *
	 * Preparing string for using in SQL query
	 * SQL Injection Protection
	 *
	 * @param string|string[]	$string
	 * @param bool				$single_quotes_around
	 *
	 * @return string|string[]
	 */
	function s ($string, $single_quotes_around = true) {
		if (is_array($string)) {
			foreach ($string as &$s) {
				$s	= $this->s_internal($s, $single_quotes_around);
			}
			return $string;
		}
		return $this->s_internal($string, $single_quotes_around);
	}
	/**
	 * Preparing string for using in SQL query
	 * SQL Injection Protection
	 *
	 * @param string	$string
	 * @param bool		$single_quotes_around
	 *
	 * @return string
	 */
	abstract protected function s_internal ($string, $single_quotes_around);
	/**
	 * Get information about server
	 *
	 * @return string
	 */
	abstract function server ();
	/**
	 * Connection state
	 *
	 * @return bool
	 */
	function connected () {
		return $this->connected;
	}
	/**
	 * Database type (lowercase, for example mysql)
	 *
	 * @return string
	 */
	function db_type () {
		return $this->db_type;
	}
	/**
	 * Database name
	 *
	 * @return string
	 */
	function database () {
		return $this->database;
	}
	/**
	 * Queries array, has 3 properties:

	 *
num - total number of performed queries
	 *
time - array with time of each query execution
	 *
text - array with text text of each query
	 *
	 * @return array
	 */
	function queries () {
		return $this->queries;
	}
	/**
	 * Last query information, has 2 properties:

	 *
time - execution time
	 *
text - query text
	 *
	 * @return array
	 */
	function query () {
		return $this->query;
	}
	/**
	 * Total working time (including connection, queries execution and other delays)
	 *
	 * @return int
	 */
	function time () {
		return $this->time;
	}
	/**
	 * Connecting time
	 *
	 * @return int
	 */
	function connecting_time () {
		return $this->connecting_time;
	}
	/**
	 * Cloning restriction
	 *
	 * @final
	 */
	final function __clone () {}
	/**
	 * Disconnecting from DB
	 */
	abstract function __destruct ();
}


text:
<!DOCTYPE HTML>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>A Slice of Cake</title>
    <meta name="description" content="" />

    <meta name="viewport" content="width=device-width,initial-scale=1" />

    <link rel="stylesheet" href="bower_components/normalize.css/normalize.css" />
    <link rel="stylesheet" href="css/main.css" />

ZuckZuckerberg to give away 99% of sharesve away 99% of shares

2h

US & Canada

ZuckZuckerberg to give away 99% of sharesve away 99% of shares

2h

US & Canada

Zuckerberg to give away 99% of shares

2h

US & Canada

Zuckerberg to give away 99% of shares

2h

US & Canada

Zuckerberg to give away 99% of shares

2h

US & Canada

Zuckerberg to give away 99% of shares

2h

US & Canada

Zuckerberg to give away 99% of shares

2h

US & Canada

Zuckerberg to give away 99% of shares

2h

US & Canada

Baked Alaska

4d ago

Science & Environment

Baked Alaska

4d ago

Science & Environment

Baked Alaska

4d ago

Science & Environment

Baked Alaska

4d ago

Science & Environment

Baked Alaska

4d ago

Science & Environment

Baked Alaska

4d ago

Science & Environment

Baked Alaska

4d ago

Science & Environment

Baked Alaska

4d ago

Science & Environment


text:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections.Generic;

public class LayerMaskNetworkProximityChecker : NetworkProximityChecker
{
    public string[] maskingLayers;

    private int GetMask()
    {
        if (maskingLayers.Length == 0)
            return Physics.AllLayers;
        return LayerMask.GetMask(maskingLayers);
    }

    // function from bitbucket
    public override bool OnRebuildObservers(HashSet<NetworkConnection> observers, bool initial)
    {
        if (forceHidden)
        {
            // ensure player can still see themself
            var uv = GetComponent<NetworkIdentity>();
            if (uv.connectionToClient != null)
            {
                observers.Add(uv.connectionToClient);
            }
            return true;
        }

        // find players within range
        switch (checkMethod)
        {
            case CheckMethod.Physics3D:
                {
                    var hits = Physics.OverlapSphere(transform.position, visRange, GetMask());
                    for (int i = 0; i < hits.Length; i++)
                    {
                        var hit = hits[i];
                        // (if an object has a connectionToClient, it is a player)
                        var uv = hit.GetComponent<NetworkIdentity>();
                        if (uv != null && uv.connectionToClient != null)
                        {
                            observers.Add(uv.connectionToClient);
                        }
                    }
                    return true;
                }

            case CheckMethod.Physics2D:
                {
                    var hits = Physics2D.OverlapCircleAll(transform.position, visRange, GetMask());
                    for (int i = 0; i < hits.Length; i++)
                    {
                        var hit = hits[i];
                        // (if an object has a connectionToClient, it is a player)
                        var uv = hit.GetComponent<NetworkIdentity>();
                        if (uv != null && uv.connectionToClient != null)
                        {
                            observers.Add(uv.connectionToClient);
                        }
                    }
                    return true;
                }
        }
        return false;
    }
}


text:
Add non-determinism to the publish list to avoid order related side effect reliance

# Some backup commands from earlier npm scripts

"test2": "istanbul cover tape \"es5/**/*.test.js\" > test.tap && istanbul report --include=./coverage clover",

"test3": "istanbul cover _mocha -- --reporter ${MOCHA_REPORTER-nyan} --slow 10 --ui tdd --full-trace --require source-map-support/register --recursive lib/**/*_test.js ",

> bundle needs work
"prebundle": "npm run compile && mv es5/** .",
"bundle": "dts-generator --name $npm_package_name --main ${npm_package_name}/index --baseDir . --exclude node_modules/dts-generator/node_modules/typescript/bin/lib.es6.d.ts -out ${npm_package_name}.d.ts *.d.ts",

"pre-commit": [
  "compile"
],

"compile": "./node_modules/.bin/babel-cli -d ./dist ./src",

"dev:osx": "chokidar 'src/**/*.js' 'test/**/*.js' -c 'npm run --silent dev:exec'",
"dev:linux": "supervisor -w 'src/**/*.js','test/**/*.js' -x npm run",

"dev": "npm run --silent dev:exec",
"lint": "jshint ."

"zuul": "./node_modules/.bin/zuul --local --open -- test/**/*.test.js",
"compile": "./node_modules/.bin/babel -d ./dist ./src",
"build": "npm run test && npm run readme && npm run compile",
"buildcli": "babel src -d dist",
"publish": "git push && git push --tags && npm publish",
"validate": "npm ls",
"webpack2": "webpack ./dist/cqjs.js -o cqjs.bundle.js",


text:
FROM rabbitmq:3.5.2

ENV RABBITMQ_PLUGINS "rabbitmq_management rabbitmq_tracing rabbitmq_management_visualiser rabbitmq_shovel rabbitmq_shovel_management"
ENV RABBITMQ_HOME /var/lib/rabbitmq
# This is required so rabbitmqctl knows where to look for the Erlang cookie
ENV HOME $RABBITMQ_HOME

RUN rabbitmq-plugins enable --offline $RABBITMQ_PLUGINS

EXPOSE 15672

COPY bin/rabbitmqadmin /usr/local/bin/


text:
namespace pdal {

  static PluginInfo const s_info {
    "kernels.mykernel",
    "MyKernel",
    "http://link/to/documentation"
  };

  CREATE_SHARED_PLUGIN(1, 0, MyKernel, Kernel, s_info);
  std::string MyKernel::getName() const { return s_info.name; }

  MyKernel::MyKernel() : Kernel()
  {}

  void MyKernel::addSwitches(ProgramArgs& args)
  {
      args.add("input,i", "Input filename", m_input_file).setPositional();
      args.add("output,o", "Output filename", m_output_file).setPositional();
  }

  int MyKernel::execute()
  {
    PointTable table;
    StageFactory f;

    Stage * reader = f.createStage("readers.las");
    Options readerOptions;
    readerOptions.add("filename", m_input_file);
    reader->setOptions(readerOptions);

    Stage * filter = f.createStage("filters.decimation");
    Options filterOptions;
    filterOptions.add("step", 10);
    filter->setOptions(filterOptions);
    filter->setInput(*reader);

    Stage * writer = f.createStage("writers.text");
    Options writerOptions;
    writerOptions.add("filename", m_output_file);
    writer->setOptions(writerOptions);
    writer->setInput(*filter);
    writer->prepare(table);
    writer->execute(table);

    return 0;
  }

} // namespace pdal


text:
package decoder

import (
	"reflect"
	"sync"
	"unsafe"

	"github.com/goccy/go-json/internal/errors"
	"github.com/goccy/go-json/internal/runtime"
)

type sliceDecoder struct {
	elemType          *runtime.Type
	isElemPointerType bool
	valueDecoder      Decoder
	size              uintptr
	arrayPool         sync.Pool
	structName        string
	fieldName         string
}

// If use reflect.SliceHeader, data type is uintptr.
// In this case, Go compiler cannot trace reference created by newArray().
// So, define using unsafe.Pointer as data type
type sliceHeader struct {
	data unsafe.Pointer
	len  int
	cap  int
}

const (
	defaultSliceCapacity = 2
)

func newSliceDecoder(dec Decoder, elemType *runtime.Type, size uintptr, structName, fieldName string) *sliceDecoder {
	return &sliceDecoder{
		valueDecoder:      dec,
		elemType:          elemType,
		isElemPointerType: elemType.Kind() == reflect.Ptr || elemType.Kind() == reflect.Map,
		size:              size,
		arrayPool: sync.Pool{
			New: func() interface{} {
				return &sliceHeader{
					data: newArray(elemType, defaultSliceCapacity),
					len:  0,
					cap:  defaultSliceCapacity,
				}
			},
		},
		structName: structName,
		fieldName:  fieldName,
	}
}

func (d *sliceDecoder) newSlice(src *sliceHeader) *sliceHeader {
	slice := d.arrayPool.Get().(*sliceHeader)
	if src.len > 0 {
		// copy original elem
		if slice.cap < src.cap {
			data := newArray(d.elemType, src.cap)
			slice = &sliceHeader{data: data, len: src.len, cap: src.cap}
		} else {
			slice.len = src.len
		}
		copySlice(d.elemType, *slice, *src)
	} else {
		slice.len = 0
	}
	return slice
}

func (d *sliceDecoder) releaseSlice(p *sliceHeader) {
	d.arrayPool.Put(p)
}

//go:linkname copySlice reflect.typedslicecopy
func copySlice(elemType *runtime.Type, dst, src sliceHeader) int

//go:linkname newArray reflect.unsafe_NewArray
func newArray(*runtime.Type, int) unsafe.Pointer

//go:linkname typedmemmove reflect.typedmemmove
func typedmemmove(t *runtime.Type, dst, src unsafe.Pointer)

func (d *sliceDecoder) errNumber(offset int64) *errors.UnmarshalTypeError {
	return &errors.UnmarshalTypeError{
		Value:  "number",
		Type:   reflect.SliceOf(runtime.RType2Type(d.elemType)),
		Struct: d.structName,
		Field:  d.fieldName,
		Offset: offset,
	}
}

func (d *sliceDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error {
	depth++
	if depth > maxDecodeNestingDepth {
		return errors.ErrExceededMaxDepth(s.char(), s.cursor)
	}

	for {
		switch s.char() {
		case ' ', '\n', '\t', '\r':
			s.cursor++
			continue
		case 'n':
			if err := nullBytes(s); err != nil {
				return err
			}
			*(*unsafe.Pointer)(p) = nil
			return nil
		case '[':
			s.cursor++
			if s.skipWhiteSpace() == ']' {
				dst := (*sliceHeader)(p)
				if dst.data == nil {
					dst.data = newArray(d.elemType, 0)
				} else {
					dst.len = 0
				}
				s.cursor++
				return nil
			}
			idx := 0
			slice := d.newSlice((*sliceHeader)(p))
			srcLen := slice.len
			capacity := slice.cap
			data := slice.data
			for {
				if capacity <= idx {
					src := sliceHeader{data: data, len: idx, cap: capacity}
					capacity *= 2
					data = newArray(d.elemType, capacity)
					dst := sliceHeader{data: data, len: idx, cap: capacity}
					copySlice(d.elemType, dst, src)
				}
				ep := unsafe.Pointer(uintptr(data) + uintptr(idx)*d.size)

				// if srcLen is greater than idx, keep the original reference
				if srcLen <= idx {
					if d.isElemPointerType {
						**(**unsafe.Pointer)(unsafe.Pointer(&ep)) = nil // initialize elem pointer
					} else {
						// assign new element to the slice
						typedmemmove(d.elemType, ep, unsafe_New(d.elemType))
					}
				}

				if err := d.valueDecoder.DecodeStream(s, depth, ep); err != nil {
					return err
				}
				s.skipWhiteSpace()
			RETRY:
				switch s.char() {
				case ']':
					slice.cap = capacity
					slice.len = idx + 1
					slice.data = data
					dst := (*sliceHeader)(p)
					dst.len = idx + 1
					if dst.len > dst.cap {
						dst.data = newArray(d.elemType, dst.len)
						dst.cap = dst.len
					}
					copySlice(d.elemType, *dst, *slice)
					d.releaseSlice(slice)
					s.cursor++
					return nil
				case ',':
					idx++
				case nul:
					if s.read() {
						goto RETRY
					}
					slice.cap = capacity
					slice.data = data
					d.releaseSlice(slice)
					goto ERROR
				default:
					slice.cap = capacity
					slice.data = data
					d.releaseSlice(slice)
					goto ERROR
				}
				s.cursor++
			}
		case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			return d.errNumber(s.totalOffset())
		case nul:
			if s.read() {
				continue
			}
			goto ERROR
		default:
			goto ERROR
		}
	}
ERROR:
	return errors.ErrUnexpectedEndOfJSON("slice", s.totalOffset())
}

func (d *sliceDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
	buf := ctx.Buf
	depth++
	if depth > maxDecodeNestingDepth {
		return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor)
	}

	for {
		switch buf[cursor] {
		case ' ', '\n', '\t', '\r':
			cursor++
			continue
		case 'n':
			if err := validateNull(buf, cursor); err != nil {
				return 0, err
			}
			cursor += 4
			*(*unsafe.Pointer)(p) = nil
			return cursor, nil
		case '[':
			cursor++
			cursor = skipWhiteSpace(buf, cursor)
			if buf[cursor] == ']' {
				dst := (*sliceHeader)(p)
				if dst.data == nil {
					dst.data = newArray(d.elemType, 0)
				} else {
					dst.len = 0
				}
				cursor++
				return cursor, nil
			}
			idx := 0
			slice := d.newSlice((*sliceHeader)(p))
			srcLen := slice.len
			capacity := slice.cap
			data := slice.data
			for {
				if capacity <= idx {
					src := sliceHeader{data: data, len: idx, cap: capacity}
					capacity *= 2
					data = newArray(d.elemType, capacity)
					dst := sliceHeader{data: data, len: idx, cap: capacity}
					copySlice(d.elemType, dst, src)
				}
				ep := unsafe.Pointer(uintptr(data) + uintptr(idx)*d.size)
				// if srcLen is greater than idx, keep the original reference
				if srcLen <= idx {
					if d.isElemPointerType {
						**(**unsafe.Pointer)(unsafe.Pointer(&ep)) = nil // initialize elem pointer
					} else {
						// assign new element to the slice
						typedmemmove(d.elemType, ep, unsafe_New(d.elemType))
					}
				}
				c, err := d.valueDecoder.Decode(ctx, cursor, depth, ep)
				if err != nil {
					return 0, err
				}
				cursor = c
				cursor = skipWhiteSpace(buf, cursor)
				switch buf[cursor] {
				case ']':
					slice.cap = capacity
					slice.len = idx + 1
					slice.data = data
					dst := (*sliceHeader)(p)
					dst.len = idx + 1
					if dst.len > dst.cap {
						dst.data = newArray(d.elemType, dst.len)
						dst.cap = dst.len
					}
					copySlice(d.elemType, *dst, *slice)
					d.releaseSlice(slice)
					cursor++
					return cursor, nil
				case ',':
					idx++
				default:
					slice.cap = capacity
					slice.data = data
					d.releaseSlice(slice)
					return 0, errors.ErrInvalidCharacter(buf[cursor], "slice", cursor)
				}
				cursor++
			}
		case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			return 0, d.errNumber(cursor)
		default:
			return 0, errors.ErrUnexpectedEndOfJSON("slice", cursor)
		}
	}
}


text:
package gov.sandia.cognition.statistics.distribution;

import gov.sandia.cognition.math.UnivariateStatisticsUtil;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.statistics.SmoothUnivariateDistributionTestHarness;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Kevin R. Dixon
 */
public class UnivariateGaussianTest
    extends SmoothUnivariateDistributionTestHarness
{

    /**
     * Constructor
     * @param testName Name
     */
    public UnivariateGaussianTest(
        String testName )
    {
        super( testName );
    }

    @Override
    public UnivariateGaussian createInstance()
    {
        double mean = RANDOM.nextGaussian();
        double variance = RANDOM.nextDouble();
        return new UnivariateGaussian( mean, variance );
    }

    @Override
    public void testDistributionGetVariance()
    {
        int temp = NUM_SAMPLES;
        NUM_SAMPLES = 10000;
        super.testDistributionGetVariance();
        NUM_SAMPLES = temp;
    }

    /**
     * Error function
     */
    public void testErrorFunction()
    {
        System.out.println( "ErrorFunction.evaluate" );
        double tol = 1e-6;

        // These values were computed from octave's erf() function
        assertEquals( 0.0, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( new Double(0.0) ), tol );
        assertEquals( 1.128342e-2, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( 0.01 ), tol );
        assertEquals( -1.128342e-2, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( -0.01 ), tol );
        assertEquals( 1.124629e-1, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( 0.1 ), tol );
        assertEquals( 2.227026e-1, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( 0.2 ), tol );
        assertEquals( 8.427008e-1, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( 1.0 ), tol );
        assertEquals( -8.427008e-1, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( -1.0 ), tol );
        assertEquals( 9.999779e-1, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( 3.0 ), tol );
        assertEquals( 1.0, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( 3.9 ), tol );
        assertEquals( -1.0, UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( -3.9 ), tol );
    }

    /**
     * ErrorFunction.Inverse.evaluate
     */
    public void testErrorFunctionInverse()
    {
        System.out.println( "ErrorFunction.Inverse.evaluate" );

        // These values were computes from octave's erfinv() function
        assertEquals( 0.0, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( new Double(0.0) ), TOLERANCE  );
        assertEquals( 0.0888559905, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 0.1 ), TOLERANCE  );
        assertEquals( 0.0888559905, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 0.1 ), TOLERANCE  );
        assertEquals( -0.0888559905, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( -0.1 ), TOLERANCE  );
        assertEquals( 0.1791434546, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 0.2 ), TOLERANCE  );
        assertEquals( -0.1791434546, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( -0.2 ), TOLERANCE  );
        assertEquals( 0.2724627147, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 0.3 ), TOLERANCE  );
        assertEquals( 0.4769362762, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 0.5 ), TOLERANCE  );
        assertEquals( 0.7328690780, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 0.7 ), TOLERANCE  );
        assertEquals( -0.7328690780, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( -0.7 ), TOLERANCE  );
        assertEquals( -1.1630871537, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( -0.9 ), TOLERANCE  );
        assertEquals( 1.1630871537, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 0.9 ), TOLERANCE  );
        assertEquals( 2.3267537655, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 0.999 ), TOLERANCE  );
        assertEquals( -2.3267537655, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( -0.999 ), TOLERANCE  );
        assertEquals( 3.1234132743, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 0.99999 ), TOLERANCE  );
        assertEquals( -3.1234132743, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( -0.99999 ), TOLERANCE  );

        assertEquals( Double.POSITIVE_INFINITY, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 1.0 ), TOLERANCE  );
        assertEquals( Double.POSITIVE_INFINITY, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( 10.0 ), TOLERANCE  );
        assertEquals( Double.NEGATIVE_INFINITY, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( -1.0 ), TOLERANCE  );
        assertEquals( Double.NEGATIVE_INFINITY, UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( -10.0 ), TOLERANCE  );

        for (int i = 0; i < 100; i++)
        {
            double y = RANDOM.nextDouble() * 2 - 1;
            double x = UnivariateGaussian.ErrorFunction.Inverse.INSTANCE.evaluate( y );
            double yhat = UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( x );
            assertEquals( y, yhat, TOLERANCE  );
        }
    }

    /**
     * CDF.Inverse
     */
    public void testCDFInverse()
    {
        System.out.println( "CDF.Inverse" );

        UnivariateGaussian instance = this.createInstance();
        UnivariateGaussian.CDF.Inverse cdfi =
            new UnivariateGaussian.CDF.Inverse( instance );
        assertNotSame( instance, cdfi );
        assertEquals( instance.convertToVector(), cdfi.convertToVector() );
        UnivariateGaussian clone = cdfi.clone();
        assertNotNull( clone );
        assertNotSame( cdfi, clone );
        assertEquals( cdfi.convertToVector(), clone.convertToVector() );

        UnivariateGaussian.CDF cdf = new UnivariateGaussian.CDF( cdfi );
        assertNotNull( cdf );
        assertNotSame( cdfi, cdf );
        assertEquals( cdfi.convertToVector(), cdf.convertToVector() );

        double p = RANDOM.nextDouble();
        double x = cdfi.evaluate(p);
        double phat = cdf.evaluate(x);
        assertEquals( p, phat, TOLERANCE );

        assertEquals( Double.NEGATIVE_INFINITY, cdfi.evaluate(0.0) );
        assertEquals( Double.POSITIVE_INFINITY, cdfi.evaluate(1.0) );

        assertEquals( Double.NEGATIVE_INFINITY, cdfi.evaluate(-1.0) );
        assertEquals( Double.POSITIVE_INFINITY, cdfi.evaluate(2.0) );
    }

    /**
     * Test of getMean method, of class gov.sandia.cognition.learning.util.statistics.UnivariateGaussian.
     */
    public void testGetMean()
    {
        System.out.println( "getMean" );

        double mean = RANDOM.nextGaussian();
        double variance = RANDOM.nextDouble();
        UnivariateGaussian.CDF instance = new UnivariateGaussian.CDF( mean, variance );
        assertEquals( mean, instance.getMean() );
    }

    /**
     * Test of setMean method, of class gov.sandia.cognition.learning.util.statistics.UnivariateGaussian.
     */
    public void testSetMean()
    {
        System.out.println( "setMean" );

        double mean = RANDOM.nextGaussian();
        double variance = RANDOM.nextDouble();
        UnivariateGaussian.PDF instance = new UnivariateGaussian.PDF( mean, variance );
        assertEquals( mean, instance.getMean() );

        double m2 = mean + RANDOM.nextGaussian();
        instance.setMean( m2 );
        assertEquals( m2, instance.getMean() );
    }

    /**
     * Test of getVariance method, of class gov.sandia.cognition.learning.util.statistics.UnivariateGaussian.
     */
    public void testGetVariance()
    {
        System.out.println( "getVariance" );

        double mean = RANDOM.nextGaussian();
        double variance = RANDOM.nextDouble();
        UnivariateGaussian instance = new UnivariateGaussian( mean, variance );
        assertEquals( variance, instance.getVariance() );
    }

    /**
     * Test of setVariance method, of class gov.sandia.cognition.learning.util.statistics.UnivariateGaussian.
     */
    public void testSetVariance()
    {
        System.out.println( "setVariance" );

        double mean = RANDOM.nextGaussian();
        double variance = RANDOM.nextDouble();
        UnivariateGaussian.PDF instance = new UnivariateGaussian.PDF( mean, variance );
        assertEquals( variance, instance.getVariance() );

        double v2 = variance + RANDOM.nextDouble();
        instance.setVariance( v2 );
        assertEquals( v2, instance.getVariance() );

        try
        {
            instance.setVariance( 0.0 );
            fail( "Variance must be > 0.0" );
        }
        catch (Exception e)
        {
            System.out.println( "Good: " + e );
        }

        try
        {
            instance.setVariance( -RANDOM.nextDouble() );
            fail( "Variance must be > 0.0" );
        }
        catch (Exception e)
        {
            System.out.println( "Good: " + e );
        }
    }

    @Override
    public void testKnownConvertToVector()
    {
        System.out.println( "CDF.convertToVector" );

        UnivariateGaussian instance = this.createInstance();
        Vector v = instance.convertToVector();
        assertEquals( 2, v.getDimensionality() );
        assertEquals( instance.getMean(), v.getElement( 0 ) );
        assertEquals( instance.getVariance(), v.getElement( 1 ) );

    }

    @Override
    public void testPDFKnownValues()
    {
        System.out.println( "PDF.known values" );

        for (int i = 0; i < NUM_SAMPLES; i++)
        {
            UnivariateGaussian.PDF pdf = this.createInstance().getProbabilityFunction();
            double mean = pdf.getMean();
            double variance = pdf.getVariance();

            double x = RANDOM.nextGaussian();
            double p = pdf.evaluate( x );

            Double P = pdf.evaluate( new Double( x ) );
            assertEquals( p, P.doubleValue() );

            double delta = x - mean;
            double top = Math.exp( (delta * delta) / (-2.0 * variance) );
            double bottom = Math.sqrt( 2.0 * Math.PI * variance );
            double phat = top / bottom;
            assertEquals( p, phat, TOLERANCE );

        }
    }

    @Override
    public void testCDFKnownValues()
    {
        UnivariateGaussian.CDF cdf = this.createInstance().getCDF();
        double m1 = cdf.getMean();
        assertEquals( 0.5, cdf.evaluate( m1 ), TOLERANCE );
        assertEquals( 0.0, UnivariateGaussian.CDF.evaluate( Double.NEGATIVE_INFINITY, 0, 1 ), TOLERANCE );
        assertEquals( 1.0, UnivariateGaussian.CDF.evaluate( Double.POSITIVE_INFINITY, 0, 1 ), TOLERANCE );

        for (int i = 0; i < 100; i++)
        {
            double x = RANDOM.nextDouble() * 10 - 5;
            double expected = 0.5 * (1.0 + UnivariateGaussian.ErrorFunction.INSTANCE.evaluate( x / Math.sqrt( 2 ) ));
            assertEquals( expected, UnivariateGaussian.CDF.evaluate( x, 0, 1 ), TOLERANCE );
        }
    }

    /**
     * Learner
     */
    public void testLearner()
    {
        System.out.println( "Learner" );

        UnivariateGaussian.MaximumLikelihoodEstimator learner =
            new UnivariateGaussian.MaximumLikelihoodEstimator();
        this.distributionEstimatorTest(learner);
    }

    /**
     * Weighted learner
     */
    public void testWeightedLearner()
    {
        System.out.println( "Weighted Learner" );

        UnivariateGaussian.WeightedMaximumLikelihoodEstimator learner =
            new UnivariateGaussian.WeightedMaximumLikelihoodEstimator();
        this.weightedDistributionEstimatorTest(learner);
    }

    @Override
    public void testPDFConstructors()
    {
        System.out.println( "PDF Constructor" );
        UnivariateGaussian.PDF g = new UnivariateGaussian.PDF();
        assertEquals( UnivariateGaussian.DEFAULT_MEAN, g.getMean() );
        assertEquals( UnivariateGaussian.DEFAULT_VARIANCE, g.getVariance() );

        double mean = RANDOM.nextGaussian();
        double variance = Math.abs(RANDOM.nextGaussian());
        g = new UnivariateGaussian.PDF( mean, variance );

        UnivariateGaussian.PDF g2 = new UnivariateGaussian.PDF( g );
        assertEquals( g.getMean(), g2.getMean() );
        assertEquals( g.getVariance(), g2.getVariance() );
    }

    @Override
    public void testDistributionConstructors()
    {
        System.out.println( "Constructor" );
        UnivariateGaussian g = new UnivariateGaussian();
        assertEquals( UnivariateGaussian.DEFAULT_MEAN, g.getMean() );
        assertEquals( UnivariateGaussian.DEFAULT_VARIANCE, g.getVariance() );

        double mean = RANDOM.nextGaussian();
        double variance = Math.abs(RANDOM.nextGaussian());
        g = new UnivariateGaussian( mean, variance );

        UnivariateGaussian g2 = new UnivariateGaussian( g );
        assertEquals( g.getMean(), g2.getMean() );
        assertEquals( g.getVariance(), g2.getVariance() );

    }

    @Override
    public void testCDFConstructors()
    {
        System.out.println( "CDF Constructor" );

        UnivariateGaussian.CDF g = new UnivariateGaussian.CDF();
        assertEquals( UnivariateGaussian.DEFAULT_MEAN, g.getMean() );
        assertEquals( UnivariateGaussian.DEFAULT_VARIANCE, g.getVariance() );

        double mean = RANDOM.nextGaussian();
        double variance = Math.abs(RANDOM.nextGaussian());
        g = new UnivariateGaussian.CDF( mean, variance );

        UnivariateGaussian.CDF g2 = new UnivariateGaussian.CDF( g );
        assertEquals( g.getMean(), g2.getMean() );
        assertEquals( g.getVariance(), g2.getVariance() );
    }

    /**
     * times
     */
    public void testTimes()
    {
        System.out.println( "times" );

        UnivariateGaussian g1 = this.createInstance();
        UnivariateGaussian g2 = this.createInstance();
        UnivariateGaussian result = g1.times( g2 );

        System.out.println( "G1: " + g1 );
        System.out.println( "G2: " + g2 );
        System.out.println( "Result: " + result );
        double vhat = 1.0 / (1.0/g1.getVariance() + 1.0/g2.getVariance());
        double meanHat = (vhat/g1.getVariance())*g1.getMean() + (vhat/g2.getVariance())*g2.getMean();
        assertEquals( meanHat, result.getMean(), TOLERANCE );
        assertEquals( vhat, result.getVariance(), TOLERANCE );

    }

    /**
     * convolve
     */
    public void testConvolve()
    {
        System.out.println( "convolve" );

        UnivariateGaussian g1 = this.createInstance();
        UnivariateGaussian g2 = this.createInstance();
        UnivariateGaussian result = g1.convolve( g2 );

        System.out.println( "G1: " + g1 );
        System.out.println( "G2: " + g2 );
        System.out.println( "Result: " + result );
        double vhat = g1.getVariance() + g2.getVariance();
        double meanHat = g1.getMean() + g2.getMean();
        assertEquals( meanHat, result.getMean(), TOLERANCE );
        assertEquals( vhat, result.getVariance(), TOLERANCE );

    }

    /**
     * tests the incremental estimator
     */
    public void testIncrementalEstimator()
    {
        System.out.println( "Incremental Estimator" );

        UnivariateGaussian.IncrementalEstimator estimator =
            new UnivariateGaussian.IncrementalEstimator();

        UnivariateGaussian target = new UnivariateGaussian(
            RANDOM.nextGaussian(), RANDOM.nextDouble() );
        ArrayList<Double> samples = target.sample(RANDOM,NUM_SAMPLES);

        double mean = UnivariateStatisticsUtil.computeMean(samples);
        UnivariateGaussian.SufficientStatistic ss = estimator.learn(samples);
        assertEquals( samples.size(), ss.getCount() );
        assertEquals( mean, ss.getMean(), TOLERANCE );
        assertEquals( UnivariateStatisticsUtil.computeVariance(samples, mean), ss.getVariance(), TOLERANCE );
        UnivariateGaussian result = ss.create();

        UnivariateGaussian batch =
            UnivariateGaussian.MaximumLikelihoodEstimator.learn(samples, 0.0);

        System.out.println( "Target: " + target );
        System.out.println( "Result: " + result );
        System.out.println( "Batch : " + batch );

        assertEquals( batch.getMean(), result.getMean(), TOLERANCE );
        assertEquals( batch.getVariance(), result.getVariance(), TOLERANCE );

        UnivariateGaussian.SufficientStatistic clone = ss.clone();
        assertEquals( ss.getCount(), clone.getCount() );
        assertEquals( ss.getMean(), clone.getMean() );
        assertEquals( ss.getVariance(), clone.getVariance() );

        // This example is from the Wikipedia page: http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
        // First demonstrate that for these simple values the mean is 10 and variance is 30.
        double epsilon = 1E-10;
        estimator.setDefaultVariance(epsilon);
        Collection<Double> xd = Arrays.asList(4.0, 7.0, 13.0, 16.0);
        ss = estimator.createInitialLearnedObject();
        ss = estimator.learn(xd);
        result = ss.create();
        assertEquals(10.0, result.getMean(), epsilon);
        assertEquals(30.0, result.getVariance(), epsilon);

        // Now shift the mean by adding 10^9 and check that the variance remains
        // 30.
        xd = Arrays.asList(1.0e9 + 4.0, 1e9 + 7, 1e9 + 13, 1e9 + 16);
        ss = estimator.createInitialLearnedObject();
        ss = estimator.learn(xd);
        result = ss.create();
        assertEquals(1e9 + 10.0, result.getMean(), epsilon);
        assertEquals(30.0, result.getVariance(), epsilon);
    }

    /**
     * Tests adding together sufficient statistics
     */
    public void testSufficientStatisticsPlus()
    {
        // This example is from the Wikipedia page: http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
        // First demonstrate that for these simple values the mean is 10 and variance is 30.
        double epsilon = 1E-10;
        List<Double> xd = Arrays.asList(4.0, 7.0, 13.0, 16.0);
        UnivariateGaussian.SufficientStatistic instance =
            new UnivariateGaussian.SufficientStatistic();
        int count = 1;
        int i = 0;
        while (i < xd.size())
        {
            UnivariateGaussian.SufficientStatistic other =
                new UnivariateGaussian.SufficientStatistic();
            for (int j = 0; j < count && i < xd.size(); j++)
            {
                other.update(xd.get(i));
                i++;
            }
            instance.plusEquals(other);
            count++;
        }
        assertEquals(10.0, instance.getMean(), epsilon);
        assertEquals(30.0, instance.getVariance(), epsilon);

        // Now shift the mean by adding 10^9 and check that the variance remains
        // 30.
        xd = Arrays.asList(1.0e9 + 4.0, 1e9 + 7, 1e9 + 13, 1e9 + 16);
        instance.clear();
        count = 1;
        i = 0;
        while (i < xd.size())
        {
            UnivariateGaussian.SufficientStatistic other =
                new UnivariateGaussian.SufficientStatistic();
            for (int j = 0; j < count && i < xd.size(); j++)
            {
                other.update(xd.get(i));
                i++;
            }
            instance.plusEquals(other);
            count++;
        }
        assertEquals(count, instance.getCount());
        assertEquals(1e9 + 10.0, instance.getMean(), epsilon);
        assertEquals(30.0, instance.getVariance(), epsilon);
        assertEquals(22.5, instance.getSampleVariance(), epsilon);

        UnivariateGaussian target = new UnivariateGaussian(
            RANDOM.nextGaussian(), RANDOM.nextDouble() );
        ArrayList<Double> samples = target.sample(RANDOM,NUM_SAMPLES);
        instance.clear();
        count = 1;
        i = 0;
        while (i < samples.size())
        {
            UnivariateGaussian.SufficientStatistic other =
                new UnivariateGaussian.SufficientStatistic();
            for (int j = 0; j < count && i < samples.size(); j++)
            {
                other.update(samples.get(i));
                i++;
            }
            instance.plusEquals(other);
            count++;
        }

        double mean = UnivariateStatisticsUtil.computeMean(samples);
        double variance = UnivariateStatisticsUtil.computeVariance(samples, mean);
        double sampleVariance = variance * (i - 1) / i;
        assertEquals(i, instance.getCount());
        assertEquals(mean, instance.getMean(), epsilon);
        assertEquals(variance, instance.getVariance(), epsilon);
        assertEquals(sampleVariance, instance.getSampleVariance(), epsilon);
    }

    public void testSufficientStatisticsRemove()
    {
        // This example is from the Wikipedia page: http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
        // First demonstrate that for these simple values the mean is 10 and variance is 30.
        double epsilon = 1E-10;
        List<Double> xd = Arrays.asList(4.0, 7.0, 13.0, 16.0);

        for (int i = 0; i < xd.size(); i++)
        {
            UnivariateGaussian.SufficientStatistic instance =
                new UnivariateGaussian.SufficientStatistic();
            instance.update(xd);
            assertEquals(10.0, instance.getMean(), epsilon);
            assertEquals(30.0, instance.getVariance(), epsilon);
            instance.remove(xd.get(i));

            List<Double> samples = new LinkedList<Double>(xd);
            samples.remove(i);
            double mean = UnivariateStatisticsUtil.computeMean(samples);
            double variance = UnivariateStatisticsUtil.computeVariance(samples, mean);

            assertEquals(mean, instance.getMean(), epsilon);
            assertEquals(variance, instance.getVariance(), epsilon);

            instance.update(xd.get(i));
            for (double value : xd)
            {
                instance.remove(value);
            }
            assertEquals(0, instance.getCount());
            assertEquals(0.0, instance.getMean(), epsilon);
            assertEquals(0.0, instance.getVariance(), epsilon);
            assertEquals(0.0, instance.getSampleVariance(), epsilon);
        }

        // Now shift the mean by adding 10^9 and check that the variance remains
        // 30.
        xd = Arrays.asList(1.0e9 + 4.0, 1e9 + 7, 1e9 + 13, 1e9 + 16);
        for (int i = 0; i < xd.size(); i++)
        {
            UnivariateGaussian.SufficientStatistic instance =
                new UnivariateGaussian.SufficientStatistic();
            instance.update(xd);
            assertEquals(1e9 + 10.0, instance.getMean(), epsilon);
            assertEquals(30.0, instance.getVariance(), epsilon);
            assertEquals(22.5, instance.getSampleVariance(), epsilon);
            instance.remove(xd.get(i));

            List<Double> samples = new LinkedList<Double>(xd);
            samples.remove(i);
            int count = xd.size() - 1;
            double mean = UnivariateStatisticsUtil.computeMean(samples);
            double variance = UnivariateStatisticsUtil.computeVariance(samples, mean);
            double sampleVariance = variance * (count - 1) / count;

            assertEquals(count, instance.getCount());
            assertEquals(mean, instance.getMean(), epsilon);
            assertEquals(variance, instance.getVariance(), epsilon);
            assertEquals(sampleVariance, instance.getSampleVariance(), epsilon);
        }
    }

}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: jesus
 * Date: 5/6/13
 * Time: 5:35 PM
 * To change this template use File | Settings | File Templates.
 */
namespace Album\Model;

class Album
{
    public $id;
    public $artist;
    public $title;

    public function exchangeArray($data)
    {
        $this->id     = (isset($data['id']))     ? $data['id']     : null;
        $this->artist = (isset($data['artist'])) ? $data['artist'] : null;
        $this->title  = (isset($data['title']))  ? $data['title']  : null;
    }
}


text:
/*************************************************************************
**									**
**  Description							 	**
**									**
**  This module deals with I/O of ASCII files in GAMMA.  Although GAMMA	**
**  data types often come with the ability to read themselves from set	**
**  parameter files (ASCII files in GAMMA parameter format), often one	**
**  needs to input a set of values (int, double, string, ....) that	**
**  control program function but have nothing to do with GAMMA objects.	**
**  These functions simplify that process by allowing flexible parsing	**
**  of ASCII files.							**
**								 	**
*************************************************************************/

#ifndef   Gamascii_h_			// Is file already included?
#  define Gamascii_h_ 1			// If no, then remember it
#  if defined(GAMPRAGMA)		// Using the GNU compiler?
#    pragma interface		    	// This is the interface
#  endif

#include <GamGen.h>			// Know MSVCDLL (__declspec)
#include <string>			// Know about libstdc++ strings
#include <Matrix/row_vector.h>		// Know about row_vectors

// __________________________________________________________________________________
// i                        ASCII File I/O Error Functions
// __________________________________________________________________________________

void ASCIIerr(int eidx, int noret=0);

        // Input                eidx    : Flag for error type
        //                      noret   : Flag for return (0=return)
        // Output               none    : Error message

void ASCIIdie(int eidx);

        // Input                eidx    : Flag for error type
        //                      noret   : Flag for return (0=return)
        // Output               none    : Error message

void ASCIIerr(int eidx, const std::string& pname, int noret=0);

        // Input                eidx    : Flag for error type
        //                      pname   : string included in message
        //                      noret   : Flag for return (0=return)
        // Output               none    : Error message

// __________________________________________________________________________________
// A                        ASCII File Reading & Parsing
// __________________________________________________________________________________

// ----------------------------------------------------------------------------------
//                     I/O To Obtain strings From An ASCII File
// ----------------------------------------------------------------------------------

MSVCDLL std::string* Getstrings(const std::string& filename, int& N);

        // Input        filename: ASCII input file name
        //		        N	    : Number of strings
        // Return       Svect   : A string vector is filled with names
        //                        found in the file "filename"
        //			              Value of N is set to # strings found
        // Note                 : Assumes file contains 1 name per
        //                        line

// ----------------------------------------------------------------------------------
//                    I/O To Obtain Doubles From An ASCII File
// ----------------------------------------------------------------------------------

MSVCDLL double* GetDoubles(const std::string& filename, int& N);

        // Input        filename: ASCII input file name
        //		        N      	: Number of doubles
        // Return       Dvect   : A double vector is filled with values
        //                        found in the file "filename"
        //			              Value of N is set to # doubles found
        // Note                 : Assumes file contains 1 value per line

MSVCDLL row_vector GetDoubles(const std::string& filename);

        // Input        filename: ASCII input file name
        // Return       data    : A vector is filled with values
        //                        found in the file "filename"

MSVCDLL void vxread(const std::string& filename, row_vector& vx);

	// Input           filename : ASCII input file name
	//                 vx       : A row vector
	// Return          none     : vx is filled with data in
	//                            file "filename"

// __________________________________________________________________________________
// G                       ASCII File Auxiliary Functions
// __________________________________________________________________________________

MSVCDLL void ASCIItell(const std::string& filename, int verbose=0);

	// Input           filename : ASCII input file name
	//		   vebose   : Flag how much info to output
	// Return          none     : The ASCII file is probed to determine
	//                            what type of information it contains

MSVCDLL int LineCount(const std::string& filename);

        // Input           filename	: ASCII input file name
        // Return          int		: The nubmer of lines in the ASCII file
		//                            named filename

#endif                                                             // Gascii.h