text:
"""
Implements a file system specific data adapter
"""

import os
import shutil

from datafinder.persistence.adapters.filesystem import util
from datafinder.persistence.data.datastorer import NullDataStorer
from datafinder.persistence.error import PersistenceError

__version__ = "$Revision-Id$"

_BLOCK_SIZE = 30000

class DataFileSystemAdapter(NullDataStorer):
    """ Implements data storer interface for a standard file system. """

    def __init__(self, identifier, itemIdMapper):
        """
        Constructor.

        @param identifier: Identifier of the item.
        @type identifier: C{unicode}
        @param itemIdMapper: Utility object allowing item identifier mapping.
        @type itemIdMapper: L{ItemIdentifierMapper<datafinder.persistence.adapters.filesystem.util.ItemIdentifierMapper>}
        """

        NullDataStorer.__init__(self, identifier)
        self._itemIdMapper = itemIdMapper
        self._persistenceId = self._itemIdMapper.mapIdentifier(identifier)

    @property
    def linkTarget(self):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        link = util.ShortCut(self._persistenceId)
        if link.isLink():
            persistenceId = link.resolve()
            return self._itemIdMapper.mapPersistenceIdentifier(persistenceId)

    @property
    def isLink(self):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        return util.createShortcut(self._persistenceId).isLink()

    @property
    def isCollection(self):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        return os.path.isdir(self._persistenceId)

    @property
    def isLeaf(self):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        return os.path.isfile(self._persistenceId)

    @property
    def canAddChildren(self):
        """
        @see L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}
        """

        canAddChildren = False
        if self.isCollection and not util.isWindowsRootPath(self._persistenceId):
            canAddChildren = True
        return canAddChildren

    def createCollection(self, recursively=False):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        try:
            if recursively:
                os.makedirs(self._persistenceId)
            else:
                os.mkdir(self._persistenceId)
        except OSError, error:
            reason = os.strerror(error.errno)
            errorMessage = "Cannot create collection '%s'. Reason: '%s'" % (self.identifier, reason)
            raise PersistenceError(errorMessage)

    def createResource(self):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        try:
            fd = open(self._persistenceId, "wb")
            fd.close()
        except IOError, error:
            reason = os.strerror(error.errno)
            errorMessage = "Cannot create resource '%s'. Reason: '%s'" % (self.identifier, reason)
            raise PersistenceError(errorMessage)

    def createLink(self, source):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        link = util.createShortcut(self._persistenceId)
        link.create(self._itemIdMapper.mapIdentifier(source.identifier))

    def getChildren(self):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        mappedIds = list()
        rawResult = list()
        if self.isCollection:
            try:
                rawResult = util.listDirectory(self._persistenceId)
            except OSError, error:
                reason = os.strerror(error.errno)
                errorMessage = "Cannot retrieve children of '%s'. Reason: '%s'." % (self.identifier, reason)
                raise PersistenceError(errorMessage)
        for persistenceId in rawResult:
            mappedIds.append(self._itemIdMapper.mapPersistenceIdentifier(persistenceId))
        return mappedIds

    def exists(self):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        return os.path.exists(self._persistenceId)

    def delete(self):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        try:
            if self.isCollection:
                shutil.rmtree(self._persistenceId)
            else:
                os.remove(self._persistenceId)
        except OSError, error:
            reason = os.strerror(error.errno)
            errorMessage = "Cannot delete item '%s'. Reason: '%s'." % (self.identifier, reason)
            raise PersistenceError(errorMessage)
        except shutil.Error, error:
            errorMessage = "Cannot delete item '%s'. Reason: '%s'." % (self.identifier, reason)
            raise PersistenceError(errorMessage)

    def copy(self, destination):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        try:
            targetPersistenceId = self._itemIdMapper.mapIdentifier(destination.identifier)
            if self.isCollection:
                shutil.copytree(self._persistenceId, targetPersistenceId)
            else:
                shutil.copy(self._persistenceId, targetPersistenceId)
        except (IOError, OSError, EnvironmentError), error:
            reason = os.strerror(error.errno or 0)
            errorMessage = "Cannot copy item '%s' to item '%s'. Reason: '%s'." % (self.identifier, destination.identifier, reason)
            raise PersistenceError(errorMessage)

    def move(self, destination):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        try:
            os.rename(self._persistenceId, self._itemIdMapper.mapIdentifier(destination.identifier))
        except OSError, error:
            reason = os.strerror(error.errno)
            errorMessage = "Cannot move item '%s' to item '%s'. Reason: '%s'." % (self.identifier, destination.identifier, reason)
            raise PersistenceError(errorMessage)

    def readData(self):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        try:
            return open(self._persistenceId, "rb")
        except IOError, error:
            reason = os.strerror(error.errno)
            errorMessage = "Cannot read item data '%s'. Reason: '%s'." % (self.identifier, reason)
            raise PersistenceError(errorMessage)

    def writeData(self, dataStream):
        """ @see: L{NullDataStorer<datafinder.persistence.data.datastorer.NullDataStorer>}  """

        try:
            fd = open(self._persistenceId, "wb")
            try:
                block = dataStream.read(_BLOCK_SIZE)
                while len(block) > 0:
                    fd.write(block)
                    block = dataStream.read(_BLOCK_SIZE)
            finally:
                fd.close()
        except IOError, error:
            reason = os.strerror(error.errno)
            errorMessage = "Cannot read item data '%s'. Reason: '%s'." % (self.identifier, reason)
            raise PersistenceError(errorMessage)
        finally:
            dataStream.close()


text:
package versioned_test

import (
	"encoding/json"
	"io"
	"testing"
	"time"

	"k8s.io/api/core/v1"
	apiequality "k8s.io/apimachinery/pkg/api/equality"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	runtimejson "k8s.io/apimachinery/pkg/runtime/serializer/json"
	"k8s.io/apimachinery/pkg/runtime/serializer/streaming"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apimachinery/pkg/watch"
	"github.com/hyperhq/client-go/kubernetes/scheme"
	restclientwatch "github.com/hyperhq/client-go/rest/watch"
)

// getDecoder mimics how k8s.io/client-go/rest.createSerializers creates a decoder
func getDecoder() runtime.Decoder {
	jsonSerializer := runtimejson.NewSerializer(runtimejson.DefaultMetaFactory, scheme.Scheme, scheme.Scheme, false)
	directCodecFactory := serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
	return directCodecFactory.DecoderToVersion(jsonSerializer, v1.SchemeGroupVersion)
}

func TestDecoder(t *testing.T) {
	table := []watch.EventType{watch.Added, watch.Deleted, watch.Modified, watch.Error}

	for _, eventType := range table {
		out, in := io.Pipe()

		decoder := restclientwatch.NewDecoder(streaming.NewDecoder(out, getDecoder()), getDecoder())

		expect := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}
		encoder := json.NewEncoder(in)
		go func() {
			data, err := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expect)
			if err != nil {
				t.Fatalf("Unexpected error %v", err)
			}
			event := metav1.WatchEvent{
				Type:   string(eventType),
				Object: runtime.RawExtension{Raw: json.RawMessage(data)},
			}
			if err := encoder.Encode(&event); err != nil {
				t.Errorf("Unexpected error %v", err)
			}
			in.Close()
		}()

		done := make(chan struct{})
		go func() {
			action, got, err := decoder.Decode()
			if err != nil {
				t.Fatalf("Unexpected error %v", err)
			}
			if e, a := eventType, action; e != a {
				t.Errorf("Expected %v, got %v", e, a)
			}
			if e, a := expect, got; !apiequality.Semantic.DeepDerivative(e, a) {
				t.Errorf("Expected %v, got %v", e, a)
			}
			t.Logf("Exited read")
			close(done)
		}()
		<-done

		done = make(chan struct{})
		go func() {
			_, _, err := decoder.Decode()
			if err == nil {
				t.Errorf("Unexpected nil error")
			}
			close(done)
		}()
		<-done

		decoder.Close()
	}
}

func TestDecoder_SourceClose(t *testing.T) {
	out, in := io.Pipe()
	decoder := restclientwatch.NewDecoder(streaming.NewDecoder(out, getDecoder()), getDecoder())

	done := make(chan struct{})

	go func() {
		_, _, err := decoder.Decode()
		if err == nil {
			t.Errorf("Unexpected nil error")
		}
		close(done)
	}()

	in.Close()

	select {
	case <-done:
		break
	case <-time.After(wait.ForeverTestTimeout):
		t.Error("Timeout")
	}
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.base;

/**
 * A subclass used only to differentiate different test client service process instances.
 */
public class MultiprocessTestClientService3 extends MultiprocessTestClientService {}


text:
namespace llvm {
  template <class T> class ArrayRef;
  class Constant;
  class Function;
  class GlobalVariable;
  class Value;
}

namespace swift {
  class AbstractFunctionDecl;
  class FuncDecl;
  enum class ResilienceExpansion : unsigned;
  struct SILDeclRef;
  class SILType;
  class VarDecl;
  enum class SpecialProtocol : uint8_t;

namespace irgen {
  class Callee;
  class Explosion;
  class FieldTypeInfo;
  class GenericTypeRequirements;
  class IRGenFunction;
  class IRGenModule;
  class Size;
  class StructLayout;
  struct ClassLayout;

  /// Is the given class known to have Swift-compatible metadata?
  bool hasKnownSwiftMetadata(IRGenModule &IGM, ClassDecl *theClass);

  inline bool isKnownNotTaggedPointer(IRGenModule &IGM, ClassDecl *theClass) {
    // For now, assume any class type defined in Clang might be tagged.
    return hasKnownSwiftMetadata(IGM, theClass);
  }

  /// Is the given class-like type known to have Swift-compatible
  /// metadata?
  bool hasKnownSwiftMetadata(IRGenModule &IGM, CanType theType);

  /// Is the given class known to have an implementation in Swift?
  bool hasKnownSwiftImplementation(IRGenModule &IGM, ClassDecl *theClass);

  /// Is the given method known to be callable by vtable dispatch?
  bool hasKnownVTableEntry(IRGenModule &IGM, AbstractFunctionDecl *theMethod);

  /// Emit the body of a lazy cache access function.
  void emitLazyCacheAccessFunction(IRGenModule &IGM,
                                   llvm::Function *accessor,
                                   llvm::GlobalVariable *cacheVariable,
        const llvm::function_ref<llvm::Value *(IRGenFunction &IGF)> &getValue);

  /// Emit a declaration reference to a metatype object.
  void emitMetatypeRef(IRGenFunction &IGF, CanMetatypeType type,
                       Explosion &explosion);

  /// Emit a reference to a compile-time constant piece of type metadata, or
  /// return a null pointer if the type's metadata cannot be represented by a
  /// constant.
  llvm::Constant *tryEmitConstantTypeMetadataRef(IRGenModule &IGM,
                                                 CanType type);

  enum class MetadataValueType { ObjCClass, TypeMetadata };

  /// Emit a reference to the heap metadata for a class.
  ///
  /// \returns a value of type ObjCClassPtrTy or TypeMetadataPtrTy,
  ///    depending on desiredType
  llvm::Value *emitClassHeapMetadataRef(IRGenFunction &IGF, CanType type,
                                        MetadataValueType desiredType,
                                        bool allowUninitialized = false);

  /// Emit a reference to the (initialized) ObjC heap metadata for a class.
  ///
  /// \returns a value of type ObjCClassPtrTy
  llvm::Value *emitObjCHeapMetadataRef(IRGenFunction &IGF, ClassDecl *theClass,
                                       bool allowUninitialized = false);

  /// Given a class metadata reference, produce the appropriate heap
  /// metadata reference for it.
  llvm::Value *emitClassHeapMetadataRefForMetatype(IRGenFunction &IGF,
                                                   llvm::Value *metatype,
                                                   CanType type);

  /// Emit the metadata associated with the given class declaration.
  void emitClassMetadata(IRGenModule &IGM, ClassDecl *theClass,
                         const StructLayout &layout,
                         const ClassLayout &fieldLayout);

  /// Emit the constant initializer of the type metadata candidate for
  /// the given foreign class declaration.
  llvm::Constant *emitForeignTypeMetadataInitializer(IRGenModule &IGM,
                                                     CanType type,
                                                     Size &addressPointOffset);

  /// Emit the metadata associated with the given struct declaration.
  void emitStructMetadata(IRGenModule &IGM, StructDecl *theStruct);

  /// Emit the metadata associated with the given enum declaration.
  void emitEnumMetadata(IRGenModule &IGM, EnumDecl *theEnum);

  /// Get what will be the index into the generic type argument array at the end
  /// of a nominal type's metadata.
  int32_t getIndexOfGenericArgument(IRGenModule &IGM,
                                    NominalTypeDecl *decl,
                                    ArchetypeType *archetype);

  /// Given a reference to nominal type metadata of the given type,
  /// derive a reference to the parent type metadata.  There must be a
  /// parent type.
  llvm::Value *emitParentMetadataRef(IRGenFunction &IGF,
                                     NominalTypeDecl *theDecl,
                                     llvm::Value *metadata);

  /// Given a reference to nominal type metadata of the given type,
  /// derive a reference to the type metadata stored in the nth
  /// requirement slot.  The type must have generic arguments.
  llvm::Value *emitArgumentMetadataRef(IRGenFunction &IGF,
                                       NominalTypeDecl *theDecl,
                                       const GenericTypeRequirements &reqts,
                                       unsigned reqtIndex,
                                       llvm::Value *metadata);

  /// Given a reference to nominal type metadata of the given type,
  /// derive a reference to a protocol witness table stored in the nth
  /// requirement slot.  The type must have generic arguments.
  llvm::Value *emitArgumentWitnessTableRef(IRGenFunction &IGF,
                                           NominalTypeDecl *theDecl,
                                           const GenericTypeRequirements &reqts,
                                           unsigned reqtIndex,
                                           llvm::Value *metadata);

  /// Get the offset of a field in the class type metadata.
  Size getClassFieldOffset(IRGenModule &IGM,
                           ClassDecl *theClass,
                           VarDecl *field);

  /// Given a reference to class type metadata of the given type,
  /// decide the offset to the given field.  This assumes that the
  /// offset is stored in the metadata, i.e. its offset is potentially
  /// dependent on generic arguments.  The result is a ptrdiff_t.
  llvm::Value *emitClassFieldOffset(IRGenFunction &IGF,
                                    ClassDecl *theClass,
                                    VarDecl *field,
                                    llvm::Value *metadata);

  /// Given a metatype value, read its instance type.
  llvm::Value *emitMetatypeInstanceType(IRGenFunction &IGF,
                                        llvm::Value *metatypeMetadata);

  /// Load the fragile instance size and alignment mask from a reference to
  /// class type metadata of the given type.
  std::pair<llvm::Value *, llvm::Value *>
  emitClassFragileInstanceSizeAndAlignMask(IRGenFunction &IGF,
                                           ClassDecl *theClass,
                                           llvm::Value *metadata);

  /// Load the instance size and alignment mask from a reference to
  /// class type metadata of the given type.
  std::pair<llvm::Value *, llvm::Value *>
  emitClassResilientInstanceSizeAndAlignMask(IRGenFunction &IGF,
                                             ClassDecl *theClass,
                                             llvm::Value *metadata);

  /// Given an opaque class instance pointer, produce the type
  /// metadata reference as a %type*.
  llvm::Value *emitDynamicTypeOfOpaqueHeapObject(IRGenFunction &IGF,
                                                 llvm::Value *object);

  /// Given a heap-object instance, with some heap-object type,
  /// produce a reference to its type metadata.
  llvm::Value *emitDynamicTypeOfHeapObject(IRGenFunction &IGF,
                                           llvm::Value *object,
                                           SILType objectType,
                                           bool suppressCast = false);

  /// Given a heap-object instance, with some heap-object type, produce a
  /// reference to its heap metadata by dynamically asking the runtime for it.
  llvm::Value *emitHeapMetadataRefForUnknownHeapObject(IRGenFunction &IGF,
                                                       llvm::Value *object);

  /// Given a heap-object instance, with some heap-object type,
  /// produce a reference to its heap metadata.
  llvm::Value *emitHeapMetadataRefForHeapObject(IRGenFunction &IGF,
                                                llvm::Value *object,
                                                CanType objectType,
                                                bool suppressCast = false);

  /// Given a heap-object instance, with some heap-object type,
  /// produce a reference to its heap metadata.
  llvm::Value *emitHeapMetadataRefForHeapObject(IRGenFunction &IGF,
                                                llvm::Value *object,
                                                SILType objectType,
                                                bool suppressCast = false);

  /// Given an instance pointer (or, for a static method, a class
  /// pointer), emit the callee for the given method.
  llvm::Value *emitVirtualMethodValue(IRGenFunction &IGF,
                                      llvm::Value *base,
                                      SILType baseType,
                                      SILDeclRef method,
                                      CanSILFunctionType methodType,
                                      bool useSuperVTable);

  /// \brief Load a reference to the protocol descriptor for the given protocol.
  ///
  /// For Swift protocols, this is a constant reference to the protocol
  /// descriptor symbol.
  /// For ObjC protocols, descriptors are uniqued at runtime by the ObjC
  /// runtime. We need to load the unique reference from a global variable fixed up at
  /// startup.
  llvm::Value *emitProtocolDescriptorRef(IRGenFunction &IGF,
                                         ProtocolDecl *protocol);

  llvm::Value *emitObjCMetadataRefForMetadata(IRGenFunction &IGF,
                                              llvm::Value *classPtr);

  /// Emit the field type accessor for a nominal type's metadata. This function
  /// lazily generates the metadata for the types of all of the nominal type's
  /// fields for reflection purposes.
  void emitFieldTypeAccessor(IRGenModule &IGM,
                             NominalTypeDecl *type,
                             llvm::Function *fn,
                             ArrayRef<FieldTypeInfo> fieldTypes);

  /// Adjustment indices for the address points of various metadata.
  /// Size is in words.
  namespace MetadataAdjustmentIndex {
    enum : unsigned {
      // Class metadata has two words of head-allocated data: the destructor
      // and the value witness table.
      Class = 2,

      // Struct and enum metadata have one word of head-allocated data:
      // the value witness table.
      ValueType = 1,

      // Other metadata objects have no head allocation.
      None = 0,
    };
  }

  enum class MetadataAccessStrategy {
    /// There is a unique public accessor function for the given type metadata.
    PublicUniqueAccessor,

    /// There is a unique hidden accessor function for the given type metadata.
    HiddenUniqueAccessor,

    /// There is a unique private accessor function for the given type metadata.
    PrivateAccessor,

    /// There is no unique accessor function for the given type metadata, but
    /// one should be made automatically.
    NonUniqueAccessor
  };

  /// Is it basically trivial to access the given metadata?  If so, we don't
  /// need a cache variable in its accessor.
  bool isTypeMetadataAccessTrivial(IRGenModule &IGM, CanType type);

  /// Determine how the given type metadata should be accessed.
  MetadataAccessStrategy getTypeMetadataAccessStrategy(IRGenModule &IGM,
                                                       CanType type);

  /// Return the address of a function that will return type metadata
  /// for the given non-dependent type.
  llvm::Function *getOrCreateTypeMetadataAccessFunction(IRGenModule &IGM,
                                                        CanType type);

  /// Get the runtime identifier for a special protocol, if any.
  SpecialProtocol getSpecialProtocolID(ProtocolDecl *P);

} // end namespace irgen
} // end namespace swift

#endif


text:
<?php
require_once('Autoload.php');
class GroupTest extends PHPUnit\Framework\TestCase
{
    use \phpmock\phpunit\PHPMock;

    public function testGroup()
    {
        $user = new \Flipside\Auth\Group();
        $this->assertFalse($user->getGroupName());
        $this->assertFalse($user->getDescription());
        $this->assertFalse($user->setGroupName('AAR'));
        $this->assertFalse($user->setDescription('Test'));
        $this->assertEmpty($user->getMemberUids());
        $this->assertEmpty($user->getMemberUids(true));
        $this->assertEmpty($user->members());
        $this->assertEmpty($user->members(true));
        $this->assertEmpty($user->members(false, false));
        $this->assertEmpty($user->members(true, false));
        $this->assertEmpty($user->members(false, false, false));
        $this->assertEmpty($user->members(true, false, false));
        $this->assertEmpty($user->members(true, true, false));
        $this->assertEquals(0, $user->member_count());
        $this->assertFalse($user->clearMembers());
        $this->assertEmpty($user->getNonMembers());
        $this->assertFalse($user->addMember('test'));
        $this->assertFalse($user->addMember('test', true));
        $this->assertFalse($user->addMember('test', false, false));
        $this->assertFalse($user->addMember('test', true, false));
        $json = json_encode($user);
        $this->assertEquals($json, '{"cn":false,"description":false,"member":[]}');
        $this->assertFalse(\Flipside\Auth\Group::from_name('test'));

        $user->editGroup(array('description' => 'Testing'));
    }

    public function testLDAPGroup()
    {
        $GLOBALS['FLIPSIDE_SETTINGS_LOC'] = './tests/helpers';
        try
        {
            $group = new \Flipside\Auth\LDAPGroup(false);
            $this->assertFalse(true);
        }
        catch(\Exception $ex)
        {
            $this->assertFalse(false);
        }
        $array = array('dn'=>array('cn=Test,dc=example,dc=com'), 'cn'=>array('Test'), 'description'=>array('Test Group'), 'member'=>array('uid=test,dc=example,dc=com', 'cn=tg,dc=example,dc=com'));
        $ldapGroup = new \Flipside\LDAP\LDAPObject($array);
        $group = new \Flipside\Auth\LDAPGroup($ldapGroup);
        $this->assertEquals('Test', $group->getGroupName());
        $this->assertEquals('Test Group', $group->getDescription());
        $group->setDescription('New Group');
        $this->assertEquals('New Group', $group->getDescription());
        $ids = $group->getMemberUids(false);
        $this->assertNotFalse($ids);
        $this->assertCount(2, $ids);

        $this->assertTrue($group->addMember('test2', false, false));
        $ids = $group->getMemberUids(false);
        $this->assertNotFalse($ids);
        $this->assertCount(3, $ids);

        $this->assertTrue($group->addMember('test3', true, false));
        $ids = $group->getMemberUids(false);
        $this->assertNotFalse($ids);
        $this->assertCount(4, $ids);

        $group->clearMembers();
        $ids = $group->getMemberUids();
        $this->assertNotFalse($ids);
        $this->assertCount(0, $ids);

        $array = array('dn'=>array('cn=Test,dc=example,dc=com'), 'cn'=>array('Test'), 'description'=>array('Test Group'), 'memberuid'=>array('test'));
        $ldapGroup = new \Flipside\LDAP\LDAPObject($array);
        $group = new \Flipside\Auth\LDAPGroup($ldapGroup);
        $ids = $group->getMemberUids();
        $this->assertNotFalse($ids);
        $this->assertCount(1, $ids);

        $group->clearMembers();
        $ids = $group->getMemberUids();
        $this->assertNotFalse($ids);
        $this->assertCount(0, $ids);

        $array = array('dn'=>array('cn=Test,dc=example,dc=com'), 'cn'=>array('Test'), 'description'=>array('Test Group'), 'uniquemember'=>array('uid=test'));
        $ldapGroup = new \Flipside\LDAP\LDAPObject($array);
        $group = new \Flipside\Auth\LDAPGroup($ldapGroup);
        $ids = $group->getMemberUids();
        $this->assertNotFalse($ids);
        $this->assertCount(1, $ids);

        $group->clearMembers();
        $ids = $group->getMemberUids();
        $this->assertNotFalse($ids);
        $this->assertCount(0, $ids);

        $group->addMember('test', false, false);
        $ids = $group->getMemberUids();
        $this->assertNotFalse($ids);
        $this->assertCount(1, $ids);
        $group->addMember('test', false, false);
        $ids = $group->getMemberUids();
        $this->assertCount(1, $ids);

        $array = array('dn'=>array('cn=Test,dc=example,dc=com'), 'cn'=>array('Test'), 'description'=>array('Test Group'), 'memberuid'=>array('test'));
        $ldapGroup = new \Flipside\LDAP\LDAPObject($array);
        $group = new \Flipside\Auth\LDAPGroup($ldapGroup);
        $ids = $group->getMemberUids();
        $this->assertNotFalse($ids);
        $this->assertCount(1, $ids);

        $group->addMember('test1', false, false);
        $ids = $group->getMemberUids();
        $this->assertNotFalse($ids);
        $this->assertCount(2, $ids);

        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('Unable to add a group as a child of this group type');
        $group->addMember('bob', true, false);
    }

    public function testLDAPGroupRecursiveMembers()
    {
        $ldap_connect = $this->getFunctionMock('Flipside\LDAP', "ldap_connect");
        $ldap_connect->expects($this->any())->willReturn(true);
        $ldap_bind = $this->getFunctionMock('Flipside\LDAP', "ldap_bind");
        $ldap_bind->expects($this->any())->willReturn(true);
        $ldap_set_option = $this->getFunctionMock('Flipside\LDAP', "ldap_set_option");
        $ldap_set_option->expects($this->any())->willReturn(true);
        $ldap_close = $this->getFunctionMock('Flipside\LDAP', "ldap_close");
        $ldap_close->expects($this->any())->willReturn(true);
        $ldap_list = $this->getFunctionMock('Flipside\LDAP', "ldap_read");
        $ldap_list->expects($this->any())->willReturn(true);
        $ldap_list = $this->getFunctionMock('Flipside\LDAP', "ldap_list");
        $ldap_list->expects($this->any())->willReturn(true);
        $ldap_get_entries = $this->getFunctionMock('Flipside\LDAP', "ldap_get_entries");
        $ldap_get_entries->expects($this->any())->willReturn(array('count' => 1, 0 => array('dn'=>'test', 'cn'=>'test', 'description'=>array('Bob'), 'member'=>array('count' => 1, 0 => 'uid=bob'))));

        $server = \Flipside\LDAP\LDAPServer::getInstance();
        $server->connect('ldap');
        $array = array('dn'=>array('cn=Test,dc=example,dc=com'), 'cn'=>array('Test'), 'description'=>array('Test Group'), 'uniquemember'=>array('count' => 2, 0=> 'uid=test', 1 => 'cn=x'));
        $ldapGroup = new \Flipside\LDAP\LDAPObject($array);
        $group = new \Flipside\Auth\LDAPGroup($ldapGroup);
        $ids = $group->getMemberUids(true);
        $this->assertNotFalse($ids);
        $this->assertCount(2, $ids);

        $ids = $group->members();
        $this->assertNotFalse($ids);
        $this->assertCount(2, $ids);

        $array = array('dn'=>array('cn=Test,dc=example,dc=com'), 'cn'=>array('Test'), 'description'=>array('Test Group'), 'uniquemember'=>array('count' => 2, 0=> 'uid=test', 1 => 'cn=x'));
        $ldapGroup = new \Flipside\LDAP\LDAPObject($array);
        $group = new \Flipside\Auth\LDAPGroup($ldapGroup);
        $ids = $group->members(true, false);
        $this->assertNotFalse($ids);
        $this->assertCount(2, $ids);

        $array = array('dn'=>array('cn=Test,dc=example,dc=com'), 'cn'=>array('Test'), 'description'=>array('Test Group'), 'uniquemember'=>array('count' => 2, 0=> 'uid=test,base', 1 => 'cn=x,base'));
        $ldapGroup = new \Flipside\LDAP\LDAPObject($array);
        $group = new \Flipside\Auth\LDAPGroup($ldapGroup);
        $ids = $group->members(true, false);
        $this->assertNotFalse($ids);
        $this->assertCount(2, $ids);

        $server->disconnect();

        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('data must be set for LDAPGroup');
        \Flipside\Auth\LDAPGroup::from_name('test');
    }

    public function testSQLGroup()
    {
        $GLOBALS['FLIPSIDE_SETTINGS_LOC'] = './tests/helpers';
        $auth = \Flipside\AuthProvider::getInstance();
        $dataSet = \Flipside\DataSetFactory::getDataSetByName('authentication');
        if($dataSet->tableExists('groupUserMap'))
        {
            $dataSet->raw_query('DROP TABLE groupUserMap;');
        }
        $dataSet->raw_query('CREATE TABLE groupUserMap (`idgroupUserMap` int, `groupCN` varchar(50) NOT NULL, `uid` varchar(50) DEFAULT NULL, `gid` varchar(50) DEFAULT NULL, PRIMARY KEY (`idgroupUserMap`));');

        $group = new \Flipside\Auth\SQLGroup(array(), false);
        $this->assertFalse($group->getGroupName());
        $this->assertFalse($group->getDescription());
        $this->assertEmpty($group->members());
        $this->assertEmpty($group->getMemberUids());

        $group = new \Flipside\Auth\SQLGroup(array('gid'=>'testGid', 'description'=>'Test Group'), false);
        $this->assertEquals($group->getGroupName(), 'testGid');
        $this->assertEquals($group->getDescription(), 'Test Group');

        /*
        $group = new \Flipside\Auth\SQLGroup(array(), false);
        $group->addMember('test');
        $group->editGroup(array('member'=>array('test1')));
        $this->assertEquals(array(), $group->getMemberUids());

        $group->editGroup(array('member'=>array(array('type'=>'Group', 'cn'=>'test1'))));
        $this->assertEquals(array(), $group->getMemberUids());

        $group->editGroup(array('member'=>array(array('type'=>'User', 'uid'=>'test1'))));
        $this->assertEquals(array(), $group->getMemberUids());*/

        $dataSet->raw_query('DROP TABLE groupUserMap;');
    }
}
/* vim: set tabstop=4 shiftwidth=4 expandtab: */


text:
import {checkData, validateDataExists, writeScript} from '../3p/3p';

/**
 * @param {!Window} global
 * @param {!Object} data
 */
export function openadstream(global, data) {
  //all available fields
  checkData(data, ['adhost', 'sitepage', 'pos', 'query']);
  //required fields
  validateDataExists(data, ['adhost', 'sitepage', 'pos']);
  let url = 'https://' + encodeURIComponent(data.adhost) + '/3/' + data.sitepage + '/1' + String(Math.random()).substring(2, 11) + '@' + data.pos;
  if (data.query) {
    url = url + '?' + data.query;
  }
  writeScript(global, url);

}


text:
<component name="libraryTable">
  <library name="GreenDaoUpgradeHelper-v0.0.5">
    <CLASSES>
      <root url="file://$PROJECT_DIR$/mygreendao/build/intermediates/exploded-aar/com.github.yuweiguocn/GreenDaoUpgradeHelper/v0.0.5/res" />
      <root url="jar://$PROJECT_DIR$/mygreendao/build/intermediates/exploded-aar/com.github.yuweiguocn/GreenDaoUpgradeHelper/v0.0.5/jars/classes.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
package com.Voxce.model;

import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="rule_discrepancy_texts")
public class RuleDiscrepancyTexts {

	private int rule_discrepancy_text_id;
	private int validation_rule_id;
	private int discrepancy_text_id;
	private int created_by;
	private Date date_created;
	private int modified_by;
	private Date date_modified;

	@Id
	@GeneratedValue
	@Column(name="validation_rule_id")
	public int getRule_discrepancy_text_id() {
		return rule_discrepancy_text_id;
	}
	public void setRule_discrepancy_text_id(int rule_discrepancy_text_id) {
		this.rule_discrepancy_text_id = rule_discrepancy_text_id;
	}

	@Column(name="validation_rule_id")
	public int getValidation_rule_id() {
		return validation_rule_id;
	}
	public void setValidation_rule_id(int validation_rule_id) {
		this.validation_rule_id = validation_rule_id;
	}

	@Column(name="discrepancy_text_id")
	public int getDiscrepancy_text_id() {
		return discrepancy_text_id;
	}
	public void setDiscrepancy_text_id(int discrepancy_text_id) {
		this.discrepancy_text_id = discrepancy_text_id;
	}

	@Column(name="created_by")
	public int getCreated_by() {
		return created_by;
	}
	public void setCreated_by(int created_by) {
		this.created_by = created_by;
	}

	@Column(name="date_created")
	public Date getDate_created() {
		return date_created;
	}
	public void setDate_created(Date date_created) {
		this.date_created = date_created;
	}

	@Column(name="modified_by")
	public int getModified_by() {
		return modified_by;
	}
	public void setModified_by(int modified_by) {
		this.modified_by = modified_by;
	}

	@Column(name="date_modified")
	public Date getDate_modified() {
		return date_modified;
	}
	public void setDate_modified(Date date_modified) {
		this.date_modified = date_modified;
	}

}


text:
require 'peregrine/features'
require 'peregrine/handlers'

module Peregrine
  # == Summary
  #
  # A Package is essentially a fast and easy way to package multiple commonly
  # used items into an archive that can quickly recreate new instances of those
  # items. Packages are especially useful for grouping together Components and
  # Entities, and can be used to create 'templates' for instantiating objects
  # that will be used often.
  #
  # == Usage
  #
  # By default, a Package may contain items that are children of the Component,
  # Entity, and System classes. A single Package may contain any combination of
  # these items. Items are added to the Package with the +wrap+ method, while
  # instantiation of wrapped items is performed with the +unwrap+ method. The
  # +unwrap+ method returns an array of instantiated objects built from the
  # Package's internal archive of object data.
  #
  # When used in conjunction with the EntityManager's +add_package+ method, the
  # Package class truly shines.
  #
  # == Example
  #
  # Let's assume that we're building a role-playing game and need a common
  # template for creating non-playable characters. That package may look
  # something like this:
  #
  #    include Peregrine
  #    template = Package.new { |pkg| pkg.name = 'NPC' }
  #    template.wrap(Entity.new(Renderable, Autonomous, Conversational) do |npc|
  #      npc.name = 'Generic NPC'
  #      npc.add_tags(:npc)
  #    end)
  #    template.unwrap # => [Entity 'Generic NPC' ... (3)]
  #
  # The newly instanced Entity generated from the package will have a different
  # ID and UUID each time it is created, but will always have the same name,
  # components, and tags.
  class Package
    include Peregrine::Features

    # Array of objects used to build instances for the +unwrap+ method.
    attr_reader :archive

    # Array of package handling modules used to facilitate wrapping and
    # unwrapping of objects.
    attr_reader :handlers

    # Creates a new Package instance and adds the given objects to the Package.
    # Yields the newly created Package if a block is given.
    def initialize(*objects)
      @archive  = []
      @handlers = [ Peregrine::Handlers::ComponentPackage,
                    Peregrine::Handlers::EntityPackage,
                    Peregrine::Handlers::SystemPackage ]
      wrap(*objects)
      yield self if block_given?
    end

    # Wraps the given objects into the Package. Returns the array of archived
    # objects in the Package.
    def wrap(*objects)
      objects.each do |object|
        @handlers.each do |handler|
          next unless handler.handles?(object)
          item = handler.wrap(object)
          @archive.push(item) unless item.nil?
        end
      end
      @archive
    end

    # Unwraps all objects in the package into newly instanced objects. Returns
    # the array of instanced objects. Yields each unwrapped item if a block is
    # given.
    def unwrap
      unwrapped = []
      @archive.each do |object|
        @handlers.each do |handler|
          item = handler.unwrap(object)
          unwrapped.push(item) unless item.nil?
        end
      end
      unwrapped.each { |item| yield item if block_given? }
      unwrapped
    end

    # Presents a human-readable summary of the Package.
    def to_s
      "Package '#{name}' #{id} (#{@archive.size})"
    end
    alias :inspect :to_s
  end
end


text:
class PreScanOutputDev: public OutputDev {
public:

  // Constructor.
  PreScanOutputDev(PDFDoc *docA);

  // Destructor.
  virtual ~PreScanOutputDev();

  //----- get info about output device

  // Does this device use upside-down coordinates?
  // (Upside-down means (0,0) is the top left corner of the page.)
  virtual GBool upsideDown() { return gTrue; }

  // Does this device use drawChar() or drawString()?
  virtual GBool useDrawChar() { return gTrue; }

  // Does this device use tilingPatternFill()?  If this returns false,
  // tiling pattern fills will be reduced to a series of other drawing
  // operations.
  virtual GBool useTilingPatternFill() { return gTrue; }

  // Does this device use functionShadedFill(), axialShadedFill(), and
  // radialShadedFill()?  If this returns false, these shaded fills
  // will be reduced to a series of other drawing operations.
  virtual GBool useShadedFills(int type) { return gTrue; }

  // Does this device use beginType3Char/endType3Char?  Otherwise,
  // text in Type 3 fonts will be drawn with drawChar/drawString.
  virtual GBool interpretType3Chars() { return gTrue; }

  //----- initialization and control

  // Start a page.
  virtual void startPage(int pageNum, GfxState *state);

  // End a page.
  virtual void endPage();

  //----- path painting
  virtual void stroke(GfxState *state);
  virtual void fill(GfxState *state);
  virtual void eoFill(GfxState *state);
  virtual GBool tilingPatternFill(GfxState *state, Gfx *gfx, Catalog *cat, Object *str,
				  double *pmat, int paintType, int tilingType, Dict *resDict,
				  double *mat, double *bbox,
				  int x0, int y0, int x1, int y1,
				  double xStep, double yStep);
  virtual GBool functionShadedFill(GfxState *state,
				   GfxFunctionShading *shading);
  virtual GBool axialShadedFill(GfxState *state, GfxAxialShading *shading, double tMin, double tMax);
  virtual GBool radialShadedFill(GfxState *state, GfxRadialShading *shading, double tMin, double tMax);

  //----- path clipping
  virtual void clip(GfxState *state);
  virtual void eoClip(GfxState *state);

  //----- text drawing
  virtual void beginStringOp(GfxState *state);
  virtual void endStringOp(GfxState *state);
  virtual GBool beginType3Char(GfxState *state, double x, double y,
			       double dx, double dy,
			       CharCode code, Unicode *u, int uLen);
  virtual void endType3Char(GfxState *state);

  //----- image drawing
  virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
			     int width, int height, GBool invert,
			     GBool interpolate, GBool inlineImg);
  virtual void drawImage(GfxState *state, Object *ref, Stream *str,
			 int width, int height, GfxImageColorMap *colorMap,
			 GBool interpolate, int *maskColors, GBool inlineImg);
  virtual void drawMaskedImage(GfxState *state, Object *ref, Stream *str,
			       int width, int height,
			       GfxImageColorMap *colorMap,
			       GBool interpolate,
			       Stream *maskStr, int maskWidth, int maskHeight,
			       GBool maskInvert, GBool maskInterpolate);
  virtual void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
				   int width, int height,
				   GfxImageColorMap *colorMap,
				   GBool interpolate,
				   Stream *maskStr,
				   int maskWidth, int maskHeight,
				   GfxImageColorMap *maskColorMap,
				   GBool maskInterpolate);

  //----- transparency groups and soft masks
  virtual void beginTransparencyGroup(GfxState *state, double *bbox,
				      GfxColorSpace *blendingColorSpace,
				      GBool isolated, GBool knockout,
				      GBool forSoftMask);
	virtual void paintTransparencyGroup(GfxState *state, double *bbox);
	virtual void setSoftMask(GfxState *state, double *bbox, GBool alpha,
			   Function *transferFunc, GfxColor *backdropColor);

  //----- special access

  // Returns true if the operations performed since the last call to
  // clearStats() are all monochrome (black or white).
  GBool isMonochrome() { return mono; }

  // Returns true if the operations performed since the last call to
  // clearStats() are all gray.
  GBool isGray() { return gray; }

  // Returns true if the operations performed since the last call to
  // clearStats() included any transparency.
  GBool usesTransparency() { return transparency; }

  // Returns true if the operations performed since the last call to
  // clearStats() are all rasterizable by GDI calls in GDIOutputDev.
  GBool isAllGDI() { return gdi; }

  // Returns true if the operations performed since the last call to
  // clearStats() included any image mask fills with a pattern color
  // space. (only level1!)
  GBool usesPatternImageMask() { return patternImgMask; }

  // Clear the stats used by the above functions.
  void clearStats();

private:

  void check(GfxColorSpace *colorSpace, GfxColor *color,
	     double opacity, GfxBlendMode blendMode);

  PDFDoc *doc;
  GBool mono;
  GBool gray;
  GBool transparency;
  GBool gdi;
  PSLevel level;		// PostScript level (1, 2, separation)
  GBool patternImgMask;
};

#endif