text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.remote;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions;
import com.google.devtools.build.lib.authandtls.GoogleAuthUtils;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploaderFactory;
import com.google.devtools.build.lib.buildtool.BuildRequest;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.exec.ExecutorBuilder;
import com.google.devtools.build.lib.remote.Retrier.RetryException;
import com.google.devtools.build.lib.remote.logging.LoggingInterceptor;
import com.google.devtools.build.lib.remote.util.DigestUtil;
import com.google.devtools.build.lib.remote.util.TracingMetadataUtils;
import com.google.devtools.build.lib.runtime.BlazeModule;
import com.google.devtools.build.lib.runtime.Command;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
import com.google.devtools.build.lib.runtime.ServerBuilder;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.ExitCode;
import com.google.devtools.build.lib.util.io.AsynchronousFileOutputStream;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsProvider;
import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.rpc.PreconditionFailure;
import com.google.rpc.PreconditionFailure.Violation;
import io.grpc.CallCredentials;
import io.grpc.ClientInterceptor;
import io.grpc.Context;
import io.grpc.ManagedChannel;
import io.grpc.Status.Code;
import io.grpc.protobuf.StatusProto;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.function.Predicate;
import java.util.logging.Logger;

/** RemoteModule provides distributed cache and remote execution for Bazel. */
public final class RemoteModule extends BlazeModule {
  private static final Logger logger = Logger.getLogger(RemoteModule.class.getName());
  private AsynchronousFileOutputStream rpcLogFile;

  private final ListeningScheduledExecutorService retryScheduler =
      MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(1));
  private RemoteActionContextProvider actionContextProvider;

  private final BuildEventArtifactUploaderFactoryDelegate
      buildEventArtifactUploaderFactoryDelegate = new BuildEventArtifactUploaderFactoryDelegate();

  @Override
  public void serverInit(OptionsProvider startupOptions, ServerBuilder builder) {
    builder.addBuildEventArtifactUploaderFactory(buildEventArtifactUploaderFactoryDelegate, "remote");
  }

  private static final String VIOLATION_TYPE_MISSING = "MISSING";

  private static final Predicate<? super Exception> RETRIABLE_EXEC_ERRORS =
      e -> {
        if (e instanceof CacheNotFoundException || e.getCause() instanceof CacheNotFoundException) {
          return true;
        }
        if (!(e instanceof RetryException)
            || !RemoteRetrierUtils.causedByStatus((RetryException) e, Code.FAILED_PRECONDITION)) {
          return false;
        }
        com.google.rpc.Status status = StatusProto.fromThrowable(e);
        if (status == null || status.getDetailsCount() == 0) {
          return false;
        }
        for (Any details : status.getDetailsList()) {
          PreconditionFailure f;
          try {
            f = details.unpack(PreconditionFailure.class);
          } catch (InvalidProtocolBufferException protoEx) {
            return false;
          }
          if (f.getViolationsCount() == 0) {
            return false; // Generally shouldn't happen
          }
          for (Violation v : f.getViolationsList()) {
            if (!v.getType().equals(VIOLATION_TYPE_MISSING)) {
              return false;
            }
          }
        }
        return true; // if *all* > 0 violations have type MISSING
      };

  @Override
  public void beforeCommand(CommandEnvironment env) throws AbruptExitException {
    env.getEventBus().register(this);
    String buildRequestId = env.getBuildRequestId().toString();
    String commandId = env.getCommandId().toString();
    logger.info("Command: buildRequestId = " + buildRequestId + ", commandId = " + commandId);
    Path logDir =
        env.getOutputBase().getRelative(env.getRuntime().getProductName() + "-remote-logs");
    try {
      // Clean out old logs files.
      if (logDir.exists()) {
        FileSystemUtils.deleteTree(logDir);
      }
      logDir.createDirectory();
    } catch (IOException e) {
      env.getReporter()
          .handle(Event.error("Could not create base directory for remote logs: " + logDir));
      throw new AbruptExitException(ExitCode.LOCAL_ENVIRONMENTAL_ERROR, e);
    }
    RemoteOptions remoteOptions = env.getOptions().getOptions(RemoteOptions.class);
    AuthAndTLSOptions authAndTlsOptions = env.getOptions().getOptions(AuthAndTLSOptions.class);
    DigestHashFunction hashFn = env.getRuntime().getFileSystem().getDigestFunction();
    DigestUtil digestUtil = new DigestUtil(hashFn);

    // Quit if no remote options specified.
    if (remoteOptions == null) {
      return;
    }

    boolean enableRestCache = SimpleBlobStoreFactory.isRestUrlOptions(remoteOptions);
    boolean enableDiskCache = SimpleBlobStoreFactory.isDiskCache(remoteOptions);
    if (enableRestCache && enableDiskCache) {
      throw new AbruptExitException(
          "Cannot enable HTTP-based and local disk cache simultaneously",
          ExitCode.COMMAND_LINE_ERROR);
    }
    boolean enableBlobStoreCache = enableRestCache || enableDiskCache;
    boolean enableGrpcCache = GrpcRemoteCache.isRemoteCacheOptions(remoteOptions);
    if (enableBlobStoreCache && remoteOptions.remoteExecutor != null) {
      throw new AbruptExitException(
          "Cannot combine gRPC based remote execution with local disk or HTTP-based caching",
          ExitCode.COMMAND_LINE_ERROR);
    }

    try {
      List<ClientInterceptor> interceptors = new ArrayList<>();
      if (!remoteOptions.experimentalRemoteGrpcLog.isEmpty()) {
        rpcLogFile = new AsynchronousFileOutputStream(remoteOptions.experimentalRemoteGrpcLog);
        interceptors.add(new LoggingInterceptor(rpcLogFile, env.getRuntime().getClock()));
      }

      final RemoteRetrier executeRetrier;
      final AbstractRemoteActionCache cache;
      if (enableBlobStoreCache) {
        Retrier retrier =
            new Retrier(
                () -> Retrier.RETRIES_DISABLED,
                (e) -> false,
                retryScheduler,
                Retrier.ALLOW_ALL_CALLS);
        executeRetrier = null;
        cache =
            new SimpleBlobStoreActionCache(
                remoteOptions,
                SimpleBlobStoreFactory.create(
                    remoteOptions,
                    GoogleAuthUtils.newCredentials(authAndTlsOptions),
                    env.getWorkingDirectory()),
                retrier,
                digestUtil);
      } else if (enableGrpcCache || remoteOptions.remoteExecutor != null) {
        // If a remote executor but no remote cache is specified, assume both at the same target.
        String target = enableGrpcCache ? remoteOptions.remoteCache : remoteOptions.remoteExecutor;
        ReferenceCountedChannel channel =
            new ReferenceCountedChannel(
                GoogleAuthUtils.newChannel(
                    target,
                    authAndTlsOptions,
                    interceptors.toArray(new ClientInterceptor[0])));
        RemoteRetrier rpcRetrier =
            new RemoteRetrier(
                remoteOptions,
                RemoteRetrier.RETRIABLE_GRPC_ERRORS,
                retryScheduler,
                Retrier.ALLOW_ALL_CALLS);
        executeRetrier = createExecuteRetrier(remoteOptions, retryScheduler);
        CallCredentials credentials = GoogleAuthUtils.newCallCredentials(authAndTlsOptions);
        ByteStreamUploader uploader =
            new ByteStreamUploader(
                remoteOptions.remoteInstanceName,
                channel.retain(),
                credentials,
                remoteOptions.remoteTimeout,
                rpcRetrier);
        cache =
            new GrpcRemoteCache(
                channel.retain(),
                credentials,
                remoteOptions,
                rpcRetrier,
                digestUtil,
                uploader.retain());
        Context requestContext =
            TracingMetadataUtils.contextWithMetadata(buildRequestId, commandId, "bes-upload");
        buildEventArtifactUploaderFactoryDelegate.init(
            new ByteStreamBuildEventArtifactUploaderFactory(
                uploader, target, requestContext, remoteOptions.remoteInstanceName));
        uploader.release();
        channel.release();
      } else {
        executeRetrier = null;
        cache = null;
      }

      final GrpcRemoteExecutor executor;
      if (remoteOptions.remoteExecutor != null) {
        ManagedChannel channel =
            GoogleAuthUtils.newChannel(
                remoteOptions.remoteExecutor,
                authAndTlsOptions,
                interceptors.toArray(new ClientInterceptor[0]));
        RemoteRetrier retrier =
            new RemoteRetrier(
                remoteOptions,
                RemoteRetrier.RETRIABLE_GRPC_ERRORS,
                retryScheduler,
                Retrier.ALLOW_ALL_CALLS);
        executor =
            new GrpcRemoteExecutor(
                channel,
                GoogleAuthUtils.newCallCredentials(authAndTlsOptions),
                remoteOptions.remoteTimeout,
                retrier);
      } else {
        executor = null;
      }
      actionContextProvider =
          new RemoteActionContextProvider(env, cache, executor, executeRetrier, digestUtil, logDir);
    } catch (IOException e) {
      env.getReporter().handle(Event.error(e.getMessage()));
      env.getBlazeModuleEnvironment()
          .exit(
              new AbruptExitException(
                  "Error initializing RemoteModule", ExitCode.COMMAND_LINE_ERROR));
    }
  }

  @Override
  public void afterCommand() {
    if (rpcLogFile != null) {
      try {
        rpcLogFile.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      } finally {
        rpcLogFile = null;
      }
    }
    buildEventArtifactUploaderFactoryDelegate.reset();
  }

  @Override
  public void executorInit(CommandEnvironment env, BuildRequest request, ExecutorBuilder builder) {
    if (actionContextProvider != null) {
      builder.addActionContextProvider(actionContextProvider);
    }
  }

  @Override
  public Iterable<Class<? extends OptionsBase>> getCommandOptions(Command command) {
    return "build".equals(command.name())
        ? ImmutableList.of(RemoteOptions.class, AuthAndTLSOptions.class)
        : ImmutableList.of();
  }

  static RemoteRetrier createExecuteRetrier(
      RemoteOptions options, ListeningScheduledExecutorService retryService) {
    return new RemoteRetrier(
        options.experimentalRemoteRetry
            ? () -> new Retrier.ZeroBackoff(options.experimentalRemoteRetryMaxAttempts)
            : () -> Retrier.RETRIES_DISABLED,
        RemoteModule.RETRIABLE_EXEC_ERRORS,
        retryService,
        Retrier.ALLOW_ALL_CALLS);
  }

  private static class BuildEventArtifactUploaderFactoryDelegate
      implements BuildEventArtifactUploaderFactory {

    private volatile BuildEventArtifactUploaderFactory uploaderFactory;

    public void init(BuildEventArtifactUploaderFactory uploaderFactory) {
      Preconditions.checkState(this.uploaderFactory == null);
      this.uploaderFactory = uploaderFactory;
    }

    public void reset() {
      this.uploaderFactory = null;
    }

    @Override
    public BuildEventArtifactUploader create(OptionsProvider options) {
      BuildEventArtifactUploaderFactory uploaderFactory0 = this.uploaderFactory;
      if (uploaderFactory0 == null) {
        return BuildEventArtifactUploader.LOCAL_FILES_UPLOADER;
      }
      return uploaderFactory0.create(options);
    }
  }
}


text:
package com.google.cloud.functions.v2alpha.samples;

// [START cloudfunctions_v2alpha_generated_FunctionService_DeleteFunction_sync]
import com.google.cloud.functions.v2alpha.DeleteFunctionRequest;
import com.google.cloud.functions.v2alpha.FunctionName;
import com.google.cloud.functions.v2alpha.FunctionServiceClient;
import com.google.protobuf.Empty;

public class SyncDeleteFunction {

  public static void main(String[] args) throws Exception {
    syncDeleteFunction();
  }

  public static void syncDeleteFunction() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (FunctionServiceClient functionServiceClient = FunctionServiceClient.create()) {
      DeleteFunctionRequest request =
          DeleteFunctionRequest.newBuilder()
              .setName(FunctionName.of("[PROJECT]", "[LOCATION]", "[FUNCTION]").toString())
              .build();
      functionServiceClient.deleteFunctionAsync(request).get();
    }
  }
}
// [END cloudfunctions_v2alpha_generated_FunctionService_DeleteFunction_sync]

redpajama_set_name: RedPajamaGithub


text:
/*
 * This file is part of the swblocks-baselib library.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef __UTESTS_TESTFSUTILS_H_
#define __UTESTS_TESTFSUTILS_H_

#include <baselib/core/OS.h>
#include <baselib/core/FsUtils.h>
#include <baselib/core/BaseIncludes.h>
#include <baselib/core/PathUtils.h>
#include <baselib/core/Logging.h>
#include <baselib/core/TlsState.h>
#include <baselib/core/CPP.h>

#include <utests/baselib/TestUtils.h>

#include <algorithm>
#include <random>
#include <cstddef>

namespace utest
{
    /**
     * class TestFsUtilsT
     */

    template
    <
        typename E = void
    >
    class TestFsUtilsT
    {
    private:

        typedef std::vector< bl::fs::path >                                     list_t;
        typedef std::vector< std::pair< bl::fs::path, std::uint64_t > >         fileList_t;
        typedef std::vector< std::pair< bl::fs::path, bl::fs::path > >          symlinkList_t;

        bool                m_supportLargeFiles;
        bool                m_supportLongFileNames;

        list_t              m_fixedDirTree;
        fileList_t          m_fixedFilePaths;
        symlinkList_t       m_fixedDirSymlinkPaths;
        symlinkList_t       m_fixedFileSymlinkPaths;

    public:

        TestFsUtilsT()
            :
            m_supportLargeFiles( false ),
            m_supportLongFileNames( true )
        {
        }

        void createDummyTestDir( SAA_in const bl::fs::path& root )
        {
            initFixedDirStructure();
            createFixedDir( root );
        }

        void enableLargeFileSupport( SAA_in const bool enable)
        {
            m_supportLargeFiles = enable;
        }

        void enableLongFileNames( SAA_in const bool enable )
        {
            m_supportLongFileNames = enable;
        }

        static bool compareFolders(
             SAA_in              const bl::fs::path&     left,
             SAA_in              const bl::fs::path&     right
             )
        {
            const auto printFolders = [](
                SAA_in              const bl::fs::path&     left,
                SAA_in              const bl::fs::path&     right,
                SAA_in              const bool              isSimilar
                )
            {
                const auto getFileList = []( SAA_in const bl::fs::path& path )
                    -> std::string
                {
                    bl::cpp::SafeOutputStringStream oss;
                    for( const auto& elem: path )
                    {
                        oss
                            << "["
                            << elem.string()
                            << "]\n";
                    }
                    return oss.str();
                };

                if ( ! isSimilar )
                {
                    BL_LOG(
                        bl::Logging::debug(),
                        BL_MSG()
                            << "\nFolders are different\n"
                            << "Left folder : ["
                            << left
                            << "]\nRight folder: ["
                            << right
                            << "]\nLeft folder files:\n"
                            << getFileList( left )
                            << "Right folder files:\n"
                            << getFileList( right )
                        );
                }
            };

            bool isSimilar = true;

            if( exists( left ) && exists( right ) && is_directory( left ) && is_directory( right ) )
            {
                list_t leftVec, rightVec;

                copy( bl::fs::directory_iterator( left ), bl::fs::directory_iterator(), back_inserter( leftVec ) );
                copy( bl::fs::directory_iterator( right ), bl::fs::directory_iterator(), back_inserter( rightVec ) );

                isSimilar = isSimilar && ( leftVec.size() == rightVec.size() );

                if( ! isSimilar)
                {
                    printFolders( left, right, isSimilar );
                    return isSimilar;
                }

                sort( leftVec.begin(), leftVec.end() );
                sort( rightVec.begin(), rightVec.end() );

                auto leftIter = leftVec.begin();
                auto rightIter = rightVec.begin();

                for( ; leftIter != leftVec.end() && rightIter != rightVec.end(); ++leftIter, ++rightIter )
                {
                    if( is_directory( *leftIter ) )
                    {
                        isSimilar = isSimilar &&
                            ( leftIter->filename() == rightIter->filename() ) &&
                            compareFolders( *leftIter, *rightIter );
                    }
                    else if( is_regular_file( *leftIter ) )
                    {
                        isSimilar = isSimilar && compareFileContents( *leftIter, *rightIter );
                    }
                    else if( is_symlink( *leftIter ) )
                    {
                        isSimilar = isSimilar &&
                            ( read_symlink( *leftIter ).filename() == read_symlink( *rightIter ).filename() );
                    }

                    if( ! isSimilar )
                    {
                        BL_LOG(
                            bl::Logging::debug(),
                            BL_MSG()
                                << "TestFsUtils: Comparison failed "
                                << *leftIter
                                << " "
                                << *rightIter
                            );

                        break;
                    }
                }
            }

            printFolders( left, right, isSimilar );
            return isSimilar;
        }

        static bool compareFileContents(
             SAA_in              const bl::fs::path&     leftPath,
             SAA_in              const bl::fs::path&     rightPath,
             SAA_in_opt          const bool              ignoreTimestamp = false,
             SAA_in_opt          const bool              ignoreName = false
             )
        {
            bool isSimilar = false;

            if( exists( leftPath ) && exists( rightPath ) && is_regular_file( leftPath ) && is_regular_file( rightPath ) )
            {
                isSimilar =
                    ( ignoreName || ( leftPath.filename() == rightPath.filename() ) ) &&
                    ( file_size( leftPath ) == file_size( rightPath ) ) &&
                    ( ignoreTimestamp || ( last_write_time( leftPath ) == last_write_time( rightPath ) ) );

                if( ! isSimilar )
                {
                    BL_LOG(
                        bl::Logging::debug(),
                        BL_MSG()
                            << "TestFsUtils: File Metadata Comparison failed "
                            << leftPath
                            << " "
                            << rightPath
                        );
                }

                bl::fs::SafeInputFileStreamWrapper leftFileWrapper( leftPath );
                auto& leftFile = leftFileWrapper.stream();
                leftFile.seekg( 0, std::ios::end );

                bl::fs::SafeInputFileStreamWrapper rightFileWrapper( rightPath );
                auto& rightFile = rightFileWrapper.stream();
                rightFile.seekg( 0, std::ios::end );

                if( leftFile.good() && rightFile.good() )
                {
                    const auto leftSize = leftFile.tellg();
                    const auto rightSize = rightFile.tellg();
                    isSimilar = isSimilar && ( leftSize == rightSize );

                    if( isSimilar && leftSize > 0 )
                    {
                        const auto readSize = ( std::size_t ) std::min< decltype( leftSize ) >( 1024U, leftSize );
                        const auto leftContents = bl::cpp::SafeUniquePtr< char[] >::attach( new char[ readSize ] );
                        const auto rightContents = bl::cpp::SafeUniquePtr< char[] >::attach( new char[ readSize ] );

                        leftFile.seekg( 0, std::ios::beg );
                        rightFile.seekg( 0, std::ios::beg );
                        leftFile.read( leftContents.get(), readSize );
                        rightFile.read( rightContents.get(), readSize );

                        std::size_t counter = readSize - 1;

                        while( counter && isSimilar )
                        {
                            isSimilar = isSimilar && ( leftContents.get()[ counter ] == rightContents.get()[ counter ] );
                            --counter;
                        }
                    }
                }
            }

            return isSimilar;
        }

        static void createDummyFile(
             SAA_in              const bl::fs::path&        path,
             SAA_in              const std::uint64_t        fileSize
             )
        {
            const unsigned char pattern[] = { 1, 2, 3, 4, 5 };
            const auto outfile = bl::os::fopen( path, "wb" );

            if( fileSize > 0 )
            {
                std::uint64_t pos = fileSize > BL_ARRAY_SIZE( pattern ) ? fileSize - BL_ARRAY_SIZE( pattern ) : 0U;
                const auto writeSize = ( std::size_t ) std::min< decltype( fileSize ) >( fileSize, BL_ARRAY_SIZE( pattern ) );
                bl::os::fseek( outfile, pos, SEEK_SET );
                bl::os::fwrite( outfile, pattern , writeSize );
            }
        }

    private:

        void initFixedDirStructure()
        {
            m_fixedDirTree.clear();
            m_fixedFilePaths.clear();
            m_fixedDirSymlinkPaths.clear();
            m_fixedFileSymlinkPaths.clear();
            bl::fs::path basePath( "foo" );
            bl::fs::path barPath( basePath / "bar" );
            bl::fs::path normalFilePath( barPath / "normalFile.bin" );

            m_fixedDirTree.push_back( basePath );
            m_fixedDirTree.push_back( barPath );
            m_fixedDirTree.push_back( basePath / "emptyDirectory" );
            m_fixedDirTree.push_back( barPath / " DirName with Spaces" );
            m_fixedDirTree.push_back( barPath / "DirNameWithOne Space" );
            m_fixedDirTree.push_back( barPath / "DirNameWith'!£$%^&_-@;,.(WinRestrictedSpecialCharacters)" );
            m_fixedDirTree.push_back( barPath / L"DirNameWithUnicode\u263A" );

            if( bl::os::onUNIX() )
            {
                m_fixedDirTree.push_back( barPath / "DirNameWith\"quotes\" " );
                m_fixedDirTree.push_back( barPath / "DirNameWith'!£$%^&*_-@;:<>,.?|(SpecialCharacters)" );
            }

            /*
             * TODO: UTF8 dir names
             */

            m_fixedFilePaths.push_back( std::make_pair( basePath / "zeroSizeFile.bin", 0U ) );
            m_fixedFilePaths.push_back( std::make_pair( normalFilePath, 20U * 1024U ) );
            m_fixedFilePaths.push_back( std::make_pair( barPath / "oneChunkFile.bin", 510U * 1024U ) );
            m_fixedFilePaths.push_back( std::make_pair( barPath / "chunkSizedFile.bin", 512U * 1024U ) );
            m_fixedFilePaths.push_back( std::make_pair( barPath / "multipleChunkFile.bin", 2U * 512U * 1024U ) );
            m_fixedFilePaths.push_back( std::make_pair( barPath / " FileName with Spaces.bin", 20U * 1024U ) );
            m_fixedFilePaths.push_back( std::make_pair( barPath / "FileNameWithOne Space.bin", 20U * 1024U ) );
            m_fixedFilePaths.push_back( std::make_pair( barPath / "FileNameWith'!£$%^&_-@;,.(WinRestrictedSpecialCharacters).bin", 20U * 1024U ) );
            m_fixedFilePaths.push_back( std::make_pair( barPath / L"FileNameWithUnicode\u263A.bin", 20U * 1024U ) );

            if( bl::os::onUNIX() )
            {
                m_fixedFilePaths.push_back( std::make_pair( barPath / "FileNameWith\"quotes\".bin", 20U * 1024U ) );
                m_fixedFilePaths.push_back( std::make_pair( barPath / "FileNameWith'!£$%^&*_-@;:<>,.?|(SpecialCharacters).bin", 20U * 1024U ) );
            }

            if( m_supportLargeFiles )
            {
                std::uint64_t fileSize = 0;
                fileSize += 1024U * 1024U;
                fileSize *= 1024U;
                fileSize *= 5U;
                m_fixedFilePaths.push_back( std::make_pair( barPath / "LargeFile.bin", fileSize ) );
            }

            if( bl::os::onUNIX() )
            {
                m_fixedDirSymlinkPaths.push_back( std::make_pair( barPath, basePath / "linkToBar" ) );
                m_fixedDirSymlinkPaths.push_back( std::make_pair( basePath / "emptyDirectory", basePath / "linkToEmpty" ) );
                m_fixedFileSymlinkPaths.push_back( std::make_pair( normalFilePath, basePath / "linkToNormal.bin" ) );
            }
        }

        void createFixedDir( SAA_in const bl::fs::path& path ) const
        {
            for( auto dirIter = m_fixedDirTree.begin(); dirIter != m_fixedDirTree.end(); ++dirIter )
            {
                bl::fs::safeCreateDirectory( path / * dirIter);
            }

            for( auto fileIter = m_fixedFilePaths.begin(); fileIter != m_fixedFilePaths.end(); ++fileIter )
            {
                createDummyFile( path / fileIter -> first, fileIter -> second );
            }

            if( bl::os::onWindows() && m_supportLongFileNames )
            {
                bl::fs::path longPath( path );

                for( std::size_t i = 0; i < 400; ++i )
                {
                    longPath /= "LongName";
                    bl::fs::safeCreateDirectory( longPath );
                }

                longPath /= "LongFileName.bin";
                createDummyFile( longPath, 20U * 1024U );
            }

            if( bl::os::onUNIX() )
            {
                for( auto dirSymlinkIter = m_fixedDirSymlinkPaths.begin(); dirSymlinkIter != m_fixedDirSymlinkPaths.end(); ++dirSymlinkIter )
                {
                    bl::fs::create_directory_symlink( path / dirSymlinkIter -> first, path / dirSymlinkIter -> second );
                }

                for( auto fileSymlinkIter = m_fixedFileSymlinkPaths.begin(); fileSymlinkIter != m_fixedFileSymlinkPaths.end(); ++fileSymlinkIter )
                {
                    bl::fs::create_symlink( path / fileSymlinkIter -> first, path / fileSymlinkIter -> second );
                }
            }
        }
    };

    typedef TestFsUtilsT<> TestFsUtils;

} // utest

#endif /* __UTESTS_TESTFSUTILS_H_ */


text:
package hudson.ivy;

import java.util.List;

import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.TaskListener;

/**
 * Represents a dependency that never triggers a downstream build.
 *
 * Used to represent the association between an Ivy Project configured to build
 * its modules as separate jobs and downstream projects depending on its
 * modules. This is required to make downstream projects behave properly when
 * they have their "Block build when upstream project is building" option
 * enabled.
 *
 * @author tbingaman
 */
public class IvyVirtualDependency extends IvyDependency {

    public IvyVirtualDependency(AbstractProject<?, ?> upstream, AbstractProject<?, ?> downstream) {
        super(upstream, downstream);
    }

    @Override
    public boolean shouldTriggerBuild(AbstractBuild build, TaskListener listener, List<Action> actions) {
        return false;
    }

}


text: kive is a high property keep alive http serve , fullfilled by python


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Fixture\Factory;

use Sylius\Bundle\CoreBundle\Fixture\OptionsResolver\LazyOption;
use Sylius\Component\Addressing\Model\ZoneInterface;
use Sylius\Component\Channel\Factory\ChannelFactoryInterface;
use Sylius\Component\Core\Formatter\StringInflector;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ShopBillingData;
use Sylius\Component\Currency\Model\CurrencyInterface;
use Sylius\Component\Locale\Model\LocaleInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ChannelExampleFactory extends AbstractExampleFactory implements ExampleFactoryInterface
{
    /** @var ChannelFactoryInterface */
    private $channelFactory;

    /** @var RepositoryInterface */
    private $localeRepository;

    /** @var RepositoryInterface */
    private $currencyRepository;

    /** @var RepositoryInterface */
    private $zoneRepository;

    /** @var \Faker\Generator */
    private $faker;

    /** @var OptionsResolver */
    private $optionsResolver;

    public function __construct(
        ChannelFactoryInterface $channelFactory,
        RepositoryInterface $localeRepository,
        RepositoryInterface $currencyRepository,
        RepositoryInterface $zoneRepository
    ) {
        $this->channelFactory = $channelFactory;
        $this->localeRepository = $localeRepository;
        $this->currencyRepository = $currencyRepository;
        $this->zoneRepository = $zoneRepository;

        $this->faker = \Faker\Factory::create();
        $this->optionsResolver = new OptionsResolver();

        $this->configureOptions($this->optionsResolver);
    }

    /**
     * {@inheritdoc}
     */
    public function create(array $options = []): ChannelInterface
    {
        $options = $this->optionsResolver->resolve($options);

        /** @var ChannelInterface $channel */
        $channel = $this->channelFactory->createNamed($options['name']);
        $channel->setCode($options['code']);
        $channel->setHostname($options['hostname']);
        $channel->setEnabled($options['enabled']);
        $channel->setColor($options['color']);
        $channel->setDefaultTaxZone($options['default_tax_zone']);
        $channel->setTaxCalculationStrategy($options['tax_calculation_strategy']);
        $channel->setThemeName($options['theme_name']);
        $channel->setContactEmail($options['contact_email']);
        $channel->setSkippingShippingStepAllowed($options['skipping_shipping_step_allowed']);
        $channel->setSkippingPaymentStepAllowed($options['skipping_payment_step_allowed']);
        $channel->setAccountVerificationRequired($options['account_verification_required']);

        $channel->setDefaultLocale($options['default_locale']);
        foreach ($options['locales'] as $locale) {
            $channel->addLocale($locale);
        }

        $channel->setBaseCurrency($options['base_currency']);
        foreach ($options['currencies'] as $currency) {
            $channel->addCurrency($currency);
        }

        if (isset($options['shop_billing_data']) && null !== $options['shop_billing_data']) {
            $shopBillingData = new ShopBillingData();
            $shopBillingData->setCompany($options['shop_billing_data']['company'] ?? null);
            $shopBillingData->setTaxId($options['shop_billing_data']['tax_id'] ?? null);
            $shopBillingData->setCountryCode($options['shop_billing_data']['country_code'] ?? null);
            $shopBillingData->setStreet($options['shop_billing_data']['street'] ?? null);
            $shopBillingData->setCity($options['shop_billing_data']['city'] ?? null);
            $shopBillingData->setPostcode($options['shop_billing_data']['postcode'] ?? null);

            $channel->setShopBillingData($shopBillingData);
        }

        return $channel;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefault('name', function (Options $options): string {
                return $this->faker->words(3, true);
            })
            ->setDefault('code', function (Options $options): string {
                return StringInflector::nameToCode($options['name']);
            })
            ->setDefault('hostname', function (Options $options): string {
                return $options['code'] . '.localhost';
            })
            ->setDefault('color', function (Options $options): string {
                return $this->faker->colorName;
            })
            ->setDefault('enabled', function (Options $options): bool {
                return $this->faker->boolean(90);
            })
            ->setAllowedTypes('enabled', 'bool')
            ->setDefault('skipping_shipping_step_allowed', false)
            ->setAllowedTypes('skipping_shipping_step_allowed', 'bool')
            ->setDefault('skipping_payment_step_allowed', false)
            ->setAllowedTypes('skipping_payment_step_allowed', 'bool')
            ->setDefault('account_verification_required', true)
            ->setAllowedTypes('account_verification_required', 'bool')
            ->setDefault('default_tax_zone', LazyOption::randomOne($this->zoneRepository))
            ->setAllowedTypes('default_tax_zone', ['null', 'string', ZoneInterface::class])
            ->setNormalizer('default_tax_zone', LazyOption::findOneBy($this->zoneRepository, 'code'))
            ->setDefault('tax_calculation_strategy', 'order_items_based')
            ->setAllowedTypes('tax_calculation_strategy', 'string')
            ->setDefault('default_locale', function (Options $options): LocaleInterface {
                return $this->faker->randomElement($options['locales']);
            })
            ->setAllowedTypes('default_locale', ['string', LocaleInterface::class])
            ->setNormalizer('default_locale', LazyOption::findOneBy($this->localeRepository, 'code'))
            ->setDefault('locales', LazyOption::all($this->localeRepository))
            ->setAllowedTypes('locales', 'array')
            ->setNormalizer('locales', LazyOption::findBy($this->localeRepository, 'code'))
            ->setDefault('base_currency', function (Options $options): CurrencyInterface {
                return $this->faker->randomElement($options['currencies']);
            })
            ->setAllowedTypes('base_currency', ['string', CurrencyInterface::class])
            ->setNormalizer('base_currency', LazyOption::findOneBy($this->currencyRepository, 'code'))
            ->setDefault('currencies', LazyOption::all($this->currencyRepository))
            ->setAllowedTypes('currencies', 'array')
            ->setNormalizer('currencies', LazyOption::findBy($this->currencyRepository, 'code'))
            ->setDefault('theme_name', null)
            ->setDefault('contact_email', null)
            ->setDefault('shop_billing_data', null)
        ;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>CLUSTER</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.0.10 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="SQL Commands"
HREF="sql-commands.html"><LINK
REL="PREVIOUS"
TITLE="CLOSE"
HREF="sql-close.html"><LINK
REL="NEXT"
TITLE="COMMENT"
HREF="sql-comment.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2012-09-19T22:08:45">

PostgreSQL 9.0.10 Documentation

Prev	Up		Next

CLUSTER

Name
CLUSTER -- cluster a table according to an index

Synopsis

CLUSTER [VERBOSE] <TT
CLASS="REPLACEABLE"
>table_name</TT
> [ USING <TT
CLASS="REPLACEABLE"
>index_name</TT
> ]
CLUSTER [VERBOSE]

Description

   <TT
CLASS="COMMAND"
>CLUSTER</TT
> instructs PostgreSQL
   to cluster the table specified
   by <TT
CLASS="REPLACEABLE"
>table_name</TT
>
   based on the index specified by
   <TT
CLASS="REPLACEABLE"
>index_name</TT
>. The index must
   already have been defined on
   <TT
CLASS="REPLACEABLE"
>table_name</TT
>.

   When a table is clustered, it is physically reordered
   based on the index information. Clustering is a one-time operation:
   when the table is subsequently updated, the changes are
   not clustered.  That is, no attempt is made to store new or
   updated rows according to their index order.  (If one wishes, one can
   periodically recluster by issuing the command again.  Also, setting
   the table's <TT
CLASS="LITERAL"
>FILLFACTOR</TT
> storage parameter to less than
   100% can aid in preserving cluster ordering during updates, since updated
   rows are kept on the same page if enough space is available there.)

   When a table is clustered, PostgreSQL
   remembers which index it was clustered by.  The form
   <TT
CLASS="COMMAND"
>CLUSTER <TT
CLASS="REPLACEABLE"
>table_name</TT
></TT
>
   reclusters the table using the same index as before.  You can also
   use the <TT
CLASS="LITERAL"
>CLUSTER</TT
> or <TT
CLASS="LITERAL"
>SET WITHOUT CLUSTER</TT
>
   forms of ALTER TABLE to set the index to be used for
   future cluster operations, or to clear any previous setting.

   <TT
CLASS="COMMAND"
>CLUSTER</TT
> without any parameter reclusters all the
   previously-clustered tables in the current database that the calling user
   owns, or all such tables if called by a superuser.  This
   form of <TT
CLASS="COMMAND"
>CLUSTER</TT
> cannot be executed inside a transaction
   block.

   When a table is being clustered, an <TT
CLASS="LITERAL"
>ACCESS
   EXCLUSIVE</TT
> lock is acquired on it. This prevents any other
   database operations (both reads and writes) from operating on the
   table until the <TT
CLASS="COMMAND"
>CLUSTER</TT
> is finished.

Parameters

<TT
CLASS="REPLACEABLE"
>table_name</TT
>

      The name (possibly schema-qualified) of a table.

<TT
CLASS="REPLACEABLE"
>index_name</TT
>

      The name of an index.

<TT
CLASS="LITERAL"
>VERBOSE</TT
>

      Prints a progress report as each table is clustered.

Notes

    In cases where you are accessing single rows randomly
    within a table, the actual order of the data in the
    table is unimportant. However, if you tend to access some
    data more than others, and there is an index that groups
    them together, you will benefit from using <TT
CLASS="COMMAND"
>CLUSTER</TT
>.
    If you are requesting a range of indexed values from a table, or a
    single indexed value that has multiple rows that match,
    <TT
CLASS="COMMAND"
>CLUSTER</TT
> will help because once the index identifies the
    table page for the first row that matches, all other rows
    that match are probably already on the same table page,
    and so you save disk accesses and speed up the query.

    During the cluster operation, a temporary copy of the table is created
    that contains the table data in the index order.  Temporary copies of
    each index on the table are created as well.  Therefore, you need free
    space on disk at least equal to the sum of the table size and the index
    sizes.

    Because <TT
CLASS="COMMAND"
>CLUSTER</TT
> remembers the clustering information,
    one can cluster the tables one wants clustered manually the first time, and
    setup a timed event similar to <TT
CLASS="COMMAND"
>VACUUM</TT
> so that the tables
    are periodically reclustered.

    Because the planner records statistics about the ordering of
    tables, it is advisable to run ANALYZE
    on the newly clustered table.
    Otherwise, the planner might make poor choices of query plans.

    There is another way to cluster data. The
    <TT
CLASS="COMMAND"
>CLUSTER</TT
> command reorders the original table by
    scanning it using the index you specify. This can be slow
    on large tables because the rows are fetched from the table
    in index order, and if the table is disordered, the
    entries are on random pages, so there is one disk page
    retrieved for every row moved. (PostgreSQL has
    a cache, but the majority of a big table will not fit in the cache.)
    The other way to cluster a table is to use:

CREATE TABLE <TT
CLASS="REPLACEABLE"
>newtable</TT
> AS
    SELECT * FROM <TT
CLASS="REPLACEABLE"
>table</TT
> ORDER BY <TT
CLASS="REPLACEABLE"
>columnlist</TT
>;

    which uses the PostgreSQL sorting code
    to produce the desired order;
    this is usually much faster than an index scan for disordered data.
    Then you drop the old table, use
    <TT
CLASS="COMMAND"
>ALTER TABLE ... RENAME</TT
>
    to rename <TT
CLASS="REPLACEABLE"
>newtable</TT
> to the
    old name, and recreate the table's indexes.
    The big disadvantage of this approach is that it does not preserve
    OIDs, constraints, foreign key relationships, granted privileges, and
    other ancillary properties of the table — all such items must be
    manually recreated.  Another disadvantage is that this way requires a sort
    temporary file about the same size as the table itself, so peak disk usage
    is about three times the table size instead of twice the table size.

Examples

   Cluster the table <TT
CLASS="LITERAL"
>employees</TT
> on the basis of
   its index <TT
CLASS="LITERAL"
>employees_ind</TT
>:

CLUSTER employees USING employees_ind;

   Cluster the <TT
CLASS="LITERAL"
>employees</TT
> table using the same
   index that was used before:

CLUSTER employees;

   Cluster all tables in the database that have previously been clustered:

CLUSTER;

Compatibility

   There is no <TT
CLASS="COMMAND"
>CLUSTER</TT
> statement in the SQL standard.

   The syntax

CLUSTER <TT
CLASS="REPLACEABLE"
>index_name</TT
> ON <TT
CLASS="REPLACEABLE"
>table_name</TT
>

  is also supported for compatibility with pre-8.3 PostgreSQL
  versions.

See Also
clusterdb

Prev	Home	Next

CLOSE	Up	COMMENT


text:
if (typeof (WScript) != "undefined") {
  WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js", "self");
}

var tests = {
  // Note: each test has name (string) and body (function) properties.
  //       Success is when the body does not throw, failure -- when it throws.

  test01: {
    name: "8.12.9.4.a (variation 1): define generic property, check default attrbitues",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo02";
      var pd = {};
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: undefined, configurable: false, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test02: {
    name: "8.12.9.4.a (variation 2): define data property, check default attrbitues",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo03";
      var pd = { value: 0 };
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: 0, configurable: false, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test03: {
    name: "8.12.9.4.a (variation 3): define generic property by specifying some attributes, check attrbitues",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo02_v3";
      var pd = { configurable: true, writable: false };
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: undefined, configurable: true, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test04: {
    name: "8.12.9.4.b: define accessor property, check default attrbitues",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo04";
      var getter = function () { return this.Value };
      var pd = { get: getter };
      Object.defineProperty(o, propertyName, pd);
      var expected = { get: getter, set: undefined, configurable: false, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test05: {
    name: "8.12.9.5: re-define property: use descriptor with all fields absent, check that nothing happens to previous descriptor",
    body: function () {
      var propertyName = "foo05";
      var o = { foo05: 1 };
      var pd = {};
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: true, value: 1, configurable: true, enumerable: true };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test06: {
    name: "8.12.9.6: re-define property: use equal descriptor with data field, check that nothing happens to previous descriptor",
    body: function () {
      var propertyName = "foo06";
      var o = { foo06: 1 };
      var pd = { value: 1 };
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: true, value: 1, configurable: true, enumerable: true };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  // where we are:
  // - re-define
  // - desc is not empty
  // - desc and current are not the same

  test07: {
    name: "8.12.9.7.a: re-define property: current descriptor is not configurable and descriptor is configurable, check that it throws TypeError",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo07";
      var pd = { value: 0, configurable: false };
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 1, configurable: true };
      assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError);
    }
  },

  test08: {
    name: "8.12.9.7.b (variation 1): re-define property: current descriptor is not configurable and descriptor enumerable is specified and it's negation of current enumerable, check that it throws TypeError",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo08";
      var pd = { value: 0 };
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 1, enumerable: true };
      assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError);
    }
  },

  test09: {
    name: "8.12.9.7.b (variation 2): re-define property: current descriptor is not configurable and descriptor enumerable is not specified, check that it does not throw",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo09";
      var pd = { value: 0, writable: true }; // set writable to true to avoid throw code path.
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 1, writable: false };
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: 1, configurable: false, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test10: {
    name: "8.12.9.7.b (variation 3): re-define property: current descriptor is not configurable and descriptor enumerable is same as current enumerable, check that it does not throw",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo10";
      var pd = { value: 0, writable: true }; // set writable to true to avoid throw code path.
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 1, enumerable: false, writable: false };
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: 1, configurable: false, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test11: {
    name: "8.12.9.8: re-define property: descriptor is not empty, generic and is different from current",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo11";
      var pd = { value: 0, configurable: true };
      Object.defineProperty(o, propertyName, pd);
      pd = { enumerable: true }; // change enumerable to make sure that descriptor is diferent from current.
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: 0, configurable: true, enumerable: true };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  // where we are:
  // - re-define
  // - desc is not empty
  // - desc and current are not the same
  // - descriptor.IsData != current.IsData

  test12: {
    name: "8.12.9.9.a: re-define property: descriptor.IsData != current.IsData and current is not configurable, check that it throws TypeError",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo12";
      var pd = { value: 0, configurable: false };
      Object.defineProperty(o, propertyName, pd);
      pd = { get: function () { return this.Value; } };
      assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError);
    }
  },

  test13: {
    name: "8.12.9.9.b (variation 1): re-define property: convert from data to accessor descriptor, check that configurable/enumerable (true) are preserved",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo13";
      var pd = { value: 0, configurable: true, enumerable: true };
      Object.defineProperty(o, propertyName, pd);
      var getter = function() { return this.Value; };
      pd = { get: getter };
      Object.defineProperty(o, propertyName, pd);
      var expected = { get: getter, set: undefined, configurable: true, enumerable: true };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test14: {
    name: "8.12.9.9.b (variation 2): re-define property: convert from data to accessor descriptor, check that enumerable (false) is preserved",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo14";
      var pd = { value: 0, configurable: true, enumerable: false };
      Object.defineProperty(o, propertyName, pd);
      var getter = function () { return this.Value; };
      pd = { get: getter };
      Object.defineProperty(o, propertyName, pd);
      var expected = { get: getter, set: undefined, configurable: true, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test15: {
    name: "8.12.9.9.b (variation 3): re-define property: convert from data to accessor descriptor, check that configurable/enumerable not preserved when specified by descriptor",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo15";
      var pd = { value: 0, configurable: true, enumerable: true };
      Object.defineProperty(o, propertyName, pd);
      var getter = function () { return this.Value; };
      pd = { get: getter, configurable: false };
      Object.defineProperty(o, propertyName, pd);
      var expected = { get: getter, set: undefined, configurable: false, enumerable: true };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test16: {
    name: "8.12.9.9.c (variation 1): re-define property: convert from accessor to data descriptor, check that configurable/enumerable (true) are preserved",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo16";
      var pd = {
        set: function (arg) { helpers.writeln("setter was called"); this.Value = arg; },
        configurable: true,
        enumerable: true
      };
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 1 };
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: 1, configurable: true, enumerable: true };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test17: {
    name: "8.12.9.9.c (variation 2): re-define property: convert from accessor to data descriptor, check that enumerable (false) is preserved",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo17";
      var pd = {
        set: function (arg) { helpers.writeln("setter was called"); this.Value = arg; },
        configurable: true,
        enumerable: false
      };
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 1 };
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: 1, configurable: true, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test18: {
    name: "8.12.9.9.c (variation 3): re-define property: convert from accessor to data descriptor, check that configurable/enumerable (true/false) not preserved when specified by descriptor (false/absent)",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo18";
      var pd = {
        set: function (arg) { helpers.writeln("setter was called"); this.Value = arg; },
        configurable: true,
        enumerable: false
      };
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 1, configurable: false };
      Object.defineProperty(o, propertyName, pd);
      // expected: configurable/enumerable = false/false.
      var expected = { writable: false, value: 1, configurable: false, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test19: {
    name: "8.12.9.9.c (variation 4): re-define property: convert from accessor to data descriptor, check that configurable/enumerable (true/true) not preserved when specified by descriptor (absent/false)",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo19";
      var pd = {
        set: function (arg) { helpers.writeln("setter was called"); this.Value = arg; },
        configurable: true,
        enumerable: true
      };
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 1, enumerable: false };
      Object.defineProperty(o, propertyName, pd);
      // expected: configurable/enumerable = true/false.
      var expected = { writable: false, value: 1, configurable: true, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  // where we are:
  // - re-define
  // - desc is not empty
  // - desc and current are not the same
  // - descriptor is data, current is data

  test20: {
    name: "8.12.9.10.a (variation 1): re-define data property: current is not configurable/not writable and descriptor writable is absent/value is same",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo20";
      var pd = { value: 1 };
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 1 };
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: 1, configurable: false, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test21: {
    name: "8.12.9.10.a.i: re-define data property: current is not configurable/not writable and descriptor is writable, check that it throws TypeError",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo21";
      var pd = { value: 1 };
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 2, writable: true };
      assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError);
      return true;
    }
  },

  test22: {
    name: "8.12.9.10.a.ii: re-define data property: current is not configurable/not writable and descriptor writable is false and value is different, check that it throws TypeError",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo22";
      var pd = { value: 1 };
      Object.defineProperty(o, propertyName, pd);
      pd = { value: 2, writable: false };
      assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError);
    }
  },

  test23: {
    name: "8.12.9.10.a (variation 2): re-define data property: current is configurable",
    body: function () {
      var propertyName = "foo23";
      var o = { foo23: 1 };
      var pd = { value: 2, writable: false };
      Object.defineProperty(o, propertyName, pd);
      var expected = { writable: false, value: 2, configurable: true, enumerable: true };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

// where we are:
// - re-define
// - desc is not empty
// - desc and current are not the same
// - descriptor is accessor, current is accessor

  test24: {
    name: "Test: 8.12.9.11 (variation 1): re-define accessor property: curent configurable is true: valid case",
    body: function () {
      var propertyName = "foo24";
      var o = {
        get foo24() { return this.Value; },
        set foo24(arg) { helpers.writeln("old setter"); this.Value = arg; }
      };
      var newGetter = function() { return 2; };
      var newSetter = function(arg) { helpers.writeln("new setter"); }
      var pd = { get: newGetter, set: newSetter };
      Object.defineProperty(o, propertyName, pd);
      var expected = { get: newGetter,  set: newSetter, configurable: true, enumerable: true };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test25: {
    name: "8.12.9.11.a.i: re-define accessor property: curent configurable is false, descriptor specifies setter as different, expect TypeError",
    body: function () {
      var propertyName = "foo25";
      var o = helpers.getDummyObject();
      var pd = { set: function(arg) { helpers.writeln("old setter"); this.Value = arg; } };
      Object.defineProperty(o, propertyName, pd);

      pd = { set: function(arg) { helpers.writeln("new setter"); } };
      assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError);
    }
  },

  test26: {
    name: "8.12.9.11.a.ii: re-define accessor property: curent configurable is false, descriptor specifies getter as different, expect TypeError",
    body: function () {
      var propertyName = "foo26";
      var o = helpers.getDummyObject();
      var pd = { get: function() { return this.Value; }, };
      Object.defineProperty(o, propertyName, pd);

      pd = { get: function() { helpers.writeln("new getter"); return 2; } };
      assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError);
    }
  },

  test27: {
    name: "8.12.9.11 (variation 2): re-define accessor property: curent configurable is true and no getter, descriptor specifies getter as undefined, setter as same",
    body: function () {
      var propertyName = "foo27";
      var o = helpers.getDummyObject();
      var setter = function(arg) { helpers.writeln("setter") };
      var pd = { set: setter };
      Object.defineProperty(o, propertyName, pd);

      pd = { get: undefined, set: setter };
      Object.defineProperty(o, propertyName, pd);
      var expected = { get: undefined, set: setter, configurable: false, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
    }
  },

  test28: {
    name: "Re-define property from data to accessor property. Make sure that setter is called when setting the value.",
    body: function () {
      // define a data property.
      var propertyName = "foo28";
      var o = helpers.getDummyObject();
      var pd = { value: 1, configurable: true };
      Object.defineProperty(o, propertyName, pd);

      // re-define the property to be accessor property.
      var log = "";
      var getter = function() { log += "getter was called."; return this.Value; }
      var setter = function(arg) { log += "setter was called."; this.Value = arg; };
      pd = { get: getter, set: setter };
      Object.defineProperty(o, propertyName, pd);

      // set the value and get it.
      var newValue = 2;
      o[propertyName] = newValue;
      var actualValue = o[propertyName];

      // validate.
      var expected = { get: getter, set: setter, configurable: true, enumerable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
      assert.areEqual("setter was called.getter was called.", log, "wrong log");
      assert.areEqual(newValue, actualValue, "wrong value");
    }
  },

  test29: {
    name: "Define property 'length' as accessor property on array: check that it throws TypeError.",
    body: function () {
      assert.throws(
        function() { Object.defineProperty([], "length", {configurable: false, get: function() {return 2;}}); },
        TypeError);
      assert.throws(
        function() { Object.defineProperty(Array.prototype, "length", {configurable: false, get: function() {return 2;}}); },
        TypeError);
    }
  },

  // Where we are: some tests for specific issues.
  test30: {
    name: "Define property with getter specified as undefined, then access the property (WOOB bug 1123281)",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo30";
      var pd = { get: undefined };
      Object.defineProperty(o, propertyName, pd);
      assert.areEqual(undefined, o[propertyName]);
    }
  },

  test31: {
    name: "Define property with setter specified as undefined, then set the property (WOOB bug 1123281)",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo31";
      var pd = { set: undefined };
      Object.defineProperty(o, propertyName, pd);
      o[propertyName] = 1; // Make sure this does not throw.
      assert.areEqual(undefined, o[propertyName]); // Just in case try to access the property.
    }
  },

  test32: {
    name: "Convert data to accessor property with getter specified as undefined, then access the property (WOOB bug 1123281)",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo32";
      var pd = { configurable: true, value: 0 };
      Object.defineProperty(o, propertyName, pd);

      pd = { get: undefined };
      Object.defineProperty(o, propertyName, pd);
      assert.areEqual(undefined, o[propertyName]);
    }
  },

  test33: {
    name: "Convert data to accessor property with setter specified as undefined, then set the property (WOOB bug 1123281)",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "foo33";
      var pd = { configurable: true, value: 0 };
      Object.defineProperty(o, propertyName, pd);

      pd = { set: undefined };
      Object.defineProperty(o, propertyName, pd);
      o[propertyName] = 1; // Make sure this does not throw.
      assert.areEqual(undefined, o[propertyName]); // Just in case try to access the property.
    }
  },

  test34: {
    name: "Convert accessor to a data property for non-extensible object (WIN8 bug 463559)",
    body: function () {
      var o = helpers.getDummyObject();
      var propertyName = "x";

      Object.defineProperty(o, propertyName, {
        get: function() { return 0; },
        set: function(val) { helpers.writeln("setter was called although it shouldn't"); },
        configurable: true
      });
      Object.preventExtensions(o);
      var val = 1;
      Object.defineProperty(o, propertyName, { value: val, });

      var expected = { value: val, configurable: true, enumerable: false, writable: false };
      assert.areEqual(expected, Object.getOwnPropertyDescriptor(o, propertyName), "wrong value of getOwnPropertyDescriptor");
      assert.areEqual(val, o[propertyName], "the property value is wrong");
      assert.areEqual(false, Object.isExtensible(o), "isExtensible() changed");
    }
  },

  // Note: this test irreversibly changes the dummy object (that's important when dummy object is document/window),
  //       it should in the very end.
  test_last_01: {
    name: "8.12.9.3: define property for non-extensible object, check that it throws TypeError",
    body: function () {
      var o = helpers.getDummyObject();
      Object.preventExtensions(o);
      var propertyName = "foo01";
      var pd = {};
      assert.throws(function() { Object.defineProperty(o, propertyName, pd); }, TypeError);
    }
  }

}; // tests.

testRunner.runTests(tests);


text:
<?php

namespace Nexucis\Elasticsearch\Helper\Nodowntime;

use Elasticsearch\Client;
use Elasticsearch\Common\Exceptions\InvalidArgumentException;
use Elasticsearch\Common\Exceptions\RuntimeException;
use Nexucis\Elasticsearch\Helper\Nodowntime\Exceptions\IndexAlreadyExistException;
use Nexucis\Elasticsearch\Helper\Nodowntime\Exceptions\IndexNotFoundException;
use Nexucis\Elasticsearch\Helper\Nodowntime\Parameter\SearchParameter;
use stdClass;

/**
 * Class IndexHelper : This class can help you to manage your index with the alias management.
 * According to the official documentation https://www.elastic.co/guide/en/elasticsearch/guide/master/index-aliases.html,
 * alias management allow to use with no downtime your index.
 *
 * @category Elasticsearch Helper
 * @package  Nexucis\Elasticsearch\Helper\Nodowntime
 * @author   Augustin Husson <husson.augustin@gmail.com>
 * @license  MIT
 */
class IndexHelper implements IndexHelperInterface
{

    const INDEX_NAME_CONVENTION_1 = '_v1';
    const INDEX_NAME_CONVENTION_2 = '_v2';

    const RETURN_ACKNOWLEDGE = "ok";

    /**
     * @var Client
     */
    protected $client;

    /**
     * IndexHelper constructor.
     * @param Client $client
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    /**
     * You can pass an alias name or an index name here.
     *
     * @param string $index [REQUIRED]
     * @return bool
     */
    public function existsIndex($index)
    {
        $params = array(
            'index' => $index,
        );

        return $this->client->indices()->exists($params);
    }

    /**
     * @param string $alias [REQUIRED]
     * @return void
     * @throws IndexAlreadyExistException
     */
    public function createIndexByAlias($alias)
    {
        $index = $alias . self::INDEX_NAME_CONVENTION_1;

        if ($this->existsIndex($index)) {
            throw new IndexAlreadyExistException($index);
        }

        $params = array(
            'index' => $index,
            'body' => array(
                'aliases' => array(
                    $alias => new stdClass()
                )),
        );

        $this->client->indices()->create($params);
    }

    /**
     * @param string $alias [REQUIRED]
     * @return void
     * @throws IndexNotFoundException
     */
    public function deleteIndexByAlias($alias)
    {
        if (!$this->existsIndex($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $params = array(
            'index' => $this->findIndexByAlias($alias)
        );

        $this->client->indices()->delete($params);
    }

    /**
     * @param string $aliasSrc [REQUIRED]
     * @param string $aliasDest [REQUIRED]
     * @param string|bool $refresh wait until the result are visible to search
     * @param bool $waitForCompletion : According to the official documentation (https://www.elastic.co/guide/en/elasticsearch/reference/2.4/docs-reindex.html),
     * it is strongly advised to not set this parameter to false with ElasticSearch 2.4. In fact, it would be preferable to create an asynchronous process that executes this task.
     * If you set it to false, don't forget to put an alias to the new index when the corresponding task is gone.
     * @return string : the task ID if the parameter $waitForCompletion is set to false, acknowledge if not
     * @throws IndexAlreadyExistException
     * @throws IndexNotFoundException
     */
    public function copyIndex($aliasSrc, $aliasDest, $refresh = false, $waitForCompletion = true)
    {
        if (!$this->existsAlias($aliasSrc)) {
            throw new IndexNotFoundException($aliasSrc);
        }

        if ($this->existsAlias($aliasDest)) {
            throw new IndexAlreadyExistException($aliasDest);
        }

        $indexSrc = $this->findIndexByAlias($aliasSrc);
        $indexDest = $aliasDest . self::INDEX_NAME_CONVENTION_1;

        $this->copyMappingAndSetting($indexSrc, $indexDest);

        // currently, the reindex api doesn't work when there are no documents inside the index source
        // So if there are some documents to copy and if the reindex Api send an error, we throw a RuntimeException
        if (!$this->indexIsEmpty($indexSrc)) {
            $response = $this->copyDocuments($indexSrc, $indexDest, $refresh, $waitForCompletion);

            if ($waitForCompletion) {
                if (!$response) {
                    $this->deleteIndex($indexDest);
                    throw new RuntimeException('reindex failed');
                }
            } else {
                // return the task ID
                return $response;
            }
        }

        $this->putAlias($aliasDest, $indexDest);

        return self::RETURN_ACKNOWLEDGE;
    }

    /**
     * @param string $alias [REQUIRED]
     * @param string|bool $refresh wait until the result are visible to search
     * @param bool $needToCreateIndexDest
     * @param bool $waitForCompletion : According to the official documentation (https://www.elastic.co/guide/en/elasticsearch/reference/2.4/docs-reindex.html),
     * it is strongly advised to not set this parameter to false with ElasticSearch 2.4.
     * If you set it to false, don't forget to remove the old index and to switch the alias after the task is gone.
     * @return string : the task ID if the parameter $waitForCompletion is set to false, acknowledge if not
     * @throws IndexNotFoundException
     */
    public function reindex($alias, $refresh = false, $needToCreateIndexDest = true, $waitForCompletion = true)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $indexSrc = $this->findIndexByAlias($alias);
        $indexDest = $this->getIndexDest($alias, $indexSrc);

        if ($needToCreateIndexDest) { // for example, if you have updated your settings/mappings, your index_dest is already created. So you don't need to create it again
            if ($this->existsIndex($indexDest)) {
                $this->deleteIndex($indexDest);
            }

            $this->copyMappingAndSetting($indexSrc, $indexDest);
        }

        // currently, the reindex api doesn't work when there are no documents inside the index source
        // So if there are some documents to copy and if the reindex Api send an error, we throw a RuntimeException

        if (!$this->indexIsEmpty($indexSrc)) {
            $response = $this->copyDocuments($indexSrc, $indexDest, $refresh, $waitForCompletion);

            if ($waitForCompletion) {
                if (!$response) {
                    $this->deleteIndex($indexDest);
                    throw new RuntimeException('reindex failed');
                }
            } else {
                // return the task ID
                return $response;
            }
        }

        $this->switchIndex($alias, $indexSrc, $indexDest);
        $this->deleteIndex($indexSrc);

        return self::RETURN_ACKNOWLEDGE;
    }

    /**
     * This method must call when you want to add something inside the settings. Because the reindexation is a long task,
     * you should do the difference between add and delete something inside the settings. In the add task,
     * you don't need to reindex , unlike the delete task
     *
     * @param string $alias [REQUIRED]
     * @param mixed[] $settings [REQUIRED]
     * @return void
     * @throws IndexNotFoundException
     * @throws InvalidArgumentException
     */
    public function addSettings($alias, $settings)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        if (!is_array($settings) || count($settings) === 0) {
            throw new InvalidArgumentException("settings are empty, you are not allowed to add an empty array as the settings.");
        }

        $indexSource = $this->findIndexByAlias($alias);

        $this->closeIndex($indexSource);
        $params = array(
            'index' => $indexSource,
            'body' => array(
                'settings' => $settings
            )
        );

        $this->client->indices()->putSettings($params);

        $this->openIndex($indexSource);
    }

    /**
     * This method must call when you want to delete something inside the settings.
     *
     * @param string $alias [REQUIRED]
     * @param mixed[] $settings [REQUIRED]
     * @param string|bool $refresh wait until the result are visible to search
     * @param bool $needReindexation : The process of reindexation can be so long, instead of calling reindex method inside this method,
     * you may want to call it in an asynchronous process.
     * But if you pass this parameters to false, don't forget to reindex. If you don't do it, you will not see your modification of the settings
     * @param bool $waitForCompletion : According to the official documentation (https://www.elastic.co/guide/en/elasticsearch/reference/2.4/docs-reindex.html),
     * it is strongly advised to not set this parameter to false with ElasticSearch 2.4.
     * If you set it to false, don't forget to remove the old index and to switch the alias after the task is gone.
     * @return string : the task ID if the parameter $waitForCompletion is set to false, acknowledge if not
     * @throws IndexNotFoundException
     */
    public function updateSettings($alias, $settings, $refresh = false, $needReindexation = true, $waitForCompletion = true)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $indexSrc = $this->findIndexByAlias($alias);
        $indexDest = $this->getIndexDest($alias, $indexSrc);

        if ($this->existsIndex($indexDest)) {
            $this->deleteIndex($indexDest);
        }

        $mapping = $this->getMappingsByIndex($indexSrc)[$indexSrc];
        $mappingSource = null;

        if (is_array($mapping) && array_key_exists('mappings', $mapping)) {
            $mappingSource = $mapping['mappings'];
        }

        $params = array(
            'index' => $indexDest,
        );

        if (is_array($settings) && count($settings) > 0) {
            $params['body'] = array(
                'settings' => $settings
            );
        }

        if (is_array($mappingSource) && (count($mappingSource) !== 0)) {
            $this->createBody($params);
            $params['body']['mappings'] = $mappingSource;
        }

        $result = $this->client->indices()->create($params);

        if ($result['acknowledged'] && $needReindexation) {
            return $this->reindex($alias, $refresh, false, $waitForCompletion);
        }

        return self::RETURN_ACKNOWLEDGE;
    }

    /**
     * This method must call whenever you want to add or delete something inside the mappings
     *
     * @param string $alias [REQUIRED]
     * @param mixed[] $mapping [REQUIRED]
     * @param string|bool $refresh wait until the result are visible to search
     * @param bool $needReindexation : The process of reindexation can be so long, instead of calling reindex method inside this method,
     * you may want to call it in an asynchronous process.
     * But if you pass this parameters to false, don't forget to reindex. If you don't do it, you will not see your modification of the mappings
     * @param bool $waitForCompletion : According to the official documentation (https://www.elastic.co/guide/en/elasticsearch/reference/2.4/docs-reindex.html),
     * it is strongly advised to not set this parameter to false with ElasticSearch 2.4.
     * If you set it to false, don't forget to remove the old index and to switch the alias after the task is gone.
     * @param bool $includeTypeName : Indicate if you still use a type in your index. To be ready for the next release (v8), you should consider to set this parameter to false.
     * Which means you have to change your mapping to remove the usage of the type. See more here: https://www.elastic.co/blog/moving-from-types-to-typeless-apis-in-elasticsearch-7-0
     * This parameter will be removed in the next release
     * @return string : the task ID if the parameter $waitForCompletion is set to false, acknowledge if not
     * @throws IndexNotFoundException
     */
    public function updateMappings($alias, $mapping, $refresh = false, $needReindexation = true, $waitForCompletion = true, $includeTypeName = true)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $indexSrc = $this->findIndexByAlias($alias);
        $indexDest = $this->getIndexDest($alias, $indexSrc);
        if ($this->existsIndex($indexDest)) {
            $this->deleteIndex($indexDest);
        }

        $settings = $this->getSettingsByIndex($indexSrc)[$indexSrc]['settings']['index'];

        $params = array(
            'index' => $indexDest,
        );

        if (is_array($mapping) && count($mapping) > 0) {
            $params['body'] = array(
                'mappings' => $mapping,
            );
        }

        $this->copySettings($params, $settings);

        if ($includeTypeName) {
            $params['include_type_name'] = true;
        }

        $result = $this->client->indices()->create($params);

        if ($result['acknowledged'] && $needReindexation) {
            return $this->reindex($alias, $refresh, false, $waitForCompletion);
        }

        return self::RETURN_ACKNOWLEDGE;
    }

    /**
     * @return mixed[]
     */
    public function getListAlias()
    {
        $indices = $this->client->indices()->getAliases();
        $result = array();
        foreach ($indices as $index) {
            foreach ($index['aliases'] as $alias => $params_alias) {
                $result[] = $alias;
            }
        }
        return $result;
    }

    /**
     * @param string $alias [REQUIRED]
     * @return mixed[]
     * @throws IndexNotFoundException
     */
    public function getMappings($alias)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $indexSource = $this->findIndexByAlias($alias);
        $mapping = $this->getMappingsByIndex($indexSource)[$indexSource];

        if (is_array($mapping) && array_key_exists('mappings', $mapping)) {
            return $mapping['mappings'];
        }

        return array();
    }

    /**
     * @param string $alias [REQUIRED]
     * @return mixed[]
     * @throws IndexNotFoundException
     */
    public function getSettings($alias)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $indexSource = $this->findIndexByAlias($alias);
        return $this->getSettingsByIndex($indexSource)[$indexSource]['settings']['index'];
    }

    /**
     * @param string $alias [REQUIRED] the name of the index or the name of the alias
     * @param string $type [REQUIRED] the type of the document
     * @param string|int $id [REQUIRED] the document ID
     * @param bool $refresh
     * @return callable|mixed[]
     * @throws IndexNotFoundException
     */
    public function getDocument($alias, $type, $id, $refresh = false)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $params = array(
            'index' => $alias,
            'type' => $type,
            'id' => $id,
            'refresh' => $refresh
        );

        return $this->client->get($params);
    }

    /**
     * @param string $alias [REQUIRED]
     * @param int $from the offset from the first result you want to fetch (0 by default)
     * @param int $size allows you to configure the maximum amount of hits to be returned. (10 by default)
     * @return callable|mixed[]
     * @throws IndexNotFoundException
     */
    public function getAllDocuments($alias, $from = 0, $size = 10)
    {
        return $this->searchDocuments($alias, null, null, $from, $size);
    }

    /**
     * @param string $alias [REQUIRED]
     * @param mixed[]|null $query
     * @param string $type . This parameter will be removed in the next major release
     * @param int $from the offset from the first result you want to fetch (0 by default)
     * @param int $size allows you to configure the maximum amount of hits to be returned. (10 by default)
     * @return callable|mixed[]
     * @throws IndexNotFoundException
     */
    public function searchDocuments($alias, $query = null, $type = null, $from = 0, $size = 10)
    {
        $body = null;

        if (is_array($query)) {
            $body = array(
                'query' => $query
            );
        }

        return $this->advancedSearchDocument(
            $alias,
            $type,
            $body,
            (new SearchParameter())
                ->from($from)
                ->size($size)
        );
    }

    /**
     * @param string $alias [REQUIRED]
     * @param string $type . This parameter will be removed in the next major release
     * @param mixed[]|null $body
     * @param SearchParameter $searchParameter
     * @return callable|mixed[]
     * @throws IndexNotFoundException
     */
    public function advancedSearchDocument($alias, $type = null, $body = null, $searchParameter = null)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $params = array();

        if ($searchParameter !== null) {
            $params = $searchParameter->build();
        }

        $params['index'] = $alias;

        if ($type !== null) {
            $params['type'] = $type;
        }

        if (is_array($body)) {
            $params['body'] = $body;
        }

        return $this->client->search($params);
    }

    /**
     * @param string $index [REQUIRED] If the alias is associated to an unique index, you can pass an alias rather than an index
     * @param string $id [REQUIRED]
     * @param string $type [REQUIRED]
     * @param mixed[] $body [REQUIRED] : actual document to update
     * @param bool $refresh wait until the result are visible to search
     * @return bool : true if the document has been updated. Otherwise, the document has been created.
     * @throws IndexNotFoundException
     */
    public function updateDocument($index, $id, $type, $body, $refresh = false)
    {
        if (!$this->existsIndex($index)) {
            throw new IndexNotFoundException($index);
        }
        return $this->indexDocument($index, $body, $type, $id) > 1;
    }

    /**
     * @param string $index [REQUIRED] If the alias is associated to an unique index, you can pass an alias rather than an index
     * @param string $id [REQUIRED]
     * @param string $type [REQUIRED]
     * @param mixed[] $body [REQUIRED] : actual document to create
     * @param bool $refresh wait until the result are visible to search
     * @return bool : true if the document has been created.
     * @throws IndexNotFoundException
     */
    public function addDocument($index, $type, $body, $id = null, $refresh = false)
    {
        if (!$this->existsIndex($index)) {
            throw new IndexNotFoundException($index);
        }
        return $this->indexDocument($index, $body, $type, $id, $refresh) === 1;
    }

    /**
     * Remove all documents from the given index seen through its alias
     *
     * @param string $alias [REQUIRED]
     * @return void
     * @throws IndexNotFoundException
     */
    public function deleteAllDocuments($alias)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $indexSrc = $this->findIndexByAlias($alias);
        $indexDest = $this->getIndexDest($alias, $indexSrc);

        if ($this->existsIndex($indexDest)) {
            $this->deleteIndex($indexDest);
        }

        $this->copyMappingAndSetting($indexSrc, $indexDest);

        $this->switchIndex($alias, $indexSrc, $indexDest);

        $this->deleteIndex($indexSrc);
    }

    /**
     * @param string $alias [REQUIRED]
     * @param string $id [REQUIRED]
     * @param string $type [REQUIRED]
     * @param bool $refresh , Refresh the index after performing the operation
     * @return void
     * @throws IndexNotFoundException
     */
    public function deleteDocument($alias, $id, $type, $refresh = false)
    {
        if (!$this->existsAlias($alias)) {
            throw new IndexNotFoundException($alias);
        }

        $params = array(
            'index' => $alias,
            'type' => $type,
            'id' => $id,
            'refresh' => $refresh
        );

        $this->client->delete($params);
    }

    /**
     * @return Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * @param string $index
     * @param string|integer $id
     * @param mixed[] $body
     * @param string $type
     * @param bool $refresh
     * @return mixed
     */
    protected function indexDocument($index, $body, $type, $id = null, $refresh = false)
    {

        $params = array(
            'index' => $index,
            'type' => $type,
            'body' => $body,
            'refresh' => $refresh
        );

        if ($id !== null) {
            $params['id'] = $id;
        }

        $response = $this->client->index($params);

        return $response['_version'];
    }

    /**
     * @param string $index : index can put here [REQUIRED]
     * @return void
     */
    protected function deleteIndex($index)
    {
        $params = array(
            'index' => $index
        );

        $this->client->indices()->delete($params);
    }

    /**
     * @param string $index
     * @return void
     */
    protected function openIndex($index)
    {
        $params = array(
            'index' => $index
        );
        $this->client->indices()->open($params);
    }

    /**
     * @param string $index
     * @return void
     */
    protected function closeIndex($index)
    {
        $params = array(
            'index' => $index
        );
        $this->client->indices()->close($params);
    }

    /**
     * @param string $alias
     * @return string
     */
    protected function findIndexByAlias($alias)
    {
        $params = array(
            'name' => urlencode($alias)
        );
        return array_keys($this->client->indices()->getAlias($params))[0];
    }

    /**
     * @param string $index
     * @return bool : true if the index doesn't have any documents. False otherwise.
     */
    protected function indexIsEmpty($index)
    {
        return $this->countDocuments($index) == 0;
    }

    /**
     * @param string $index
     * @return int
     */
    protected function countDocuments($index)
    {
        $params = array(
            'index' => $index,
        );

        return $this->client->count($params)['count'];
    }

    /**
     * @param string $alias
     * @return bool
     */
    protected function existsAlias($alias)
    {
        $params = array(
            'name' => urlencode($alias)
        );

        return $this->client->indices()->existsAlias($params);
    }

    /**
     * @param string $indexSource
     * @param string $indexDest
     *
     * @return void
     */
    protected function copyMappingAndSetting($indexSource, $indexDest)
    {
        $params = array(
            'index' => $indexDest,
        );

        $mapping = $this->getMappingsByIndex($indexSource)[$indexSource];
        $mappingSource = null;

        if (is_array($mapping) && array_key_exists('mappings', $mapping)) {
            $mappingSource = $mapping['mappings'];
        }

        $settingSource = $this->getSettingsByIndex($indexSource)[$indexSource]['settings']['index'];

        if (is_array($mappingSource) && (count($mappingSource) !== 0)) {
            $this->createBody($params);
            $params['body']['mappings'] = $mappingSource;
        }

        $this->copySettings($params, $settingSource);

        $this->client->indices()->create($params);
    }

    /**
     * @param string[] $params
     * @param mixed[] $settings
     *
     * @return void
     */
    protected function copySettings(&$params, $settings)
    {
        $numberOfShards = null;
        $numberOfReplicas = null;
        $analysisSource = null;

        if (is_array($settings)) {
            if (array_key_exists('number_of_shards', $settings)) {
                $numberOfShards = $settings['number_of_shards'];
            }

            if (array_key_exists('number_of_replicas', $settings)) {
                $numberOfReplicas = $settings['number_of_replicas'];
            }

            if (array_key_exists('analysis', $settings)) {
                $analysisSource = $settings['analysis'];
            }
        }

        if ($numberOfShards !== null) {
            $this->createBody($params);

            $params['body']['settings'] = array(
                'number_of_shards' => $numberOfShards
            );
        }

        if ($numberOfReplicas !== null) {
            $this->createBody($params);

            if (!array_key_exists('settings', $params['body'])) {
                $params['body']['settings'] = array();
            }

            $params['body']['settings']['number_of_replicas'] = $numberOfReplicas;
        }

        if (is_array($analysisSource) && (count($analysisSource) !== 0)) {
            $this->createBody($params);

            if (!array_key_exists('settings', $params['body'])) {
                $params['body']['settings'] = array();
            }

            $params['body']['settings']['analysis'] = $analysisSource;
        }
    }

    /**
     * @param string[] $params
     * @return void
     */
    private function createBody(&$params)
    {
        if (!array_key_exists('body', $params)) {
            $params['body'] = array();
        }
    }

    /**
     * @param string $indexSrc
     * @param string $indexDest
     * @param string|bool $refresh wait until the result are visible to search
     * @param bool $waitForCompletion
     * @return bool | string
     */
    protected function copyDocuments($indexSrc, $indexDest, $refresh = false, $waitForCompletion = true)
    {
        $params = array(
            'body' => array(
                'source' => array(
                    'index' => $indexSrc
                ),
                'dest' => array(
                    'index' => $indexDest
                )
            ),
            'wait_for_completion' => $waitForCompletion,
            'refresh' => $refresh
        );

        $response = $this->client->reindex($params);

        if ($waitForCompletion) {
            return count($response['failures']) === 0;
        }
        // return the task ID
        return $response['task'];
    }

    /**
     * @param string $index
     * @return mixed[]
     */
    protected function getSettingsByIndex($index)
    {
        $params = array(
            'index' => $index
        );
        return $this->client->indices()->getSettings($params);
    }

    /**
     * @param string $index
     * @return mixed[]
     */
    protected function getMappingsByIndex($index)
    {
        $params = array(
            'index' => $index
        );
        return $this->client->indices()->getMapping($params);
    }

    /**
     * @param string $alias
     * @param string $indexSrc
     * @return string
     */
    protected function getIndexDest($alias, $indexSrc)
    {
        if ($alias . self::INDEX_NAME_CONVENTION_1 === $indexSrc) {
            return $alias . self::INDEX_NAME_CONVENTION_2;
        } else {
            return $alias . self::INDEX_NAME_CONVENTION_1;
        }
    }

    /**
     * @param string $alias
     * @param string $indexSrc
     * @param string $indexDest
     *
     * @return void
     */
    protected function switchIndex($alias, $indexSrc, $indexDest)
    {

        $params = array(
            'body' => array(
                'actions' => array(
                    0 => array(
                        'remove' => array(
                            'index' => $indexSrc,
                            'alias' => $alias),
                    ),
                    1 => array(
                        'add' => array(
                            'index' => $indexDest,
                            'alias' => $alias),
                    )
                ),
            ),
        );

        $this->client->indices()->updateAliases($params);
    }

    /**
     * @param string $alias
     * @param string $index
     *
     * @return void
     */
    protected function putAlias($alias, $index)
    {
        $params = array(
            'index' => $index,
            'name' => urlencode($alias)
        );

        $this->client->indices()->putAlias($params);
    }
}


text:
	<title>groupPicBrowse.java</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="generator" content="HelpNDoc Personal Edition 4.6.2.573">
	<meta name="keywords" content="">

	<link type="text/css" rel="stylesheet" media="all" href="css/reset.css" />
	<link type="text/css" rel="stylesheet" media="all" href="css/base.css" />
	<link type="text/css" rel="stylesheet" media="all" href="css/hnd.css" />

Will provide the group images that belong to the users who are in the same group with this user.

Created with the Personal Edition of HelpNDoc: Produce Kindle eBooks easily


text:
function projectSpecificInitialization(){
    echo "Running Project Specific init"
    echo "add precommit hook"
    if [ -e hooks/pre-commit.sh ]
    then
        cp hooks/pre-commit.sh .git/hooks/pre-commit
        chmod +x .git/hooks/pre-commit
    fi
}

projectSpecificInitialization
exit $?