text:
package com.zaxxer.hikari.pool;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

import java.lang.management.ManagementFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLTransientConnectionException;
import java.sql.Statement;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicReference;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.metrics.MetricsTracker;
import com.zaxxer.hikari.util.ClockSource;
import com.zaxxer.hikari.util.DriverDataSource;
import com.zaxxer.hikari.util.PropertyElf;
import com.zaxxer.hikari.util.UtilityElf;
import com.zaxxer.hikari.util.UtilityElf.DefaultThreadFactory;

import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_AUTOCOMMIT;
import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_CATALOG;
import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_ISOLATION;
import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_NETTIMEOUT;
import static com.zaxxer.hikari.pool.ProxyConnection.DIRTY_BIT_READONLY;
import static com.zaxxer.hikari.util.UtilityElf.createInstance;

abstract class PoolBase
{
   private final Logger LOGGER = LoggerFactory.getLogger(PoolBase.class);

   protected final HikariConfig config;
   protected final String poolName;
   protected long connectionTimeout;
   protected long validationTimeout;

   private static final String[] RESET_STATES = {"readOnly", "autoCommit", "isolation", "catalog", "netTimeout"};
   private static final int UNINITIALIZED = -1;
   private static final int TRUE = 1;
   private static final int FALSE = 0;

   private int networkTimeout;
   private int isNetworkTimeoutSupported;
   private int isQueryTimeoutSupported;
   private int defaultTransactionIsolation;
   private int transactionIsolation;
   private Executor netTimeoutExecutor;
   private DataSource dataSource;

   private final String catalog;
   private final boolean isReadOnly;
   private final boolean isAutoCommit;

   private final boolean isUseJdbc4Validation;
   private final boolean isIsolateInternalQueries;
   private final AtomicReference<Throwable> lastConnectionFailure;

   private volatile boolean isValidChecked;

   PoolBase(final HikariConfig config)
   {
      this.config = config;

      this.networkTimeout = UNINITIALIZED;
      this.catalog = config.getCatalog();
      this.isReadOnly = config.isReadOnly();
      this.isAutoCommit = config.isAutoCommit();
      this.transactionIsolation = UtilityElf.getTransactionIsolation(config.getTransactionIsolation());

      this.isQueryTimeoutSupported = UNINITIALIZED;
      this.isNetworkTimeoutSupported = UNINITIALIZED;
      this.isUseJdbc4Validation = config.getConnectionTestQuery() == null;
      this.isIsolateInternalQueries = config.isIsolateInternalQueries();

      this.poolName = config.getPoolName();
      this.connectionTimeout = config.getConnectionTimeout();
      this.validationTimeout = config.getValidationTimeout();
      this.lastConnectionFailure = new AtomicReference<>();

      initializeDataSource();
   }

   /** {@inheritDoc} */
   @Override
   public String toString()
   {
      return poolName;
   }

   abstract void recycle(final PoolEntry poolEntry);

   // ***********************************************************************
   //                           JDBC methods
   // ***********************************************************************

   void quietlyCloseConnection(final Connection connection, final String closureReason)
   {
      if (connection != null) {
         try {
            LOGGER.debug("{} - Closing connection {}: {}", poolName, connection, closureReason);
            try {
               setNetworkTimeout(connection, SECONDS.toMillis(15));
            }
            finally {
               connection.close(); // continue with the close even if setNetworkTimeout() throws
            }
         }
         catch (Throwable e) {
            LOGGER.debug("{} - Closing connection {} failed", poolName, connection, e);
         }
      }
   }

   boolean isConnectionAlive(final Connection connection)
   {
      try {
         try {
            if (isUseJdbc4Validation) {
               return connection.isValid((int) MILLISECONDS.toSeconds(Math.max(1000L, validationTimeout)));
            }

            setNetworkTimeout(connection, validationTimeout);

            try (Statement statement = connection.createStatement()) {
               if (isNetworkTimeoutSupported != TRUE) {
                  setQueryTimeout(statement, (int) MILLISECONDS.toSeconds(Math.max(1000L, validationTimeout)));
               }

               statement.execute(config.getConnectionTestQuery());
            }
         }
         finally {
            if (isIsolateInternalQueries && !isAutoCommit) {
               connection.rollback();
            }
         }

         setNetworkTimeout(connection, networkTimeout);

         return true;
      }
      catch (SQLException e) {
         lastConnectionFailure.set(e);
         LOGGER.warn("{} - Failed to validate connection {} ({})", poolName, connection, e.getMessage());
         return false;
      }
   }

   Throwable getLastConnectionFailure()
   {
      return lastConnectionFailure.get();
   }

   public DataSource getUnwrappedDataSource()
   {
      return dataSource;
   }

   // ***********************************************************************
   //                         PoolEntry methods
   // ***********************************************************************

   PoolEntry newPoolEntry() throws Exception
   {
      return new PoolEntry(newConnection(), this, isReadOnly, isAutoCommit);
   }

   void resetConnectionState(final Connection connection, final ProxyConnection proxyConnection, final int dirtyBits) throws SQLException
   {
      int resetBits = 0;

      if ((dirtyBits & DIRTY_BIT_READONLY) != 0 && proxyConnection.getReadOnlyState() != isReadOnly) {
         connection.setReadOnly(isReadOnly);
         resetBits |= DIRTY_BIT_READONLY;
      }

      if ((dirtyBits & DIRTY_BIT_AUTOCOMMIT) != 0 && proxyConnection.getAutoCommitState() != isAutoCommit) {
         connection.setAutoCommit(isAutoCommit);
         resetBits |= DIRTY_BIT_AUTOCOMMIT;
      }

      if ((dirtyBits & DIRTY_BIT_ISOLATION) != 0 && proxyConnection.getTransactionIsolationState() != transactionIsolation) {
         connection.setTransactionIsolation(transactionIsolation);
         resetBits |= DIRTY_BIT_ISOLATION;
      }

      if ((dirtyBits & DIRTY_BIT_CATALOG) != 0 && catalog != null && !catalog.equals(proxyConnection.getCatalogState())) {
         connection.setCatalog(catalog);
         resetBits |= DIRTY_BIT_CATALOG;
      }

      if ((dirtyBits & DIRTY_BIT_NETTIMEOUT) != 0 && proxyConnection.getNetworkTimeoutState() != networkTimeout) {
         setNetworkTimeout(connection, networkTimeout);
         resetBits |= DIRTY_BIT_NETTIMEOUT;
      }

      if (resetBits != 0 && LOGGER.isDebugEnabled()) {
         LOGGER.debug("{} - Reset ({}) on connection {}", poolName, stringFromResetBits(resetBits), connection);
      }
   }

   void shutdownNetworkTimeoutExecutor()
   {
      if (netTimeoutExecutor instanceof ThreadPoolExecutor) {
         ((ThreadPoolExecutor) netTimeoutExecutor).shutdownNow();
      }
   }

   // ***********************************************************************
   //                       JMX methods
   // ***********************************************************************

   /**
    * Register MBeans for HikariConfig and HikariPool.
    *
    * @param pool a HikariPool instance
    */
   void registerMBeans(final HikariPool hikariPool)
   {
      if (!config.isRegisterMbeans()) {
         return;
      }

      try {
         final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

         final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")");
         final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")");
         if (!mBeanServer.isRegistered(beanConfigName)) {
            mBeanServer.registerMBean(config, beanConfigName);
            mBeanServer.registerMBean(hikariPool, beanPoolName);
         }
         else {
            LOGGER.error("{} - JMX name ({}) is already registered.", poolName, poolName);
         }
      }
      catch (Exception e) {
         LOGGER.warn("{} - Failed to register management beans.", poolName, e);
      }
   }

   /**
    * Unregister MBeans for HikariConfig and HikariPool.
    */
   void unregisterMBeans()
   {
      if (!config.isRegisterMbeans()) {
         return;
      }

      try {
         final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

         final ObjectName beanConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + poolName + ")");
         final ObjectName beanPoolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + poolName + ")");
         if (mBeanServer.isRegistered(beanConfigName)) {
            mBeanServer.unregisterMBean(beanConfigName);
            mBeanServer.unregisterMBean(beanPoolName);
         }
      }
      catch (Exception e) {
         LOGGER.warn("{} - Failed to unregister management beans.", poolName, e);
      }
   }

   // ***********************************************************************
   //                          Private methods
   // ***********************************************************************

   /**
    * Create/initialize the underlying DataSource.
    *
    * @return a DataSource instance
    */
   private void initializeDataSource()
   {
      final String jdbcUrl = config.getJdbcUrl();
      final String username = config.getUsername();
      final String password = config.getPassword();
      final String dsClassName = config.getDataSourceClassName();
      final String driverClassName = config.getDriverClassName();
      final Properties dataSourceProperties = config.getDataSourceProperties();

      DataSource dataSource = config.getDataSource();
      if (dsClassName != null && dataSource == null) {
         dataSource = createInstance(dsClassName, DataSource.class);
         PropertyElf.setTargetFromProperties(dataSource, dataSourceProperties);
      }
      else if (jdbcUrl != null && dataSource == null) {
         dataSource = new DriverDataSource(jdbcUrl, driverClassName, dataSourceProperties, username, password);
      }

      if (dataSource != null) {
         setLoginTimeout(dataSource);
         createNetworkTimeoutExecutor(dataSource, dsClassName, jdbcUrl);
      }

      this.dataSource = dataSource;
   }

   /**
    * Obtain connection from data source.
    *
    * @return a Connection connection
    */
   Connection newConnection() throws Exception
   {
      Connection connection = null;
      try {
         String username = config.getUsername();
         String password = config.getPassword();

         connection = (username == null) ? dataSource.getConnection() : dataSource.getConnection(username, password);
         if (connection == null) {
            throw new SQLTransientConnectionException("DataSource returned null unexpectedly");
         }

         setupConnection(connection);
         lastConnectionFailure.set(null);
         return connection;
      }
      catch (Exception e) {
         Exception cause = e;
         if (e instanceof ConnectionSetupException) {
            cause = (Exception) e.getCause();
         }

         if (connection != null) {
            quietlyCloseConnection(connection, "(Failed to create/setup connection)");
         }
         else if (getLastConnectionFailure() == null) {
            LOGGER.debug("{} - Failed to create/setup connection: {}", poolName, cause.getMessage());
         }

         lastConnectionFailure.set(cause);
         throw e;
      }
   }

   /**
    * Setup a connection initial state.
    *
    * @param connection a Connection
    * @throws SQLException thrown from driver
    */
   private void setupConnection(final Connection connection) throws ConnectionSetupException
   {
      try {
         if (networkTimeout == UNINITIALIZED) {
            networkTimeout = getAndSetNetworkTimeout(connection, validationTimeout);
         }
         else {
            setNetworkTimeout(connection, validationTimeout);
         }

         connection.setReadOnly(isReadOnly);
         connection.setAutoCommit(isAutoCommit);

         checkDriverSupport(connection);

         if (transactionIsolation != defaultTransactionIsolation) {
            connection.setTransactionIsolation(transactionIsolation);
         }

         if (catalog != null) {
            connection.setCatalog(catalog);
         }

         executeSql(connection, config.getConnectionInitSql(), true);

         setNetworkTimeout(connection, networkTimeout);
      }
      catch (SQLException e) {
         throw new ConnectionSetupException(e);
      }
   }

   /**
    * Execute isValid() or connection test query.
    *
    * @param connection a Connection to check
    */
   private void checkDriverSupport(final Connection connection) throws SQLException
   {
      if (!isValidChecked) {
         try {
            if (isUseJdbc4Validation) {
               connection.isValid(1);
            }
            else {
               executeSql(connection, config.getConnectionTestQuery(), false);
            }
         }
         catch (Throwable e) {
            LOGGER.error("{} - Failed to execute" + (isUseJdbc4Validation ? " isValid() for connection, configure" : "") + " connection test query. ({})", poolName, e.getMessage());
            throw e;
         }

         try {
            defaultTransactionIsolation = connection.getTransactionIsolation();
            if (transactionIsolation == -1) {
               transactionIsolation = defaultTransactionIsolation;
            }
         }
         catch (SQLException e) {
            LOGGER.warn("{} - Default transaction isolation level detection failed. ({})", poolName, e.getMessage());
         }
         finally {
            isValidChecked = true;
         }
      }
   }

   /**
    * Set the query timeout, if it is supported by the driver.
    *
    * @param statement a statement to set the query timeout on
    * @param timeoutSec the number of seconds before timeout
    */
   private void setQueryTimeout(final Statement statement, final int timeoutSec)
   {
      if (isQueryTimeoutSupported != FALSE) {
         try {
            statement.setQueryTimeout(timeoutSec);
            isQueryTimeoutSupported = TRUE;
         }
         catch (Throwable e) {
            if (isQueryTimeoutSupported == UNINITIALIZED) {
               isQueryTimeoutSupported = FALSE;
               LOGGER.info("{} - Failed to set query timeout for statement. ({})", poolName, e.getMessage());
            }
         }
      }
   }

   /**
    * Set the network timeout, if isUseNetworkTimeout is true and the
    * driver supports it.  Return the pre-existing value of the network timeout.
    *
    * @param connection the connection to set the network timeout on
    * @param timeoutMs the number of milliseconds before timeout
    * @return the pre-existing network timeout value
    */
   private int getAndSetNetworkTimeout(final Connection connection, final long timeoutMs)
   {
      if (isNetworkTimeoutSupported != FALSE) {
         try {
            final int originalTimeout = connection.getNetworkTimeout();
            connection.setNetworkTimeout(netTimeoutExecutor, (int) timeoutMs);
            isNetworkTimeoutSupported = TRUE;
            return originalTimeout;
         }
         catch (Throwable e) {
            if (isNetworkTimeoutSupported == UNINITIALIZED) {
               isNetworkTimeoutSupported = FALSE;

               LOGGER.info("{} - Driver does not support get/set network timeout for connections. ({})", poolName, e.getMessage());
               if (validationTimeout < SECONDS.toMillis(1)) {
                  LOGGER.warn("{} - A validationTimeout of less than 1 second cannot be honored on drivers without setNetworkTimeout() support.", poolName);
               }
               else if (validationTimeout % SECONDS.toMillis(1) != 0) {
                  LOGGER.warn("{} - A validationTimeout with fractional second granularity cannot be honored on drivers without setNetworkTimeout() support.", poolName);
               }
            }
         }
      }

      return 0;
   }

   /**
    * Set the network timeout, if isUseNetworkTimeout is true and the
    * driver supports it.
    *
    * @param connection the connection to set the network timeout on
    * @param timeoutMs the number of milliseconds before timeout
    * @throws SQLException throw if the connection.setNetworkTimeout() call throws
    */
   private void setNetworkTimeout(final Connection connection, final long timeoutMs) throws SQLException
   {
      if (isNetworkTimeoutSupported == TRUE) {
         connection.setNetworkTimeout(netTimeoutExecutor, (int) timeoutMs);
      }
   }

   /**
    * Execute the user-specified init SQL.
    *
    * @param connection the connection to initialize
    * @param sql the SQL to execute
    * @param isCommit whether to commit the SQL after execution or not
    * @throws SQLException throws if the init SQL execution fails
    */
   private void executeSql(final Connection connection, final String sql, final boolean isCommit) throws SQLException
   {
      if (sql != null) {
         try (Statement statement = connection.createStatement()) {
            // connection was created a few milliseconds before, so set query timeout is omitted (we assume it will succeed)
            statement.execute(sql);
         }

         if (isIsolateInternalQueries && !isAutoCommit) {
            if (isCommit) {
               connection.commit();
            }
            else {
               connection.rollback();
            }
         }
      }
   }

   private void createNetworkTimeoutExecutor(final DataSource dataSource, final String dsClassName, final String jdbcUrl)
   {
      // Temporary hack for MySQL issue: http://bugs.mysql.com/bug.php?id=75615
      if ((dsClassName != null && dsClassName.contains("Mysql")) ||
          (jdbcUrl != null && jdbcUrl.contains("mysql")) ||
          (dataSource != null && dataSource.getClass().getName().contains("Mysql"))) {
         netTimeoutExecutor = new SynchronousExecutor();
      }
      else {
         ThreadFactory threadFactory = config.getThreadFactory();
         threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory(poolName + " network timeout executor", true);
         ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(threadFactory);
         executor.setKeepAliveTime(15, SECONDS);
         executor.allowCoreThreadTimeOut(true);
         netTimeoutExecutor = executor;
      }
   }

   /**
    * Set the loginTimeout on the specified DataSource.
    *
    * @param dataSource the DataSource
    */
   private void setLoginTimeout(final DataSource dataSource)
   {
      if (connectionTimeout != Integer.MAX_VALUE) {
         try {
            dataSource.setLoginTimeout(Math.max(1, (int) MILLISECONDS.toSeconds(500L + connectionTimeout)));
         }
         catch (Throwable e) {
            LOGGER.info("{} - Failed to set login timeout for data source. ({})", poolName, e.getMessage());
         }
      }
   }

   /**
    * This will create a string for debug logging. Given a set of "reset bits", this
    * method will return a concatenated string, for example:
    *
    * Input : 0b00110
    * Output: "autoCommit, isolation"
    *
    * @param bits a set of "reset bits"
    * @return a string of which states were reset
    */
   private String stringFromResetBits(final int bits)
   {
      final StringBuilder sb = new StringBuilder();
      for (int ndx = 0; ndx < RESET_STATES.length; ndx++) {
         if ( (bits & (0b1 << ndx)) != 0) {
            sb.append(RESET_STATES[ndx]).append(", ");
         }
      }

      sb.setLength(sb.length() - 2);  // trim trailing comma
      return sb.toString();
   }

   // ***********************************************************************
   //                      Private Static Classes
   // ***********************************************************************

   static class ConnectionSetupException extends Exception
   {
      private static final long serialVersionUID = 929872118275916521L;

      public ConnectionSetupException(Throwable t)
      {
         super(t);
      }
   }

   /**
    * Special executor used only to work around a MySQL issue that has not been addressed.
    * MySQL issue: http://bugs.mysql.com/bug.php?id=75615
    */
   private static class SynchronousExecutor implements Executor
   {
      /** {@inheritDoc} */
      @Override
      public void execute(Runnable command)
      {
         try {
            command.run();
         }
         catch (Throwable t) {
            LoggerFactory.getLogger(PoolBase.class).debug("Failed to execute: {}", command, t);
         }
      }
   }

   /**
    * A class that delegates to a MetricsTracker implementation.  The use of a delegate
    * allows us to use the NopMetricsTrackerDelegate when metrics are disabled, which in
    * turn allows the JIT to completely optimize away to callsites to record metrics.
    */
   static class MetricsTrackerDelegate implements AutoCloseable
   {
      final MetricsTracker tracker;

      protected MetricsTrackerDelegate()
      {
         this.tracker = null;
      }

      MetricsTrackerDelegate(MetricsTracker tracker)
      {
         this.tracker = tracker;
      }

      @Override
      public void close()
      {
         tracker.close();
      }

      void recordConnectionUsage(final PoolEntry poolEntry)
      {
         tracker.recordConnectionUsageMillis(poolEntry.getMillisSinceBorrowed());
      }

      /**
       * @param poolEntry
       * @param now
       */
      void recordBorrowStats(final PoolEntry poolEntry, final long startTime)
      {
         final long now = ClockSource.INSTANCE.currentTime();
         poolEntry.lastBorrowed = now;
         tracker.recordConnectionAcquiredNanos(ClockSource.INSTANCE.elapsedNanos(startTime, now));
      }

      void recordConnectionTimeout() {
         tracker.recordConnectionTimeout();
      }
   }

   /**
    * A no-op implementation of the MetricsTrackerDelegate that is used when metrics capture is
    * disabled.
    */
   static final class NopMetricsTrackerDelegate extends MetricsTrackerDelegate
   {
      @Override
      void recordConnectionUsage(final PoolEntry poolEntry)
      {
         // no-op
      }

      @Override
      public void close()
      {
         // no-op
      }

      @Override
      void recordBorrowStats(final PoolEntry poolEntry, final long startTime)
      {
         // no-op
      }

      @Override
      void recordConnectionTimeout()
      {
         // no-op
      }
   }
}


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class MdInsertInvitation extends React.Component<IconBaseProps> { }
export = MdInsertInvitation;

redpajama_set_name: RedPajamaGithub


text:
package com.java110.vo.api.inspectionTask;

import java.io.Serializable;
import java.util.Date;

public class ApiInspectionTaskDataVo implements Serializable {

    private String planUserId;
    private String actInsTime;
    private String planInsTime;
    private String planEndTime;
    private String statusCd;
    private String actUserName;
    private String operate;
    private String signType;
    private String signTypeName;
    private String inspectionPlanId;
    private String inspectionPlanName;
    private String planUserName;
    private String communityId;
    private String bId;
    private String actUserId;
    private String taskId;
    private String state;
    private String stateName;

    private String originalPlanUserId;
    private String originalPlanUserName;
    private String transferDesc;
    private String taskType;

    public String getPlanUserId() {
        return planUserId;
    }

    public void setPlanUserId(String planUserId) {
        this.planUserId = planUserId;
    }

    public String getActInsTime() {
        return actInsTime;
    }

    public void setActInsTime(String actInsTime) {
        this.actInsTime = actInsTime;
    }

    public String getPlanInsTime() {
        return planInsTime;
    }

    public void setPlanInsTime(String planInsTime) {
        this.planInsTime = planInsTime;
    }

    public String getStatusCd() {
        return statusCd;
    }

    public void setStatusCd(String statusCd) {
        this.statusCd = statusCd;
    }

    public String getActUserName() {
        return actUserName;
    }

    public void setActUserName(String actUserName) {
        this.actUserName = actUserName;
    }

    public String getOperate() {
        return operate;
    }

    public void setOperate(String operate) {
        this.operate = operate;
    }

    public String getSignType() {
        return signType;
    }

    public void setSignType(String signType) {
        this.signType = signType;
    }

    public String getInspectionPlanId() {
        return inspectionPlanId;
    }

    public void setInspectionPlanId(String inspectionPlanId) {
        this.inspectionPlanId = inspectionPlanId;
    }

    public String getPlanUserName() {
        return planUserName;
    }

    public void setPlanUserName(String planUserName) {
        this.planUserName = planUserName;
    }

    public String getCommunityId() {
        return communityId;
    }

    public void setCommunityId(String communityId) {
        this.communityId = communityId;
    }

    public String getBId() {
        return bId;
    }

    public void setBId(String bId) {
        this.bId = bId;
    }

    public String getActUserId() {
        return actUserId;
    }

    public void setActUserId(String actUserId) {
        this.actUserId = actUserId;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getSignTypeName() {
        return signTypeName;
    }

    public void setSignTypeName(String signTypeName) {
        this.signTypeName = signTypeName;
    }

    public String getbId() {
        return bId;
    }

    public void setbId(String bId) {
        this.bId = bId;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getStateName() {
        return stateName;
    }

    public void setStateName(String stateName) {
        this.stateName = stateName;
    }

    public String getInspectionPlanName() {
        return inspectionPlanName;
    }

    public void setInspectionPlanName(String inspectionPlanName) {
        this.inspectionPlanName = inspectionPlanName;
    }

    public String getPlanEndTime() {
        return planEndTime;
    }

    public void setPlanEndTime(String planEndTime) {
        this.planEndTime = planEndTime;
    }

    public String getOriginalPlanUserId() {
        return originalPlanUserId;
    }

    public void setOriginalPlanUserId(String originalPlanUserId) {
        this.originalPlanUserId = originalPlanUserId;
    }

    public String getOriginalPlanUserName() {
        return originalPlanUserName;
    }

    public void setOriginalPlanUserName(String originalPlanUserName) {
        this.originalPlanUserName = originalPlanUserName;
    }

    public String getTransferDesc() {
        return transferDesc;
    }

    public void setTransferDesc(String transferDesc) {
        this.transferDesc = transferDesc;
    }

    public String getTaskType() {
        return taskType;
    }

    public void setTaskType(String taskType) {
        this.taskType = taskType;
    }
}


text:
title: ASM - Introduction
mathjax: false
date: 2022-02-22 00:06:25
categories:
  - Java
  - JVM
  - Bytecode Manipulation
tags:
  - Java
  - JVM
  - Bytecode Manipulation
  - ASM
---

# Glance

1. ASM is an **all purpose** Java bytecode manipulation and analysis framework.
   - It can be used to **modify existing classes** or to **dynamically generate classes**, directly in **binary** form.
2. ASM provides some **common bytecode transformations and analysis algorithms** from which custom complex transformations and code analysis tools can be built.
3. ASM offers similar functionality as other Java bytecode frameworks, but is focused on **performance**.
   - Because it was designed and implemented to be as **small** and as **fast** as possible, it is well suited for use in **dynamic** systems (but can of course be used in a **static** way too, e.g. in compilers).

<!-- more -->

# Introduction

## Motivations

### Situations

1. **Program analysis**
   - which can range from a simple syntaxic parsing to a full semantic analysis, can be used to find potential bugs in applications, to detect unused code, to reverse engineer code, etc.
2. **Program generation**
   - is used in **compilers**. This include **traditional compilers**, but also **stub or skeleton compilers** used for distributed programming, **Just in Time compilers**, etc.
3. **Program transformation**
   - can be used to **optimize or obfuscate programs**, to insert **debugging** or **performance monitoring** code into applications, for **aspect oriented programming**, etc.

### Advantages of working on compiled classes

1. The **source code** is **not needed**.
   - Program transformations can therefore be used on **any applications**, including **closed source** and **commercial ones**.
2. It becomes possible to analyze, generate or transform classes at **runtime**.
   - Tools such as **stub compilers** or **aspect weavers** become **transparent** to users.

### ASM

1. ASM is designed for **runtime** – but also offline – class **generation** and **transformation**.
   - The ASM library was therefore designed to work on **compiled Java classes**.
2. It was also designed to be as **fast** and as **small** as possible.
   - Being as fast as possible is important in order **not to slow down too much** the applications that use ASM at runtime, for dynamic class generation or transformation.
   - And being as small as possible is important in order to be used in memory constrained environments, and to **avoid bloating the size** of small applications or libraries using ASM.

## Overview

### Scope

1. The goal of the ASM library is to **generate, transform and analyze compiled Java classes**, represented as **byte arrays** (as they are stored on disk and loaded in the Java Virtual Machine).
2. For this purpose ASM provides tools to **read, write and transform** such byte arrays by using **higher level concepts** than bytes.
3. Note that the **scope** of the ASM library is **strictly limited** to ***reading, writing, transforming and analyzing classes***.
   - In particular the *class loading process* is *out of scope*.

### Model

1. The ASM library provides two APIs for generating and transforming compiled classes
   - the **core API** provides an **event based** representation of classes
   - the **tree API** provides an **object based** representation of classes
2. **event based**
   - With the event based model a class is represented with **a sequence of events**, each **event** representing **an element of the class**, such as its header, a field, a method declaration, an instruction, etc.
   - The event based API defines the set of possible events and the **order** in which they must occur
     - and provides a **class parser** that **generates one event per element that is parsed**
       - ***class parser: element -> event***
     - as well as a **class writer** that **generates compiled classes from sequences of such events**.
       - ***class writer: events -> class***
3. **object based**
   - With the object based model a class is represented with **a tree of objects**, each object representing a part of the class, such as the class itself, a field, a method, an instruction, etc. and each object having **references** to the objects that represent its **constituents**.
   - *The object based API is built **on top of** the event based API*.
     - The object based API provides a way to convert a sequence of events representing a class to the object tree representing the same class and, vice versa, to convert an object tree to the equivalent event sequence.
4. ASM provides both APIs because **there is no best API**.
   - The **event based** API is **faster** and **requires less memory** than the object based API, since there is no need to create and store in memory a tree of objects representing the class.
   - However **implementing class transformations** can be **more difficult** with the **event based** API, since **only one element** of the class is **available** at **any given time** (the element that corresponds to the current event), while the whole class is available in memory with the object based API.
5. Note that the two APIs **manage only one class at a time**, and **independently** of the others
   - **no information about the class hierarchy is maintained**, and if a class transformation affects other classes, it is up to the user to modify these other classes.

### Architecture

1. **event based**
   - Indeed the event based API is organized around **event producers** (the **class parser**), **event consumers** (the **class writer**) and various **predefined event filters**, to which user defined producers, consumers and filters can be added.
   - Two step process
     - **assembling** event producer, filter and consumer components into possibly complex architectures.
     - and then **starting the event producers** to run the **generation** or **transformation** process.
2. **object based**
   - Indeed class **generator** or **transformer** components that operate on object trees **can be composed**, the **links** between them representing the **order of transformations**.

![image-20220222144417064](https://jvm-byte-coding-1253868755.cos.ap-guangzhou.myqcloud.com/asm/image-20220222144417064.png)

## Organization

1. **core API**
   - **asm**
     - **the `org.objectweb.asm` and `org.objectweb.asm.signature` packages define the **event based** API and provide the **class parser and writer** components.
   - **asm-util**
     - the `org.objectweb.asm.util` package, provides various tools based on the **core API** that can be used during the **development** and **debuging** of ASM applications.
   - **asm-commons**
     - the `org.objectweb.asm.commons` package provides several useful **predefined class transformers**, mostly based on the **core API**.
2. **tree API**
   - **asm-tree**
     - the `org.objectweb.asm.tree` package, defines the **object based** API, and provides tools to **convert** between the **event based** and the **object based** representations.
   - **asm-analysis**
     - the `org.objectweb.asm.tree.analysis` package provides a **class analysis framework** and several **predefined class analyzers**, based on the **tree API**.

# Reference

1. [ASM 4.0 - A Java bytecode engineering library](https://asm.ow2.io/asm4-guide.pdf)


text:
package nw.commons.beans;

import nw.commons.NeemClazz;

public class TestClazz extends NeemClazz{

	public TestClazz() {
		super();
	}

	@Override
	public void setTargetPropertyFilename() {
		this.targetPropertyFilename = "test.properties";

	}

}


text:
class AnswerPolicy < ApplicationPolicy
  # NOTE: @user is the signed_in_user and @record is an instance of Answer

  def create_or_update?
    # TODO: Remove the owner check after the Roles have been updated
    # is the plan editable by the user or the user is the owner of the plan
    @record.plan.editable_by?(@user.id) || @user == @record.plan.owner
  end
end


text:
import itertools
import logging
import os

import six

import sahara.plugins.mapr.domain.configuration_file as bcf
import sahara.plugins.mapr.domain.node_process as np
import sahara.plugins.mapr.domain.service as s
import sahara.plugins.mapr.services.hbase.hbase as hbase
import sahara.plugins.mapr.services.hive.hive as hive
import sahara.plugins.mapr.services.httpfs.httpfs as httpfs
import sahara.plugins.mapr.services.impala.impala as impala
import sahara.plugins.mapr.services.mapreduce.mapreduce as mr
import sahara.plugins.mapr.services.mysql.mysql as mysql
import sahara.plugins.mapr.services.oozie.oozie as oozie
import sahara.plugins.mapr.services.sqoop.sqoop2 as sqoop
import sahara.plugins.mapr.services.yarn.yarn as yarn
import sahara.plugins.mapr.util.general as g
import sahara.plugins.mapr.util.validation_utils as vu
import sahara.utils.files as files

LOG = logging.getLogger(__name__)

HUE = np.NodeProcess(
    name='hue',
    ui_name='Hue',
    package='mapr-hue',
    open_ports=[8002, 8888]
)

@six.add_metaclass(s.Single)
class Hue(s.Service):
    def __init__(self):
        super(Hue, self).__init__()
        self.name = 'hue'
        self.ui_name = 'Hue'
        self.version = '3.6.0'
        self.node_processes = [HUE]
        self.ui_info = [('HUE', HUE, 'http://%s:8888')]
        self._validation_rules = [vu.on_same_node(HUE, httpfs.HTTP_FS)]

    def get_config_files(self, cluster_context, configs, instance=None):
        remote_path = "/opt/mapr/hue/hue-%s/desktop/conf/" % self.version
        template = 'plugins/mapr/services/hue/resources/hue_3.6.0.template'

        hue_ini = bcf.TemplateFile("hue.ini")
        hue_ini.remote_path = remote_path
        hue_ini.parse(files.get_file_text(template))
        hue_ini.add_properties(self._get_hue_ini_props(cluster_context))

        # TODO: rewrite it
        hue_instances = cluster_context.get_instances(HUE)
        for instance in hue_instances:
            if instance not in cluster_context.changed_instances():
                cluster_context.should_be_restarted[self] += [instance]

        return [hue_ini]

    def _get_hue_ini_props(self, context):
        db_instance = mysql.MySQL.get_db_instance(context)
        is_yarn = context.cluster_mode == 'yarn'
        hue_specs = mysql.MySQL.HUE_SPECS
        rdbms_specs = mysql.MySQL.RDBMS_SPECS

        result = {
            'db_host': db_instance.fqdn(),
            'hue_name': hue_specs.db_name,
            'hue_user': hue_specs.user,
            'hue_password': hue_specs.password,
            'rdbms_name': rdbms_specs.db_name,
            'rdbms_user': rdbms_specs.user,
            'rdbms_password': rdbms_specs.password,
            'resource_manager_uri': context.resource_manager_uri,
            'yarn_mode': is_yarn,
            'rm_host': context.get_instance_ip(yarn.RESOURCE_MANAGER),
            'webhdfs_url': context.get_instance_ip(httpfs.HTTP_FS),
            'jt_host': context.get_instance_ip(mr.JOB_TRACKER),
            'oozie_host': context.get_instance_ip(oozie.OOZIE),
            'sqoop_host': context.get_instance_ip(sqoop.SQOOP_2_SERVER),
            'impala_host': context.get_instance_ip(impala.IMPALA_STATE_STORE),
            'hbase_host': context.get_instance_ip(hbase.HBASE_THRIFT),
            'zk_hosts_with_port': context.get_zookeeper_nodes_ip_with_port(),
        }

        hive_host = context.get_instance(hive.HIVE_METASTORE)
        if hive_host:
            hive_service = context.get_service(hive.HIVE_METASTORE)
            result.update({
                'hive_host': hive_host.management_ip,
                'hive_version': hive_service.version,
                'hive_conf_dir': hive_service.conf_dir(context),
            })

        return result

    def post_install(self, cluster_context, instances):
        hue_instance = cluster_context.get_instance(HUE)

        def migrate_database(remote, context):
            hue_service = context.get_service(HUE)
            hue_home = '/opt/mapr/hue/hue-%s' % hue_service.version
            cmd = '%(activate)s && %(syncdb)s && %(migrate)s'
            args = {
                'activate': 'source %s/build/env/bin/activate' % hue_home,
                'syncdb': '%s/build/env/bin/hue syncdb --noinput' % hue_home,
                'migrate': '%s/build/env/bin/hue migrate' % hue_home,
            }
            remote.execute_command(cmd % args, run_as_root=True, timeout=600)

        def set_owner(remote):
            remote.execute_command('chown -R mapr:mapr /opt/mapr/hue',
                                   run_as_root=True)

        if hue_instance:
            with hue_instance.remote() as r:
                LOG.debug("Executing Hue database migration")
                migrate_database(r, cluster_context)
                LOG.debug("Changing Hue home dir owner")
                set_owner(r)
            self._copy_hive_configs(cluster_context, hue_instance)
            self._install_jt_plugin(cluster_context, hue_instance)

    def _copy_hive_configs(self, cluster_context, hue_instance):
        hive_server = cluster_context.get_instance(hive.HIVE_SERVER_2)
        if not hive_server or hive_server == hue_instance:
            LOG.debug('No Hive Servers found. Skip')
            return
        hive_service = cluster_context.get_service(hive.HIVE_SERVER_2)
        hive_conf_dir = hive_service.conf_dir(cluster_context)
        g.copy(hive_conf_dir, hive_server, hive_conf_dir, hue_instance, 'root')

    def update(self, cluster_context, instances=None):
        if self._should_restart(cluster_context, instances):
            hue_instance = cluster_context.get_instance(HUE)
            self.restart([hue_instance])

    def _should_restart(self, c_context, instances):
        app_services = [
            impala.Impala(),
            hive.Hive(),
            hbase.HBase(),
            sqoop.Sqoop2(),
        ]
        instances = [c_context.filter_instances(instances, service=service)
                     for service in app_services]
        return bool(g.unique_list(itertools.chain(*instances)))

    def jt_plugin_path(self, cluster_context):
        path = ('%(home)s/desktop/libs/hadoop/java-lib'
                '/hue-plugins-%(version)s-mapr.jar')
        args = {
            'home': self.home_dir(cluster_context),
            'version': self.version,
        }
        return path % args

    def _install_jt_plugin(self, cluster_context, hue_instance):
        LOG.debug("Copying Hue JobTracker plugin")
        job_trackers = cluster_context.get_instances(mr.JOB_TRACKER)
        if not job_trackers:
            LOG.debug('No JobTrackers found. Skip')
            return
        jt_plugin_src = self.jt_plugin_path(cluster_context)
        jt_plugin_dest = cluster_context.hadoop_lib + '/jt_plugin.jar'
        for jt in job_trackers:
            g.copy(jt_plugin_src, hue_instance, jt_plugin_dest, jt, 'root')


text:
"""Oanda API Library"""

from oandapy.api.oanda_base import Core
from oandapy.api.account import Account
from oandapy.api.orders import Orders
from oandapy.api.positions import Positions
from oandapy.api.pricing import Pricing
from oandapy.api.trades import Trades
from oandapy.api.transactions import Transactions

class APIv20(Core):
    """Oanda REST API v20 Class

    This class instanciates all endpoint classes

    """

    def __init__(self, environment="practice", access_token=None):
        """APIv20 object to communicate with Oanda REST API.

        Args:
            environment (str, optional): Provides the environment for
                OANDA's API. Defaults to 'practice'.
            access_token (str): Specifies the access token.

        """
        super(APIv20, self).__init__(environment, access_token)
        self._version = "v3"

        self.account = Account(self)
        self.orders = Orders(self)
        self.positions = Positions(self)
        self.pricing = Pricing(self)
        self.trades = Trades(self)
        self.transactions = Transactions(self)


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="YYYCache-Example" type="AppleRunConfiguration" factoryName="Application" PASS_PARENT_ENVS_2="true" PROJECT_NAME="YYYCache" TARGET_NAME="YYYCache_Example" CONFIG_NAME="Debug" SCHEME_NAME="YYYCache-Example" IS_LOCATION_SIMULATION_ALLOWED="true" RUN_TARGET_PROJECT_NAME="YYYCache" RUN_TARGET_NAME="YYYCache_Example" MAKE_ACTIVE="TRUE">
    <method />
  </configuration>
</component>


text:
namespace GoogleARCoreInternal
{
    internal enum ApiPlaneType
    {
        HorizontalUpwardFacing = 0,
        HorizontalDownwardFacing = 1,
        Vertical = 2,
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <include
        android:id="@+id/vp_user_info"
        layout="@layout/view_pod_user_info"
        android:layout_width="match_parent"
        android:layout_height="@dimen/user_info_height" />

    <ListView
        android:id="@+id/lv_left_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/vp_user_info"
        android:layout_marginTop="@dimen/margin_top_menu_list"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />

    <TextView
        android:id="@+id/tv_app_version"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="@dimen/margin_bottom_app_version"
        android:background="@drawable/app_version_bg"
        android:gravity="right"
        android:paddingBottom="@dimen/margin_medium"
        android:paddingRight="@dimen/margin_large"
        android:paddingTop="@dimen/margin_medium"
        android:textColor="@color/primary_text"
        android:textSize="@dimen/text_regular_2x"
        tools:text="ရုပ်ရှင် v0.1" />

    <!--
    <TextView
        android:id="@+id/tv_feedback"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/tv_app_version"
        android:layout_marginBottom="@dimen/margin_medium_2"
        android:background="@drawable/app_version_bg"
        android:gravity="right"
        android:paddingBottom="@dimen/margin_medium"
        android:paddingRight="@dimen/margin_large"
        android:paddingTop="@dimen/margin_medium"
        android:text="@string/feedback"
        android:textColor="@color/primary_text"
        android:textSize="@dimen/text_regular_2x"
        android:visibility="gone"
        />
        -->

</RelativeLayout>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="">
    <meta name="description" content="">
    <meta name="keywords" content="">

    <title>Untitled</title>

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

Hello world!


text:
package com.tryout.rest.exception;

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

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class RestEndpointExceptionHandler extends
		ResponseEntityExceptionHandler {
	protected final static Logger LOGGER = LoggerFactory
			.getLogger(RestEndpointExceptionHandler.class);

	@Autowired
	private MessageSource messageSource;

	@ExceptionHandler
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	@ResponseBody
	ErrorsWrapper handleAccessDeniedException(AccessDeniedException ex) {
		LOGGER.error("", ex);
		List<ErrorBean> errors = new ArrayList<ErrorBean>();
		errors.add(resolveLocalizedErrorMessage(
				ErrorBean.SECURITY_NOT_AUTHORIZED, null));
		return new ErrorsWrapper(errors);
	}

	@ExceptionHandler
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ResponseBody
	ErrorsWrapper handleApplicationExceptions(ApplicationException ex) {
		LOGGER.error("{}", ex);
		List<ErrorBean> errors = ex.getErrorsList();

		// if list is null, create an empty one
		if (errors == null) {
			errors = new ArrayList<ErrorBean>();
		}

		// if list is empty and a single error code was specified, then process
		// that one
		if (errors.isEmpty() && StringUtils.isNotEmpty(ex.getMessage())) {
			errors.add(new ErrorBean(ex.getMessage()));
		}

		// resolve any errors collected so far
		if (errors.size() > 0) {
			List<ErrorBean> resolvedErrs = new ArrayList<ErrorBean>();
			for (ErrorBean errorBean : errors) {
				resolvedErrs.add(resolveLocalizedErrorMessage(
						errorBean.getCode(), errorBean.getParams()));
			}
			errors.clear();
			errors.addAll(resolvedErrs);
		}

		// if errors were found using Spring validator framework
		if (ex.getFieldErrors() != null) {
			errors.addAll(resolveErrorMessages(ex.getFieldErrors()
					.getAllErrors()));
		}

		// if no errors were found but hey this is still an error so lets send
		// default system error message
		if (errors.size() == 0) {
			errors = new ArrayList<ErrorBean>();
			errors.add(resolveLocalizedErrorMessage(ErrorBean.SYSTEM_ERROR,
					null));
		}

		return new ErrorsWrapper(errors);
	}

	@ExceptionHandler
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	ErrorsWrapper handleAllOtherExceptions(Exception ex) {
		LOGGER.error("", ex);
		List<ErrorBean> errors = new ArrayList<ErrorBean>();
		errors.add(resolveLocalizedErrorMessage(ErrorBean.SYSTEM_ERROR, null));
		return new ErrorsWrapper(errors);
	}

	/**
	 * Resolve SpringMVC validation errors using a resource bundle.
	 *
	 * @param fieldErrors
	 * @return
	 */
	private List<ErrorBean> resolveErrorMessages(List<ObjectError> fieldErrors) {
		List<ErrorBean> errors = new ArrayList<ErrorBean>();
		for (ObjectError fieldError : fieldErrors) {
			String localizedErrorMessage = fieldError.getCode();
			try {
				localizedErrorMessage = messageSource.getMessage(fieldError,
						LocaleContextHolder.getLocale());
			} catch (NoSuchMessageException ex) {
				// default the message to same as the code
				LOGGER.error(
						"Could not locate error message in resource bundle messages.properties for code {}. Message will default to same as the code.",
						fieldError.getCode());
				localizedErrorMessage = fieldError.getCode();
			}
			errors.add(new ErrorBean(fieldError.getCode(),
					localizedErrorMessage));
		}
		return errors;
	}

	/**
	 * Resolve simple error codes to their equivalent error messages from the
	 * resource bundle.
	 *
	 * @param fieldErrors
	 * @return
	 */
	private ErrorBean resolveLocalizedErrorMessage(final String code,
			final Object[] params) {
		try {
			return new ErrorBean(code, messageSource.getMessage(code,
					(params != null ? params : new Object[] {}),
					LocaleContextHolder.getLocale()));
		} catch (Exception ex) {
			// default the message to same as the code
			LOGGER.error(
					"Could not locate error message in resource bundle messages.properties for code {}. Message will default to same as the code.",
					code);
			return new ErrorBean(code, code);
		}
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<title>Test Page for CheckDihedral.js</title>

Test Page for CheckDihedral.js


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**type_id** | **Integer** | type_id integer |
**flag** | **Integer** | flag integer |
**quantity** | **Integer** | quantity integer |


text:
#region License

#endregion

namespace q2gconpsexecuteqvx
{
    #region Usings
    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    using Newtonsoft.Json;
    using NLog;
    #endregion

    public class ScriptCode
    {
        #region Logger
        private static Logger logger = LogManager.GetCurrentClassLogger();
        #endregion

        #region Variables & Properties
        public List<string> Parameters { get; private set; }
        public string Code { get; private set; }
        public string ScriptWithSign { get; private set; }
        public string TableName { get; private set; }

        public string OriginalScript { get; set; }
        private string ExecuteName { get; set; } = "PSEXECUTE";
        private string Algorithm { get; set; } = "SHA256";
        #endregion

        #region Constructor & Load
        private ScriptCode(string script)
        {
            OriginalScript = script;
        }
        #endregion

        #region Static Methods
        public static ScriptCode Create(string script, CryptoManager manager)
        {
            try
            {
                var resultScript = new ScriptCode(script);
                if (resultScript.Read(manager))
                {
                    return resultScript;
                }

                return null;
            }
            catch (Exception ex)
            {
                throw new Exception("The script could not be created.", ex);
            }
        }

        public static ScriptCode Parse(string script)
        {
            try
            {
                var resultScript = new ScriptCode(script);
                if(resultScript.Read(null))
                {
                    return resultScript;
                }

                return null;
            }
            catch (Exception ex)
            {
                throw new Exception("The script is not valid.", ex);
            }
        }
        #endregion

        #region Methods
        private bool Read(CryptoManager manager)
        {
            try
            {
                if (String.IsNullOrEmpty(OriginalScript))
                {
                    logger.Warn("The script is empty.");
                    return false;
                }

                if (!OriginalScript.Trim().StartsWith(ExecuteName))
                {
                    logger.Warn($"The command {ExecuteName} was not found.");
                    return false;
                }

                var text = OriginalScript.Trim().Replace("\r\n", "\n");
                Code = Regex.Replace(text, $"{ExecuteName}[^\n]*\n", "", RegexOptions.Singleline).Trim();
                if (Code.IndexOf(Algorithm) > -1)
                    Code = Code.Substring(0, Code.IndexOf(Algorithm)).Trim();

                if (manager != null)
                    CreateSignature(manager, OriginalScript);

                //Read parameters with JSON
                var args = Regex.Match(OriginalScript, $"{ExecuteName}\\((\\[[^\\]]+\\])\\)", RegexOptions.Singleline).Groups[1].Value;

                try
                {
                    Parameters = JsonConvert.DeserializeObject<List<string>>(args);
                }
                catch(Exception ex)
                {
                    logger.Error(ex, "The script arguments could not be read in JSON.");
                }

                if (Parameters == null)
                    Parameters = new List<string>();

                //Generate name for qlik table
                TableName = Regex.Match(text, $"({ExecuteName}[^\\)]*\\))", RegexOptions.Singleline).Groups[1].Value;
                if (String.IsNullOrEmpty(TableName))
                    TableName = ExecuteName;

                return true;
            }
            catch (Exception ex)
            {
                logger.Error(ex, "The script could not be read.");
                return false;
            }
        }

        private void CreateSignature(CryptoManager manager, string script)
        {
            //Generate signature
            var signature = manager.SignWithPrivateKey(Code, false, true, Algorithm);
            var fullSignature = $"{Algorithm}:\r\n{signature}";

            if (Code.IndexOf(Algorithm) > -1)
                Code = Code.Substring(0, Code.IndexOf(Algorithm)).Trim();

            var originalWithoutSign = script.Replace("\r\n", "\n");
            var sbreak = String.Empty;
            if (originalWithoutSign.IndexOf(Algorithm) > -1)
            {
                originalWithoutSign = originalWithoutSign.Substring(0, originalWithoutSign.IndexOf(Algorithm));
                if (originalWithoutSign.EndsWith("\n"))
                    ScriptWithSign = $"{originalWithoutSign.Replace("\n", "\r\n")}{fullSignature}";
                else
                    ScriptWithSign = $"{originalWithoutSign.Replace("\n", "\r\n")}\r\n{fullSignature}";
            }
            else
            {
                ScriptWithSign = $"{originalWithoutSign.Replace("\n", "\r\n")}\r\n{fullSignature}";
            }
        }

        public string GetSignature()
        {
            try
            {
                var text = OriginalScript.Replace("\r\n", "\n");
                if (!text.EndsWith(";"))
                    text = $"{text};";

                var signature = Regex.Match(text, $"{Algorithm}:\n([^;]*);", RegexOptions.Singleline).Groups[1].Value;
                return signature.Replace("\n", "\r\n");
            }
            catch(Exception ex)
            {
                logger.Error(ex, "The signature could not be read.");
                return null;
            }
        }
        #endregion
    }
}


text:
Useful Links

Main Web Site

PyPI packages

GitHub

Issue Tracker

Mailing List

Related Projects

BorgBackup


text:
package com.umeng.comm.ui.adapters;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;

import com.umeng.comm.core.constants.Constants;
import com.umeng.comm.core.imageloader.UMImageLoader;
import com.umeng.comm.core.sdkmanager.ImageLoaderManager;
import com.umeng.comm.core.utils.ToastMsg;
import com.umeng.comm.ui.adapters.viewholders.ImagePickerGvViewHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 在发布feed时选择图片的GridView适配器,选中图片的CheckBox会打上标识.
 */
public class ImagePickerGvAdapter extends CommonAdapter<String, ImagePickerGvViewHolder> {

    /**
     * 存储被选中的图片地址
     */
    private List<String> mSelectImagePaths = new ArrayList<String>();
    private UMImageLoader mImageLoader = null;
    private ImagePickerGvViewHolder mCurrentHolder = null;

    /**
     * 最大被选中的图片数目。目前最大选中图片数不能超过9张
     */
    private static final int MAX_IMAGE_NUM = 9;

    /**
     * @param context
     * @param list 所有图片的列表
     * @param selectedImagePaths 已选中的图片列表
     */
    public ImagePickerGvAdapter(Context context, Set<String> selectedImagePaths) {
        super(context);
        if (selectedImagePaths != null) {
            mSelectImagePaths.addAll(selectedImagePaths);
        }
        mImageLoader = ImageLoaderManager.getInstance().getCurrentSDK();
    }

    @Override
    protected ImagePickerGvViewHolder createViewHolder() {
        return new ImagePickerGvViewHolder();
    }

    /**
     * 获取所有选中的图片地址</br>
     *
     * @return 所有选择图片的地址
     */
    public List<String> getSelectImagePaths() {
        return mSelectImagePaths;
    }

    public void setSelectedImagePaths(Collection<String> paths) {
        mSelectImagePaths.clear();
        mSelectImagePaths.addAll(paths);
    }

    protected void setItemData(int position, ImagePickerGvViewHolder holder, View rootView) {
        mCurrentHolder = holder;
        final String item = getItem(position);
        holder.imageView.setTag(item);
        displayImage(item);
        dealCheckBoxLogic(rootView, item);
    }

    private void displayImage(String url) {
        mImageLoader.displayImage(url, mCurrentHolder.imageView);
        mImageLoader.resume();
    }

    private void dealCheckBoxLogic(View rootView, final String url) {
        final CheckBox tmpCheckBox = mCurrentHolder.checkBox;
        // 点击每项的事件
        rootView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                clickItemView(tmpCheckBox, url);
            }
        });

        // 如果是列表中包含该路径,那么代表该项为选中的.
        tmpCheckBox.setChecked(mSelectImagePaths.contains(url));
    }

    private void clickItemView(CheckBox tmpCheckBox, String url) {
        boolean status = tmpCheckBox.isChecked();
        if (!status) {
            // 此时被选中
            if (mSelectImagePaths.size() >= MAX_IMAGE_NUM) {
                if (!mSelectImagePaths.contains(Constants.ADD_IMAGE_PATH_SAMPLE)) {
                    ToastMsg.showShortMsgByResName(mContext, "umeng_comm_image_overflow");
                    return;
                }
                mSelectImagePaths.remove(Constants.ADD_IMAGE_PATH_SAMPLE);
            }
            // 如果"+图片"存在且在末尾,则将新增的图片放在"+图片"的前面
            mSelectImagePaths.add(url);
            int index = mSelectImagePaths.indexOf(Constants.ADD_IMAGE_PATH_SAMPLE);
            if (index >= 0 && index != mSelectImagePaths.size() - 1) {
                mSelectImagePaths.add(mSelectImagePaths.remove(index));
            }
        } else {
            // 取消选中的图片
            mSelectImagePaths.remove(url);
        }
        tmpCheckBox.setChecked(!status);
    }

}


text:
package network

// Copyright (c) Microsoft and contributors.  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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// VpnConnectionsClient is the network Client
type VpnConnectionsClient struct {
	BaseClient
}

// NewVpnConnectionsClient creates an instance of the VpnConnectionsClient client.
func NewVpnConnectionsClient(subscriptionID string) VpnConnectionsClient {
	return NewVpnConnectionsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewVpnConnectionsClientWithBaseURI creates an instance of the VpnConnectionsClient client using a custom endpoint.
// Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewVpnConnectionsClientWithBaseURI(baseURI string, subscriptionID string) VpnConnectionsClient {
	return VpnConnectionsClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// CreateOrUpdate creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing
// connection.
// Parameters:
// resourceGroupName - the resource group name of the VpnGateway.
// gatewayName - the name of the gateway.
// connectionName - the name of the connection.
// vpnConnectionParameters - parameters supplied to create or Update a VPN Connection.
func (client VpnConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, vpnConnectionParameters VpnConnection) (result VpnConnectionsCreateOrUpdateFuture, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.CreateOrUpdate")
		defer func() {
			sc := -1
			if result.Response() != nil {
				sc = result.Response().StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, gatewayName, connectionName, vpnConnectionParameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "CreateOrUpdate", nil, "Failure preparing request")
		return
	}

	result, err = client.CreateOrUpdateSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "CreateOrUpdate", nil, "Failure sending request")
		return
	}

	return
}

// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client VpnConnectionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string, vpnConnectionParameters VpnConnection) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"connectionName":    autorest.Encode("path", connectionName),
		"gatewayName":       autorest.Encode("path", gatewayName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2019-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	vpnConnectionParameters.Etag = nil
	preparer := autorest.CreatePreparer(
		autorest.AsContentType("application/json; charset=utf-8"),
		autorest.AsPut(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", pathParameters),
		autorest.WithJSON(vpnConnectionParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client VpnConnectionsClient) CreateOrUpdateSender(req *http.Request) (future VpnConnectionsCreateOrUpdateFuture, err error) {
	var resp *http.Response
	resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
	if err != nil {
		return
	}
	var azf azure.Future
	azf, err = azure.NewFutureFromResponse(resp)
	future.FutureAPI = &azf
	future.Result = func(client VpnConnectionsClient) (vc VpnConnection, err error) {
		var done bool
		done, err = future.DoneWithContext(context.Background(), client)
		if err != nil {
			err = autorest.NewErrorWithError(err, "network.VpnConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure")
			return
		}
		if !done {
			err = azure.NewAsyncOpIncompleteError("network.VpnConnectionsCreateOrUpdateFuture")
			return
		}
		sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
		if vc.Response.Response, err = future.GetResult(sender); err == nil && vc.Response.Response.StatusCode != http.StatusNoContent {
			vc, err = client.CreateOrUpdateResponder(vc.Response.Response)
			if err != nil {
				err = autorest.NewErrorWithError(err, "network.VpnConnectionsCreateOrUpdateFuture", "Result", vc.Response.Response, "Failure responding to request")
			}
		}
		return
	}
	return
}

// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client VpnConnectionsClient) CreateOrUpdateResponder(resp *http.Response) (result VpnConnection, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// Delete deletes a vpn connection.
// Parameters:
// resourceGroupName - the resource group name of the VpnGateway.
// gatewayName - the name of the gateway.
// connectionName - the name of the connection.
func (client VpnConnectionsClient) Delete(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (result VpnConnectionsDeleteFuture, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.Delete")
		defer func() {
			sc := -1
			if result.Response() != nil {
				sc = result.Response().StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.DeletePreparer(ctx, resourceGroupName, gatewayName, connectionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Delete", nil, "Failure preparing request")
		return
	}

	result, err = client.DeleteSender(req)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Delete", nil, "Failure sending request")
		return
	}

	return
}

// DeletePreparer prepares the Delete request.
func (client VpnConnectionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"connectionName":    autorest.Encode("path", connectionName),
		"gatewayName":       autorest.Encode("path", gatewayName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2019-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsDelete(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client VpnConnectionsClient) DeleteSender(req *http.Request) (future VpnConnectionsDeleteFuture, err error) {
	var resp *http.Response
	resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
	if err != nil {
		return
	}
	var azf azure.Future
	azf, err = azure.NewFutureFromResponse(resp)
	future.FutureAPI = &azf
	future.Result = func(client VpnConnectionsClient) (ar autorest.Response, err error) {
		var done bool
		done, err = future.DoneWithContext(context.Background(), client)
		if err != nil {
			err = autorest.NewErrorWithError(err, "network.VpnConnectionsDeleteFuture", "Result", future.Response(), "Polling failure")
			return
		}
		if !done {
			err = azure.NewAsyncOpIncompleteError("network.VpnConnectionsDeleteFuture")
			return
		}
		ar.Response = future.Response()
		return
	}
	return
}

// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client VpnConnectionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
		autorest.ByClosing())
	result.Response = resp
	return
}

// Get retrieves the details of a vpn connection.
// Parameters:
// resourceGroupName - the resource group name of the VpnGateway.
// gatewayName - the name of the gateway.
// connectionName - the name of the vpn connection.
func (client VpnConnectionsClient) Get(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (result VpnConnection, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.Get")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetPreparer(ctx, resourceGroupName, gatewayName, connectionName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "Get", resp, "Failure responding to request")
		return
	}

	return
}

// GetPreparer prepares the Get request.
func (client VpnConnectionsClient) GetPreparer(ctx context.Context, resourceGroupName string, gatewayName string, connectionName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"connectionName":    autorest.Encode("path", connectionName),
		"gatewayName":       autorest.Encode("path", gatewayName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2019-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client VpnConnectionsClient) GetSender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client VpnConnectionsClient) GetResponder(resp *http.Response) (result VpnConnection, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// ListByVpnGateway retrieves all vpn connections for a particular virtual wan vpn gateway.
// Parameters:
// resourceGroupName - the resource group name of the VpnGateway.
// gatewayName - the name of the gateway.
func (client VpnConnectionsClient) ListByVpnGateway(ctx context.Context, resourceGroupName string, gatewayName string) (result ListVpnConnectionsResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.ListByVpnGateway")
		defer func() {
			sc := -1
			if result.lvcr.Response.Response != nil {
				sc = result.lvcr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listByVpnGatewayNextResults
	req, err := client.ListByVpnGatewayPreparer(ctx, resourceGroupName, gatewayName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "ListByVpnGateway", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListByVpnGatewaySender(req)
	if err != nil {
		result.lvcr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "ListByVpnGateway", resp, "Failure sending request")
		return
	}

	result.lvcr, err = client.ListByVpnGatewayResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "ListByVpnGateway", resp, "Failure responding to request")
		return
	}
	if result.lvcr.hasNextLink() && result.lvcr.IsEmpty() {
		err = result.NextWithContext(ctx)
		return
	}

	return
}

// ListByVpnGatewayPreparer prepares the ListByVpnGateway request.
func (client VpnConnectionsClient) ListByVpnGatewayPreparer(ctx context.Context, resourceGroupName string, gatewayName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"gatewayName":       autorest.Encode("path", gatewayName),
		"resourceGroupName": autorest.Encode("path", resourceGroupName),
		"subscriptionId":    autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2019-09-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListByVpnGatewaySender sends the ListByVpnGateway request. The method will close the
// http.Response Body if it receives an error.
func (client VpnConnectionsClient) ListByVpnGatewaySender(req *http.Request) (*http.Response, error) {
	return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}

// ListByVpnGatewayResponder handles the response to the ListByVpnGateway request. The method always
// closes the http.Response Body.
func (client VpnConnectionsClient) ListByVpnGatewayResponder(resp *http.Response) (result ListVpnConnectionsResult, err error) {
	err = autorest.Respond(
		resp,
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listByVpnGatewayNextResults retrieves the next set of results, if any.
func (client VpnConnectionsClient) listByVpnGatewayNextResults(ctx context.Context, lastResults ListVpnConnectionsResult) (result ListVpnConnectionsResult, err error) {
	req, err := lastResults.listVpnConnectionsResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "listByVpnGatewayNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListByVpnGatewaySender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "listByVpnGatewayNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListByVpnGatewayResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.VpnConnectionsClient", "listByVpnGatewayNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListByVpnGatewayComplete enumerates all values, automatically crossing page boundaries as required.
func (client VpnConnectionsClient) ListByVpnGatewayComplete(ctx context.Context, resourceGroupName string, gatewayName string) (result ListVpnConnectionsResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/VpnConnectionsClient.ListByVpnGateway")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.ListByVpnGateway(ctx, resourceGroupName, gatewayName)
	return
}


text:
package com.sonian.elasticsearch.zookeeper.discovery;

import com.sonian.elasticsearch.zookeeper.client.ZooKeeperClient;
import com.sonian.elasticsearch.zookeeper.client.ZooKeeperClientService;
import com.sonian.elasticsearch.zookeeper.client.ZooKeeperEnvironment;
import com.sonian.elasticsearch.zookeeper.client.ZooKeeperFactory;
import com.sonian.elasticsearch.zookeeper.discovery.embedded.EmbeddedZooKeeperService;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.*;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.network.NetworkUtils;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.node.service.NodeService;
import org.testng.annotations.AfterMethod;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;

/**
 * @author imotov
 */
public abstract class AbstractZooKeeperTests {

    protected final ESLogger logger = Loggers.getLogger(getClass());

    protected EmbeddedZooKeeperService embeddedZooKeeperService;

    protected final List<ZooKeeperClient> zooKeeperClients = new ArrayList<ZooKeeperClient>();

    private Settings defaultSettings = ImmutableSettings
            .settingsBuilder()
            .put("cluster.name", "test-cluster-" + NetworkUtils.getLocalAddress().getHostName())
            .build();

    private ZooKeeperEnvironment environment;

    private ZooKeeperFactory zooKeeperFactory;

    public void putDefaultSettings(Settings.Builder settings) {
        putDefaultSettings(settings.build());
    }

    public void putDefaultSettings(Settings settings) {
        defaultSettings = ImmutableSettings.settingsBuilder().put(defaultSettings).put(settings).build();
    }

    public void startZooKeeper() throws IOException, InterruptedException {
        startZooKeeper(true);
    }

    public void startZooKeeper(boolean cleanDirectory) throws IOException, InterruptedException {
        Environment tempEnvironment = new Environment(defaultSettings);
        if (cleanDirectory) {
            File zooKeeperDataDirectory = new File(tempEnvironment.dataFiles()[0], "zookeeper");
            logger.info("Deleting zookeeper directory {}", zooKeeperDataDirectory);
            if (deleteDirectory(zooKeeperDataDirectory)) {
                logger.info("Zookeeper directory {} was deleted", zooKeeperDataDirectory);
            }
        }
        embeddedZooKeeperService = new EmbeddedZooKeeperService(defaultSettings, tempEnvironment);
        embeddedZooKeeperService.start();
        putDefaultSettings(ImmutableSettings.settingsBuilder()
                .put(defaultSettings)
                .put("sonian.elasticsearch.zookeeper.client.host", "localhost:" + embeddedZooKeeperService.port()));

        zooKeeperFactory = new ZooKeeperFactory(defaultSettings);
        environment = new ZooKeeperEnvironment(defaultSettings, ClusterName.clusterNameFromSettings(defaultSettings));
    }

    public void stopZooKeeper() {
        if (embeddedZooKeeperService != null) {
            embeddedZooKeeperService.stop();
            embeddedZooKeeperService.close();
            embeddedZooKeeperService = null;
        }
    }

    public void restartZooKeeper() throws IOException, InterruptedException {
        logger.info("*** ZOOKEEPER RESTART ***");
        stopZooKeeper();
        Thread.sleep(1000);
        startZooKeeper(false);
    }

    @AfterMethod
    public void stopZooKeeperClients() {
        for (ZooKeeperClient zooKeeperClient : zooKeeperClients) {
            logger.info("Closing {}" + zooKeeperClient);
            zooKeeperClient.stop();
            zooKeeperClient.close();
        }
        zooKeeperClients.clear();
    }

    public ZooKeeperClient buildZooKeeper() {
        return buildZooKeeper(ImmutableSettings.Builder.EMPTY_SETTINGS);
    }

    public ZooKeeperClient buildZooKeeper(Settings settings) {
        String settingsSource = getClass().getName().replace('.', '/') + ".yml";
        Settings finalSettings = settingsBuilder()
                .loadFromClasspath(settingsSource)
                .put(defaultSettings)
                .put(settings)
                .build();
        ZooKeeperEnvironment environment = new ZooKeeperEnvironment(finalSettings, ClusterName.clusterNameFromSettings(defaultSettings));
        ZooKeeperClient zooKeeperClient = new ZooKeeperClientService(finalSettings, environment, zooKeeperFactory);
        zooKeeperClient.start();
        zooKeeperClients.add(zooKeeperClient);
        return zooKeeperClient;
    }

    public ZooKeeperFactory zooKeeperFactory() {
        return zooKeeperFactory;
    }

    public ZooKeeperEnvironment zooKeeperEnvironment() {
        return environment;
    }

    public Settings defaultSettings() {
        return defaultSettings;
    }

    private boolean deleteDirectory(File path) {
        if (path.exists()) {
            File[] files = path.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    if (!deleteDirectory(file)) {
                        return false;
                    }
                } else {
                    if (!file.delete()) {
                        return false;
                    }
                }
            }
            return path.delete();
        }
        return false;
    }

    protected ClusterState testClusterState(RoutingTable routingTable, DiscoveryNodes nodes) {
        return ClusterState.builder(ClusterName.clusterNameFromSettings(defaultSettings))
                .version(1234L)
                .routingTable(routingTable)
                .nodes(nodes)
                .build();
    }

    protected DiscoveryNodes testDiscoveryNodes() {
        return DiscoveryNodes.builder()
                .masterNodeId("localnodeid")
                .build();
    }

    protected RoutingTable testRoutingTable() {
        RoutingTable.Builder routingTableBuilder = RoutingTable.builder();
        for (int i = 0; i < 1000; i++) {
            IndexRoutingTable.Builder indexRoutingTableBuilder = new IndexRoutingTable.Builder("index");
            for (int j = 0; j < 100; j++) {
                ShardId shardId = new ShardId("index", j);
                IndexShardRoutingTable.Builder indexShardRoutingTableBuilder = new IndexShardRoutingTable.Builder(shardId, true);
                ImmutableShardRouting shardRouting = new ImmutableShardRouting("index", j, "i" + i + "s" + j, true, ShardRoutingState.STARTED, 0L);
                indexShardRoutingTableBuilder.addShard(shardRouting);
                indexRoutingTableBuilder.addShard(indexShardRoutingTableBuilder.build(), shardRouting);
            }
            routingTableBuilder.add(indexRoutingTableBuilder);
        }

        return routingTableBuilder
                .build();
    }

    protected ZooKeeperClusterState buildZooKeeperClusterState(DiscoveryNodes nodes) {
        return buildZooKeeperClusterState(nodes, null);
    }

    protected ZooKeeperClusterState buildZooKeeperClusterState(final DiscoveryNodes nodes, String clusterStateVersion) {
        DiscoveryNodesProvider provider = new DiscoveryNodesProvider() {
            @Override
            public DiscoveryNodes nodes() {
                return nodes;
            }

            @Override
            public NodeService nodeService() {
                return null;
            }
        };
        ZooKeeperClient zk = buildZooKeeper(defaultSettings());
        if (clusterStateVersion != null) {
            return new ZooKeeperClusterStateVersionOverride(clusterStateVersion, defaultSettings(), zooKeeperEnvironment(),
                    zk,
                    provider
            );
        } else {
            return new ZooKeeperClusterState(defaultSettings(),
                    zooKeeperEnvironment(),
                    zk,
                    provider,
                    ClusterName.clusterNameFromSettings(defaultSettings)
            );
        }
    }

    private class ZooKeeperClusterStateVersionOverride extends ZooKeeperClusterState {

        private final String clusterStateVersion;

        public ZooKeeperClusterStateVersionOverride(String clusterStateVersion, Settings settings,
                                                    ZooKeeperEnvironment environment, ZooKeeperClient zooKeeperClient,
                                                    DiscoveryNodesProvider nodesProvider) {
            super(settings, environment, zooKeeperClient, nodesProvider, ClusterName.clusterNameFromSettings(defaultSettings));
            this.clusterStateVersion = clusterStateVersion;
        }

        @Override
        protected String clusterStateVersion() {
            return clusterStateVersion;
        }
    }

    protected static class NoOpAckListener implements Discovery.AckListener {
        @Override
        public void onNodeAck(DiscoveryNode node, @Nullable Throwable t) {
        }

        @Override
        public void onTimeout() {
        }
    }

}


text:
  //==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012 - 2014 MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_AVX_FAST_RSQRT_HPP_INCLUDED
#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_AVX_FAST_RSQRT_HPP_INCLUDED
#ifdef BOOST_SIMD_HAS_AVX_SUPPORT

#include <boost/simd/arithmetic/functions/fast_rsqrt.hpp>
#include <boost/simd/include/functions/simd/multiplies.hpp>
#include <boost/simd/include/functions/simd/minus.hpp>
#include <boost/simd/include/functions/simd/sqr.hpp>
#include <boost/dispatch/attributes.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION ( boost::simd::tag::fast_rsqrt_
                                    , boost::simd::tag::avx_
                                    , (A0)
                                    , ((simd_ < single_<A0>
                                              , boost::simd::tag::avx_
                                              >
                                      ))
                                    )
  {
    typedef A0 result_type;

    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const
    {
      result_type nr  = _mm256_rsqrt_ps( a0 );
                  nr *= 0.5f * (3.f - a0 * sqr(nr));

      return nr;
    }
  };
} } }

#endif

#endif


text:
<?php

namespace LiveCMS\Models;

use Illuminate\Database\Eloquent\Model;
use LiveCMS\Models\Traits\AdminModelTrait;

class TeamMediaSocial extends Model
{
    use AdminModelTrait;

    protected $fillable = ['social', 'url'];

    protected $socials = ['facebook', 'twitter', 'instagram', 'google-plus', 'linkedin', 'github'];

    public function socials()
    {
        return $this->socials;
    }
}


text:
package persistentvolume

import (
	"reflect"
	"testing"

	"github.com/kubernetes/dashboard/src/app/backend/resource/common"
	"github.com/kubernetes/dashboard/src/app/backend/resource/dataselect"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	api "k8s.io/client-go/pkg/api/v1"
)

func TestGetPersistentVolumeList(t *testing.T) {
	cases := []struct {
		persistentVolumes []api.PersistentVolume
		expected          *PersistentVolumeList
	}{
		{nil, &PersistentVolumeList{Items: []PersistentVolume{}}},
		{
			[]api.PersistentVolume{
				{
					ObjectMeta: metaV1.ObjectMeta{Name: "foo"},
					Spec: api.PersistentVolumeSpec{
						PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimRecycle,
						AccessModes:                   []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
						ClaimRef: &api.ObjectReference{
							Name:      "myclaim-name",
							Namespace: "default",
						},
						Capacity: nil,
					},
					Status: api.PersistentVolumeStatus{
						Phase:  api.VolumePending,
						Reason: "my-reason",
					},
				},
			},
			&PersistentVolumeList{
				ListMeta: common.ListMeta{TotalItems: 1},
				Items: []PersistentVolume{{
					TypeMeta:    common.TypeMeta{Kind: "persistentvolume"},
					ObjectMeta:  common.ObjectMeta{Name: "foo"},
					Capacity:    nil,
					AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
					Status:      api.VolumePending,
					Claim:       "default/myclaim-name",
					Reason:      "my-reason",
				}},
			},
		},
	}
	for _, c := range cases {
		actual := getPersistentVolumeList(c.persistentVolumes, dataselect.NoDataSelect)
		if !reflect.DeepEqual(actual, c.expected) {
			t.Errorf("getPersistentVolumeList(%#v) == \n%#v\nexpected \n%#v\n",
				c.persistentVolumes, actual, c.expected)
		}
	}
}