text:
'use strict';

angular.module('sandstone.filebrowser')

.directive('fbFileDetails', [function() {
  return {
    restrict: 'A',
    scope: {},
    templateUrl: '/static/filebrowser/fb-filedetails/fb-filedetails.html',
    controller: ['$scope', '$element', '$uibModal', 'FilesystemService', 'FilebrowserService', 'BroadcastService', 'AlertService', function($scope,$element,$uibModal,FilesystemService,FilebrowserService,BroadcastService,AlertService) {
      var self = $scope;

      var permStringToModel = function(perms) {
        var permModel = {};
        for (var i=0;i<9;i++) {
          permModel[i] = (perms[i] !== '-')
        }
        return permModel;
      };

      self.filesystem = {};
      $scope.$watch(function() {
        return FilebrowserService.getFilesystem();
      }, function(newValue) {
        self.filesystem = newValue;
      });

      self.selection = {};
      self.editFile = {};
      $scope.$watch(function() {
        return FilebrowserService.getSelection();
      }, function(newValue) {
        self.selection = newValue;
        // Create a deep copy of the selected file for editing
        if(!self.selection.selectedFile) {
          self.editFile = {};
        } else {
          self.editFile = angular.copy(newValue.selectedFile);
          if (self.editFile) {
            self.editFile.permModel = permStringToModel(self.editFile.permissions);

            if (self.editFile.type === 'file') {
              self.downloadUrl = FilesystemService.getFileDownloadLink(self.editFile.filepath);
            } else {
              self.downloadUrl = undefined;
            }
          }
        }
      },true);

      // File Details
      self.editingName = false;
      self.renameFile = function() {
        FilesystemService
          .rename(self.selection.selectedFile.filepath,self.editFile.name)
          .then(function(newpath) {
            // Update file details prior to reselection since the
            // filepath has now changed.
            FilesystemService
              .getFileDetails(newpath)
              .then(function(file) {
                angular.extend(self.selection.selectedFile,file);
                FilebrowserService.setSelectedFile(self.selection.selectedFile);
              },
              function(data) {
                AlertService.addAlert({
                  type: 'warning',
                  message: 'Failed to retrieve file details.'
                });
                FilebrowserService.setSelectedFile();
              });
          },
          function(data) {
            // Show an alert and roll back changes to the editFile
            AlertService.addAlert({
              type: 'danger',
              message: 'Error while trying to rename file.'
            });
            self.editFile.name = self.selection.selectedFile.name;
          });
      };

      self.changeGroup = function() {
        FilesystemService
          .changeGroup(self.selection.selectedFile.filepath,self.editFile.group)
          .then(function() {
            self.selection.selectedFile.group = self.editFile.group;
            FilebrowserService.setSelectedFile(self.selection.selectedFile);
          },
          function(data) {
            // Show an alert and roll back changes to the editFile
            AlertService.addAlert({
              type: 'danger',
              message: 'Error while trying to change group.'
            });
            self.editFile.group = self.selection.selectedFile.group;
          });
      }

      self.changePermissions = function() {
        var base = 'rwxrwxrwx';
        var perms = '';
        for (var i=0;i<9;i++) {
          if (!self.editFile.permModel[i]) {
            perms = perms + '-';
          } else {
            perms = perms + base[i];
          }
        }
        FilesystemService
          .changePermissions(self.selection.selectedFile.filepath,perms)
          .then(function() {
            self.selection.selectedFile.permissions = perms;
            FilebrowserService.setSelectedFile(self.selection.selectedFile);
          },
          function(data) {
            // Show an alert and roll back changes to the editFile
            AlertService.addAlert({
              type: 'danger',
              message: 'Error while trying to change permissions.'
            });
            self.editFile.permModel = permStringToModel(self.selection.selectedFile.permissions);
          });
      };

      self.openInEditor = function() {
        var message = {
            key: 'editor:open-document',
            data: {
                filepath: self.selection.selectedFile.filepath
            }
        };
        BroadcastService.sendMessage(message);
        window.location.href = '#/editor';
      };

      self.duplicate = function() {
        var cwd = self.selection.cwd;
        var dupFile = self.selection.selectedFile;
        var basepath = FilesystemService.join(cwd.filepath,dupFile.name);
        var exists = false;
        var i = 0;
        var suffix;
        do {
          i++;
          exists = false;
          suffix = ' ('+i+')';
          for (var ci=0;ci<cwd.contents.length;ci++) {
            if (cwd.contents[ci].filepath === (basepath + suffix)) {
              exists = true;
              break;
            }
          }
        } while (exists);
        FilesystemService
          .copy(self.selection.selectedFile.filepath,basepath+suffix)
          .then(function(copypath) {
            FilebrowserService.setSelectedFile(self.selection.selectedFile);
          },
          function(data) {
            AlertService.addAlert({
              type: 'danger',
              message: 'Failed to duplicate file.'
            });
          });
      };

      self.move = function() {
        self.moveModalInstance = $uibModal.open({
          templateUrl: '/static/filebrowser/templates/move-modal.html',
          backdrop: 'static',
          keyboard: false,
          size: 'lg',
          controller: 'MoveModalInstanceCtrl',
          controllerAs: 'ctrl',
          resolve: {
            file: function () {
              return self.selection.selectedFile
            }
          }
        });

        self.moveModalInstance.result.then(function (newpath) {
          FilesystemService
            .move(self.selection.selectedFile.filepath,newpath)
            .then(function(filepath) {},
            function(data) {
              AlertService.addAlert({
                type: 'danger',
                message: 'Failed to move file.'
              });
            });
        });
      };

      self.delete = function() {
        self.deleteModalInstance = $uibModal.open({
          templateUrl: '/static/filebrowser/templates/delete-modal.html',
          backdrop: 'static',
          keyboard: false,
          controller: 'DeleteModalInstanceCtrl as ctrl',
          resolve: {
            file: function () {
              return self.selection.selectedFile;
            }
          }
        });

        self.deleteModalInstance.result.then(function (file) {
          FilesystemService
            .delete(self.selection.selectedFile.filepath)
            .then(function() {
              FilebrowserService.setSelectedFile();
            },
            function(data) {
              AlertService.addAlert({
                type: 'danger',
                message: 'Failed to delete file.'
              });
            });
        }, function () {
          self.deleteModalInstance = null;
        });
      };

    }]
  };
}]);


text:
package org.apache.geode.internal.cache.tier.sockets.command;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import org.apache.geode.CancelException;
import org.apache.geode.cache.TransactionInDoubtException;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.Assert;
import org.apache.geode.internal.cache.TXCommitMessage;
import org.apache.geode.internal.cache.TXId;
import org.apache.geode.internal.cache.TXManagerImpl;
import org.apache.geode.internal.cache.TXStateProxy;
import org.apache.geode.internal.cache.tier.Command;
import org.apache.geode.internal.cache.tier.MessageType;
import org.apache.geode.internal.cache.tier.sockets.BaseCommand;
import org.apache.geode.internal.cache.tier.sockets.Message;
import org.apache.geode.internal.cache.tier.sockets.ServerConnection;
import org.apache.geode.internal.security.SecurityService;

/**
 * This is the base command which read the parts for the MessageType.COMMIT.<br>
 *
 * @since GemFire 6.6
 */
public class CommitCommand extends BaseCommand {

  private static final CommitCommand singleton = new CommitCommand();

  public static Command getCommand() {
    return singleton;
  }

  private CommitCommand() {}

  @Override
  public void cmdExecute(final Message clientMessage, final ServerConnection serverConnection,
      final SecurityService securityService, long start) throws IOException {

    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    TXManagerImpl txMgr = (TXManagerImpl) serverConnection.getCache().getCacheTransactionManager();
    InternalDistributedMember client =
        (InternalDistributedMember) serverConnection.getProxyID().getDistributedMember();
    int uniqId = clientMessage.getTransactionId();
    TXId txId = new TXId(client, uniqId);
    TXCommitMessage commitMsg = txMgr.getRecentlyCompletedMessage(txId);
    if (commitMsg != null) {
      if (logger.isDebugEnabled()) {
        logger.debug("TX: returning a recently committed txMessage for tx: {}", txId);
      }
      if (!txMgr.isExceptionToken(commitMsg)) {
        writeCommitResponse(commitMsg, clientMessage, serverConnection);
        commitMsg.setClientVersion(null); // fixes bug 46529
        serverConnection.setAsTrue(RESPONDED);
      } else {
        sendException(clientMessage, serverConnection, txMgr.getExceptionForToken(commitMsg, txId));
      }
      txMgr.removeHostedTXState(txId);
      return;
    }
    boolean wasInProgress = txMgr.setInProgress(true); // fixes bug 43350
    final TXStateProxy txProxy = txMgr.getTXState();
    Assert.assertTrue(txProxy != null);
    if (logger.isDebugEnabled()) {
      logger.debug("TX: committing client tx: {}", txId);
    }
    commitTransaction(clientMessage, serverConnection, txMgr, wasInProgress,
        txProxy);
  }

  protected void commitTransaction(Message clientMessage, ServerConnection serverConnection,
      TXManagerImpl txMgr,
      boolean wasInProgress, TXStateProxy txProxy) throws IOException {
    Exception txException = null;
    TXCommitMessage commitMsg = null;
    TXId txId = txProxy.getTxId();
    try {
      txProxy.setCommitOnBehalfOfRemoteStub(true);
      txMgr.commit();

      commitMsg = txProxy.getCommitMessage();
      logger.debug("Sending commit response to client: {}", commitMsg);
      writeCommitResponse(commitMsg, clientMessage, serverConnection);
      serverConnection.setAsTrue(RESPONDED);

    } catch (Exception e) {
      txException = e;
    } finally {
      if (txId != null) {
        txMgr.removeHostedTXState(txId);
      }
      if (!wasInProgress) {
        txMgr.setInProgress(false);
      }
      if (commitMsg != null) {
        commitMsg.setClientVersion(null); // fixes bug 46529
      }
    }
    if (txException != null) {
      DistributedMember target = txProxy.getTarget();
      // a TransactionInDoubtException caused by the TX host shutting down means that
      // the transaction may still be active and hold locks. We must wait for the transaction
      // host to finish shutting down before responding to the client or it could encounter
      // conflicts in retrying the transaction
      try {
        if ((txException instanceof TransactionInDoubtException)
            && (txException.getCause() instanceof CancelException)) {
          // base the wait time on the client's read-timeout setting so that we respond before
          // it gives up reading. Since we've already done a commit we've eaten up some time
          // so we use a WAG of half the read-timeout
          int timeToWait = serverConnection.getHandshake().getClientReadTimeout() / 2;
          if (timeToWait < 0) {
            return;
          }
          logger.info(
              "Waiting up to {}ms for departure of {} before throwing TransactionInDoubtException.",
              timeToWait, target);
          try {
            serverConnection.getCache().getDistributionManager().getMembershipManager()
                .waitForDeparture(target, timeToWait);
          } catch (TimeoutException e) {
            // status will be logged below
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          }
          logger.info("Done waiting.  Transaction host {} in the cluster.",
              serverConnection.getCache().getDistributionManager().isCurrentMember(target)
                  ? "is still"
                  : "is no longer");
        }
      } finally {
        sendException(clientMessage, serverConnection, txException);
      }
    }
  }

  protected static void writeCommitResponse(TXCommitMessage response, Message origMsg,
      ServerConnection servConn) throws IOException {
    Message responseMsg = servConn.getResponseMessage();
    responseMsg.setMessageType(MessageType.RESPONSE);
    responseMsg.setTransactionId(origMsg.getTransactionId());
    responseMsg.setNumberOfParts(1);
    if (response != null) {
      response.setClientVersion(servConn.getClientVersion());
    }
    responseMsg.addObjPart(response, false);
    servConn.getCache().getCancelCriterion().checkCancelInProgress(null);
    if (logger.isDebugEnabled()) {
      logger.debug("TX: sending a nonNull response for transaction: {}",
          new TXId((InternalDistributedMember) servConn.getProxyID().getDistributedMember(),
              origMsg.getTransactionId()));
    }
    responseMsg.send(servConn);
    origMsg.clearParts();
  }

  private void sendException(Message msg, ServerConnection servConn, Throwable e)
      throws IOException {
    writeException(msg, MessageType.EXCEPTION, e, false, servConn);
    servConn.setAsTrue(RESPONDED);
  }

}

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.cloud.netflix.zuul.filters.post;

import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import com.netflix.zuul.context.RequestContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.StaticServerList;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.netflix.zuul.test.NoSecurityConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

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

/**
 * @author Biju Kunjummen
 */

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
		"zuul.routes.aservice.path:/service/**", "zuul.routes.aservice.strip-prefix:true",
		"eureka.client.enabled:false" })
@DirtiesContext
public class LocationRewriteFilterIntegrationTests {

	@LocalServerPort
	private int port;

	@Before
	public void before() {
		RequestContext context = new RequestContext();
		RequestContext.testSetCurrentContext(context);
	}

	@Test
	public void testWithRedirectPrefixStripped() {
		String url = "http://localhost:" + port + "/service/redirectingUri";
		ResponseEntity<String> response = new TestRestTemplate().getForEntity(url,
				String.class);
		assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND);
		List<String> locationHeaders = response.getHeaders().get("Location");

		assertThat(locationHeaders).hasSize(1);
		String locationHeader = locationHeaders.get(0);
		assertThat(locationHeader).withFailMessage("Location should have prefix")
				.isEqualTo(
						String.format("http://localhost:%d/service/redirectedUri", port));

	}

	@SpringBootConfiguration
	@EnableAutoConfiguration
	@EnableZuulProxy
	@Controller
	@RibbonClient(name = "aservice", configuration = RibbonConfig.class)
	@Import(NoSecurityConfiguration.class)
	protected static class Config {

		@RequestMapping("/redirectingUri")
		public String redirect1() {
			return "redirect:/redirectedUri";
		}

		@Bean
		public LocationRewriteFilter locationRewriteFilter() {
			return new LocationRewriteFilter();
		}

	}

	public static class RibbonConfig {
		@LocalServerPort
		private int port;

		@Bean
		public ServerList<Server> ribbonServerList() {
			return new StaticServerList<>(new Server("localhost", this.port));
		}

	}
}


text:
namespace Microsoft.Azure.Management.Synapse
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for SqlPoolWorkloadGroupOperations.
    /// </summary>
    public static partial class SqlPoolWorkloadGroupOperationsExtensions
    {
            /// <summary>
            /// Sql pool's workload group
            /// </summary>
            /// <remarks>
            /// Get a Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            public static WorkloadGroup Get(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName)
            {
                return operations.GetAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Sql pool's workload group
            /// </summary>
            /// <remarks>
            /// Get a Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<WorkloadGroup> GetAsync(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Create Or Update workload group
            /// </summary>
            /// <remarks>
            /// Create Or Update a Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            /// <param name='parameters'>
            /// The requested workload group state.
            /// </param>
            public static WorkloadGroup CreateOrUpdate(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName, WorkloadGroup parameters)
            {
                return operations.CreateOrUpdateAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, parameters).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Create Or Update workload group
            /// </summary>
            /// <remarks>
            /// Create Or Update a Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            /// <param name='parameters'>
            /// The requested workload group state.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<WorkloadGroup> CreateOrUpdateAsync(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName, WorkloadGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Remove workload group
            /// </summary>
            /// <remarks>
            /// Remove Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            public static void Delete(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName)
            {
                operations.DeleteAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Remove workload group
            /// </summary>
            /// <remarks>
            /// Remove Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task DeleteAsync(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Sql pool's workload groups
            /// </summary>
            /// <remarks>
            /// Get list of  Sql pool's workload groups.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            public static IPage<WorkloadGroup> List(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName)
            {
                return operations.ListAsync(resourceGroupName, workspaceName, sqlPoolName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Sql pool's workload groups
            /// </summary>
            /// <remarks>
            /// Get list of  Sql pool's workload groups.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<WorkloadGroup>> ListAsync(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, workspaceName, sqlPoolName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Create Or Update workload group
            /// </summary>
            /// <remarks>
            /// Create Or Update a Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            /// <param name='parameters'>
            /// The requested workload group state.
            /// </param>
            public static WorkloadGroup BeginCreateOrUpdate(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName, WorkloadGroup parameters)
            {
                return operations.BeginCreateOrUpdateAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, parameters).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Create Or Update workload group
            /// </summary>
            /// <remarks>
            /// Create Or Update a Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            /// <param name='parameters'>
            /// The requested workload group state.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<WorkloadGroup> BeginCreateOrUpdateAsync(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName, WorkloadGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Remove workload group
            /// </summary>
            /// <remarks>
            /// Remove Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            public static void BeginDelete(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName)
            {
                operations.BeginDeleteAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Remove workload group
            /// </summary>
            /// <remarks>
            /// Remove Sql pool's workload group.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='sqlPoolName'>
            /// SQL pool name
            /// </param>
            /// <param name='workloadGroupName'>
            /// The name of the workload group.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task BeginDeleteAsync(this ISqlPoolWorkloadGroupOperations operations, string resourceGroupName, string workspaceName, string sqlPoolName, string workloadGroupName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Sql pool's workload groups
            /// </summary>
            /// <remarks>
            /// Get list of  Sql pool's workload groups.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static IPage<WorkloadGroup> ListNext(this ISqlPoolWorkloadGroupOperations operations, string nextPageLink)
            {
                return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Sql pool's workload groups
            /// </summary>
            /// <remarks>
            /// Get list of  Sql pool's workload groups.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<WorkloadGroup>> ListNextAsync(this ISqlPoolWorkloadGroupOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


text:
"use strict";
/* global describe,it,before,after,beforeEach,afterEach*/
require("requirish")._(module);

var async = require("async");
var should = require("should");
var build_server_with_temperature_device = require("test/helpers/build_server_with_temperature_device").build_server_with_temperature_device;
var perform_operation_on_client_session = require("test/helpers/perform_operation_on_client_session").perform_operation_on_client_session;

var opcua = require("index");
var makeNodeId = opcua.makeNodeId;
var DataType = opcua.DataType;
var AttributeIds = opcua.AttributeIds;
var OPCUAClient = opcua.OPCUAClient;

var address_space_for_conformance_testing = require("lib/simulation/address_space_for_conformance_testing");
var build_address_space_for_conformance_testing = address_space_for_conformance_testing.build_address_space_for_conformance_testing;

function sameVariant(v1, v2) {
    if (v1.dataType !== v2.dataType) {
        return false;
    }
    if (v1.arrayType !== v2.arrayType) {
        return false;
    }
    if (v1.value !== v2.value) {
        return false;
    }
    return true;
}

function sameDate(d1, d2) {
    if (!d1) {
        return !d2;
    }
    if (!d2) {
        return !d1;
    }
    return d1.getTime() === d2.getTime();
}

function sameDataValue(dv1, dv2) {

    if (dv1.statusCode !== dv2.statusCode) {
        return false;
    }

    if (!sameVariant(dv1.statusCode, dv2.statusCode)) {
        return false;
    }
    return true;
}
describe("end-to-end testing of read and write operation on a Variable", function () {
    var server, client, temperatureVariableId, endpointUrl;

    var port = 2555;

    before(function (done) {
        server = build_server_with_temperature_device({port: port}, function (err) {

            build_address_space_for_conformance_testing(server.engine, {mass_variables: false});

            endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
            temperatureVariableId = server.temperatureVariableId;
            done(err);
        });
    });

    beforeEach(function (done) {
        client = new OPCUAClient();
        done();
    });

    afterEach(function (done) {
        client = null;
        done();
    });

    after(function (done) {
        server.shutdown(done);
    });

    var namespaceIndex = 411;

    function test_write_read_cycle(client, dataValue, done) {

        perform_operation_on_client_session(client, endpointUrl, function (session, inner_done) {

            var nodeId = makeNodeId("Scalar_Static_Float", namespaceIndex);

            var nodesToWrite = [
                {
                    nodeId: nodeId,
                    attributeId: opcua.AttributeIds.Value,
                    indexRange: null,
                    value: dataValue
                }
            ];
            session.write(nodesToWrite, function (err, results) {

                if (err) {
                    return inner_done(err);
                }
                results.length.should.eql(1);
                results[0].should.eql(opcua.StatusCodes.Good);

                var nodesToRead = [
                    {
                        nodeId: nodeId,
                        attributeId: opcua.AttributeIds.Value,
                        indexRange: null,
                        dataEncoding: null
                    }
                ];
                session.read(nodesToRead, function (err, r, results) {
                    console.log(results[0].toString());

                    // verify that value and status codes are identical
                    if (!sameDataValue(dataValue, results[0])) {
                        console.log(" ------- > expected".yellow);
                        console.log(dataValue.toString().yellow);
                        console.log(" ------- > actuel".cyan);
                        console.log(results[0].toString().cyan);
                        // dataValue.toString().split("\n").should.eql(results[0].toString().split("\n"));
                        return inner_done(new Error("dataValue is not as expected"));
                    }
                    // verify that server provides a valid serverTimestamp and sourceTimestamp, regardless
                    // of what we wrote into the variable
                    results[0].serverTimestamp.should.be.instanceOf(Date);
                    results[0].sourceTimestamp.should.be.instanceOf(Date);
                    inner_done(err);
                });
            });

        }, done);

    }

    it("writing dataValue case 1", function (done) {

        var dataValue = new opcua.DataValue({
            serverTimestamp: new Date(2015, 5, 2),
            serverPicoseconds: 20,
            sourceTimestamp: new Date(2015, 5, 3),
            sourcePicoseconds: 30,
            value: {
                dataType: opcua.DataType.Float,
                value: 32.0
            }
        });
        test_write_read_cycle(client, dataValue, done);

    });
    it("writing dataValue case 2", function (done) {

        var dataValue = new opcua.DataValue({
            serverTimestamp: null,
            serverPicoseconds: 0,
            sourceTimestamp: new Date(2015, 5, 3),
            sourcePicoseconds: 30,
            value: {
                dataType: opcua.DataType.Float,
                value: 32.0
            }
        });
        test_write_read_cycle(client, dataValue, done);

    });
    it("writing dataValue case 3", function (done) {

        var dataValue = new opcua.DataValue({
            serverTimestamp: null,
            serverPicoseconds: 0,
            sourceTimestamp: null,
            sourcePicoseconds: 0,
            value: {
                dataType: opcua.DataType.Float,
                value: 32.0
            }
        });
        test_write_read_cycle(client, dataValue, done);

    });

    it("ZZZ reading ns=411;s=Scalar_Static_Int16 ", function (done) {
        perform_operation_on_client_session(client, endpointUrl, function (session, inner_done) {
            var nodeId = makeNodeId("Scalar_Static_Int16", namespaceIndex);

            var nodesToRead = [
                {
                    nodeId: nodeId,
                    attributeId: opcua.AttributeIds.Value,
                    indexRange: null,
                    dataEncoding: null
                }
            ];

            var maxAge = 10;

            async.series([
                function (callback) {
                    var request = new opcua.read_service.ReadRequest({
                        nodesToRead: nodesToRead,
                        maxAge: maxAge,
                        timestampsToReturn: opcua.read_service.TimestampsToReturn.Both
                    });

                    session.performMessageTransaction(request, function (err, response) {
                        console.log(response.results[0].toString());
                        callback(err);
                    });

                },
                function (callback) {
                    var request = new opcua.read_service.ReadRequest({
                        nodesToRead: nodesToRead,
                        maxAge: maxAge,
                        timestampsToReturn: opcua.read_service.TimestampsToReturn.Both
                    });

                    session.performMessageTransaction(request, function (err, response) {
                        console.log(response.results[0].toString());
                        callback(err);
                    });

                },
                function (callback) {

                    var request = new opcua.read_service.ReadRequest({
                        nodesToRead: nodesToRead,
                        maxAge: maxAge,
                        timestampsToReturn: opcua.read_service.TimestampsToReturn.Server
                    });

                    session.performMessageTransaction(request, function (err, response) {
                        console.log(response.results[0].toString());
                        callback(err);
                    });
                }
            ], inner_done);
        }, done);
    });

    xit("#read test maxAge", function (done) {
        done();
    });

    describe("Performance of reading large array", function () {

        it("PERF - READ testing performance of large array", function (done) {

            perform_operation_on_client_session(client, endpointUrl, function (session, inner_done) {

                var nodeId = makeNodeId("Scalar_Static_Large_Array_Float", namespaceIndex);

                var nodesToRead = [
                    {
                        nodeId: nodeId,
                        attributeId: opcua.AttributeIds.Value,
                        indexRange: null,
                        dataEncoding: null
                    }
                ];
                session.read(nodesToRead, function (err, r, results) {
                    console.log(results[0].toString());

                    inner_done(err);
                });

            }, done);
        });
        it("PERF - WRITE testing performance of large array", function (done) {

            perform_operation_on_client_session(client, endpointUrl, function (session, inner_done) {

                var nodeId = makeNodeId("Scalar_Static_Large_Array_Float", namespaceIndex);
                var nodesToRead = [
                    {
                        nodeId: nodeId,
                        attributeId: opcua.AttributeIds.Value,
                        indexRange: null,
                        dataEncoding: null
                    }
                ];
                session.read(nodesToRead, function (err, r, results) {

                    if(err) { return inner_done(err); }

                    console.log(results[0].toString());

                    var variant = results[0].value;
                    variant.value[1] = 2;
                    variant.value[3] = 2;
                    variant.value[4] = 2;
                    console.log(results[0].toString());
                    var nodesToWrite = [
                        {
                            nodeId: nodeId,
                            attributeId: opcua.AttributeIds.Value,
                            indexRange: null,
                            value: results[0]
                        }
                    ];
                    session.write(nodesToWrite, function (err) {
                        if(err) { return inner_done(err); }

                        console.log(nodesToWrite[0].value.value.value.constructor.name);

                        nodesToWrite[0].value.value.value.should.be.instanceof(Float32Array);
                        nodesToWrite[0].value.value.value = new Float32Array(1024 * 1024);
                        session.write(nodesToWrite, function (err) {
                            if(err) { return inner_done(err); }
                            session.read(nodesToRead, function (err, r, results) {
                                console.log(results[0].toString());
                                inner_done(err);
                            });
                        });
                    });

                });
            }, done);
        });
    });
});


text:
```javascript
import { init, net, src } from 'mosi/bp';

let count = 0;

init({
  actions: (src) => ({
    INCREMENT: (increment = 1) => {
      count += increment;
      net('count').msg('NEW_COUNT', count);
    },
    COUNT: () => {
      net(src).msg('NEW_COUNT', count);
    }
  }
});
```

## content_script.js

```javascript
import { init, net } from 'mosi/cs';

// Inject Counter GUI into topright of page
const counter = document.createElement('div');
counter.setAttribute('style', 'z-index: 99999; position: fixed; top: 0; right: 0;');
counter.innerHTML = '<button id="increment">Increment</button><input id="count" disabled/>';
document.body.appendChild(counter);

init({
  subscriptions: ['count']
  onConnect: [{ action: 'COUNT' }]
  actions: {
    NEW_COUNT: (count) => {
      document.getElementById('count').value = count;
    }
  }
});

// Add Click listener to increment count
document.getElementById('increment').addEventListener('click', () => {
  net('bp').msg('INCREMENT');
});
```


text:
<?php

/**
 * Interface for RDBMS platform specific behaviour.
 *
 * @author     Hans Lellelid <hans@xmpl.org> (Propel)
 * @author     Martin Poeschl <mpoeschl@marmot.at> (Torque)
 * @version    $Revision: 536 $
 * @package    propel.engine.platform
 */
interface Platform {

	/** constant for native id method */
	const IDENTITY = "identity";

	/** constant for native id method */
	const SEQUENCE = "sequence";

	/**
	 * Returns the short name of the database type that this platform represents.
	 * For example MysqlPlatform->getDatabaseType() returns 'mysql'.
	 * @return     string
	 */
	public function getDatabaseType();

	/**
	 * Returns the native IdMethod (sequence|identity)
	 *
	 * @return     string The native IdMethod (Platform:IDENTITY, Platform::SEQUENCE).
	 */
	public function getNativeIdMethod();

	/**
	 * Returns the max column length supported by the db.
	 *
	 * @return     int The max column length
	 */
	public function getMaxColumnNameLength();

	/**
	 * Returns the db specific domain for a jdbcType.
	 *
	 * @param      string $creoleType the creole type name.
	 * @return     Domain The db specific domain.
	 */
	public function getDomainForType($creoleType);

	/**
	 * @return     string The RDBMS-specific SQL fragment for NULL
	 * or NOT NULL.
	 */
	public function getNullString($notNull);

	/**
	 * @return     The RDBMS-specific SQL fragment for autoincrement.
	 */
	public function getAutoIncrement();

	/**
	 * Returns if the RDBMS-specific SQL type has a size attribute.
	 *
	 * @param      string $sqlType the SQL type
	 * @return     boolean True if the type has a size attribute
	 */
	public function hasSize($sqlType);

	/**
	 * Returns if the RDBMS-specific SQL type has a scale attribute.
	 *
	 * @param      string $sqlType the SQL type
	 * @return     boolean True if the type has a scale attribute
	 */
	public function hasScale($sqlType);

	/**
	 * Escape the string for RDBMS.
	 * @param      string $text
	 * @return     string
	 */
	public function escapeText($text);

	/**
	 * Quotes identifiers used in database SQL.
	 * @param      string $text
	 * @return     string Quoted identifier.
	 */
	public function quoteIdentifier($text);

	/**
	 * Whether RDBMS supports native ON DELETE triggers (e.g. ON DELETE CASCADE).
	 * @return     boolean
	 */
	public function supportsNativeDeleteTrigger();

	/**
	 * Returns the boolean value for the RDBMS.
	 *
	 * This value should match the boolean value that is set
	 * when using Creole's PreparedStatement::setBoolean().
	 *
	 * This function is used to set default column values when building
	 * SQL.
	 *
	 * @param      mixed $tf A boolean or string representation of boolean ('y', 'true').
	 * @return     mixed
	 */
	public function getBooleanString($tf);

}


text:
#include <string>

#include "ffm_util.h"
#include "ignition_path.h"

/*!\brief Categorises a fire as spreading or not.

  \return true if and only if the rate of spread is at least
  ffm_settings::minRateForStratumSpread for at least ffm_settings::minTimeStepsForStratumSpread
  time steps, otherwise returns false.
*/
bool IgnitionPath::spreads() const {
  int count = 0;
  for (int i = 0; i < numSegments(); ++i){
    if (ros(i) > ffm_settings::minRateForStratumSpread)
      ++count;
    if (count >= ffm_settings::minTimeStepsForStratumSpread) return true;
  }
  return false;
}

/*!\brief Mean flame length from all segments.
  \return The mean flame length from all segments of the IgnitionPath.
  If ignoreZeros == true the only non-zero flame lengths will be used to
  compute the mean, otherwise all flame lengths will be used
*/
double IgnitionPath::meanFlameLength(const bool& ignoreZeros) const {
  if (!hasSegments()) return 0.0;
  std::vector<double> vals;
  vals.resize(numSegments());
  transform(ignitedSegments_.begin(), ignitedSegments_.end(), vals.begin(),
            [this](const Seg& s){return species().flameLength(s.length());});
  return ffm_util::mean(vals, ignoreZeros);
}

/*!\brief Standard deviation of flame lengths from all segments.
  \return The standard deviation of the flame lengths from all segments of the IgnitionPath.
  If ignoreZeros == true the only non-zero flame lengths will be used to
  compute the standard deviation, otherwise all flame lengths will be used
*/
double IgnitionPath::stdDevFlameLength(const bool& ignoreZeros) const {
  if (numSegments() < 2) return 0.0;
  std::vector<double> vals;
  vals.resize(numSegments());
  transform(ignitedSegments_.begin(), ignitedSegments_.end(), vals.begin(),
            [this](const Seg& s){return species().flameLength(s.length());});
  return ffm_util::stdDev(vals, ignoreZeros);
}

/*!\brief The FlameSeries associated with the IgnitionPath
  \param windSpeed The relevant wind speed used for computation of the flame angles
  \param slope
  \return The FlameSeries generated by the IgnitionPath.
*/
FlameSeries IgnitionPath::flameSeries(const double& windSpeed,
                                      const double& slope) const {
  FlameSeries retValue(level_);
  if (hasSegments()) {
    retValue.flames().reserve(numSegments());
    for (int i = 0; i < numSegments(); ++i) retValue.addFlame(flame(i, windSpeed, slope));
  }
  return retValue;
}

/*!\brief Extract a rate of spread
  \param idx
  \return The rate of spread computed at the idx-th segment,
  counting from idx = 0.
*/
double IgnitionPath::ros(const int& idx) const {
  if (idx >= numSegments()) return 0;
  if (idx == 0) {
    Seg s = ignitedSegments_.at(0);
    return (s.end().x() - s.start().x())/ffm_settings::computationTimeInterval;
  } else
    return (ignitedSegments_.at(idx).end().x() - ignitedSegments_.at(idx-1).end().x())/
      ffm_settings::computationTimeInterval;
}

/*!\brief Basic rate of spread calculation
  \return The average rate of spread of all segments in the IgnitionPath
  whose rate of spread exceeds ffm_settings::minRateForStratumSpread.
*/
double IgnitionPath::basicROS() const {
  if (!hasSegments()) return 0;
  double sum = 0, x = ignitedSegments_.front().start().x();
  int count = 0;
  for (const Seg& seg : ignitedSegments_) {
    double tmp = (seg.end().x() - x)/ffm_settings::computationTimeInterval;
    if (tmp > ffm_settings::minRateForStratumSpread){
      sum += tmp;
      ++count;
    }
    x = seg.end().x();
  }
  return count == 0 ? 0 : sum / count;
}

/*!\brief Non-independent rate of spread
  \return The quotient of the total horizontal distance travelled and
  the sum of the time to ignition and the time period covered by the IgnitionPath.
*/
double IgnitionPath::nonIndependentROS() const {
  if (!hasSegments()) return 0;
  // return (ignitedSegments_.back().end().x() - ignitedSegments_.front().start().x())/
  //   (ffm_settings::computationTimeInterval*(numSegments() + startTimeStep_));
  return (maxX() - ignitedSegments_.front().start().x())/
    (ffm_settings::computationTimeInterval*(numSegments() + startTimeStep_));
}

/*!\brief Time of spread
  \return The time in seconds for which spread by the
  IgnitionPath exceeded ffm_settings::minRateForStratumSpread.
*/
 double IgnitionPath::timeOfSpread() const {
  if (!hasSegments()) return 0;
  int count = 0;
  for (int i = 0; i <= numSegments() - 1; ++i)
    count += ros(i) >= ffm_settings::minRateForStratumSpread ? 1 : 0;
  return count*ffm_settings::computationTimeInterval;
}

//printing

/*!\brief Printing
  \return A formatted string describing the ignition path.
*/
std::string IgnitionPath::printToString() const{
  std::string str;
  char s[100];

  str =  "Path type:                " + ignitionPathTypeStringMap.at(type_) + "\n";
  str += "Level:                    " + levelStringMap.at(level_) + "\n";
  str += "Species:                  " + species_.name() + "\n";
  sprintf(s, "Flame duration (sec):     %.2f\n", species_.flameDuration());
  str += std::string(s);

  if (hasSegments()) {
    sprintf(s,"Ignition start time step: %d", startTimeStep_);
    str += std::string(s);
  }
  else {
    str += "Ignition start time step: NA";
  }

  bool hasPreHeatingData = false;
  bool hasIncidentData = false;
  for (int i = 0; i < preIgnitionData_.size(); i++) {
    PreIgnitionData pid = preIgnitionData_.at(i);
    switch (pid.type()) {
      case PreIgnitionData::Type::PREHEATING: hasPreHeatingData = true; break;
      case PreIgnitionData::Type::INCIDENT: hasIncidentData = true; break;
    }
  }

  if (hasPreHeatingData) {
    str += "\n\nPreHeating\n";
    str += "Length\tDepth\tDist\tTemp\tDrying\tDuration\n";
    for (int i = 0; i < preIgnitionData_.size(); i++) {
      PreIgnitionData pid = preIgnitionData_.at(i);
      if (pid.type() == PreIgnitionData::Type::PREHEATING) {
        sprintf(s, "%.2f\t%.2f\t%.2f\t%.2f\t%.4f\t%.2f\n",
	        pid.flameLength(),
		pid.depthIgnited(),
		pid.distanceToFlame(),
		pid.temperature(),
		pid.dryingFactor(),
		pid.duration());
        str += std::string(s);
      }
    }
  }

  if (hasIncidentData) {
    str += "\n\nIncident\n";
    str += "Length\tDepth\tDist\tTemp\tDrying\tIDT\n";
    for (int i = 0; i < preIgnitionData_.size(); i++) {
      PreIgnitionData pid = preIgnitionData_.at(i);
      if (pid.type() != PreIgnitionData::Type::PREHEATING) {

        sprintf(s, "%.2f\t%.2f\t%.2f\t%.2f\t%.4f\t%.2f\n",
	        pid.flameLength(),
		pid.depthIgnited(),
		pid.distanceToFlame(),
		pid.temperature(),
		pid.dryingFactor(),
		pid.idt());
        str += std::string(s);
      }
    }
  }

  if (hasSegments()){
    str += "\n\nIgnited segments:\n";
    str += "Time\tStartX\tStartY\tEndX\tEndY\tSegLen\tFlameLen\n";

    for (int i = 0; i < numSegments(); i++) {
      Seg seg = ignitedSegments_.at(i);
      sprintf(s, "%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n",
          i+1, seg.start().x(), seg.start().y(), seg.end().x(), seg.end().y(), seg.length(), species_.flameLength(seg.length()) );
      str += std::string(s);
    }
  }

  return str;
}


text:
import { objectKeys, AnyFunction } from "../../utils"

const group = {
  hover: (selector: string) => `${selector}:hover &, ${selector}[data-hover] &`,
  focus: (selector: string) => `${selector}:focus &, ${selector}[data-focus] &`,
  active: (selector: string) => `${selector}:active &, ${selector}[data-active] &`,
  disabled: (selector: string) => `${selector}:disabled &, ${selector}[data-disabled] &`,
  invalid: (selector: string) => `${selector}:invalid &, ${selector}[data-invalid] &`,
  checked: (selector: string) => `${selector}:checked &, ${selector}[data-checked] &`,
  indeterminate: (selector: string) =>
    `${selector}:indeterminate &, ${selector}[aria-checked=mixed] &, ${selector}[data-indeterminate] &`,
  readOnly: (selector: string) => `${selector}:read-only &, ${selector}[readonly] &, ${selector}[data-read-only] &`,
  expanded: (selector: string) =>
    `${selector}:read-only &, ${selector}[aria-expanded=true] &, ${selector}[data-expanded] &`,
}

const toGroup = (fn: AnyFunction) => merge(fn, "[role=group]", "[data-group]", ".group")

const merge = (fn: AnyFunction, ...selectors: string[]) => selectors.map(fn).join(", ")

export const pseudoSelectors = {
  /**
   * Styles for CSS selector `&:hover`
   */
  _hover: "&:hover, &[data-hover]",
  /**
   * Styles for CSS Selector `&:active`
   */
  _active: "&:active, &[data-active]",
  /**
   * Styles for CSS selector `&:focus`
   *
   */
  _focus: "&:focus, &[data-focus]",
  /**
   * Styles for the highlighted state.
   */
  _highlighted: "&[data-highlighted]",
  /**
   * Styles to apply when a child of this element has received focus
   * - CSS Selector `&:focus-within`
   */
  _focusWithin: "&:focus-within",
  _focusVisible: "&:focus-visible",
  /**
   * Styles to apply when this element is disabled. The passed styles are applied to these CSS selectors:
   * - `&[aria-disabled=true]`
   * - `&:disabled`
   * - `&[data-disabled]`
   */
  _disabled: "&[disabled], &[aria-disabled=true], &[data-disabled]",
  /**
   * Styles for CSS Selector `&:readonly`
   */
  _readOnly: "&[aria-readonly=true], &[readonly], &[data-readonly]",
  /**
   * Styles for CSS selector `&::before`
   *
   * NOTE:When using this, ensure the `content` is wrapped in a backtick.
   * @example
   * ```jsx
   * <Box _before={{content:`""` }}/>
   * ```
   */
  _before: "&::before",
  /**
   * Styles for CSS selector `&::after`
   *
   * NOTE:When using this, ensure the `content` is wrapped in a backtick.
   * @example
   * ```jsx
   * <Box _after={{content:`""` }}/>
   * ```
   */
  _after: "&::after",
  _empty: "&:empty",
  /**
   * Styles to apply when the ARIA attribute `aria-expanded` is `true`
   * - CSS selector `&[aria-expanded=true]`
   */
  _expanded: "&[aria-expanded=true], &[data-expanded]",
  /**
   * Styles to apply when the ARIA attribute `aria-checked` is `true`
   * - CSS selector `&[aria-checked=true]`
   */
  _checked: "&[aria-checked=true], &[data-checked]",
  /**
   * Styles to apply when the ARIA attribute `aria-grabbed` is `true`
   * - CSS selector `&[aria-grabbed=true]`
   */
  _grabbed: "&[aria-grabbed=true], &[data-grabbed]",
  /**
   * Styles for CSS Selector `&[aria-pressed=true]`
   * Typically used to style the current "pressed" state of toggle buttons
   */
  _pressed: "&[aria-pressed=true], &[data-pressed]",
  /**
   * Styles to apply when the ARIA attribute `aria-invalid` is `true`
   * - CSS selector `&[aria-invalid=true]`
   */
  _invalid: "&[aria-invalid=true], &[data-invalid]",
  /**
   * Styles for the valid state
   * - CSS selector `&[data-valid], &[data-state=valid]`
   */
  _valid: "&[data-valid], &[data-state=valid]",
  /**
   * Styles for CSS Selector `&[aria-busy=true]` or `&[data-loading=true]`.
   * Useful for styling loading states
   */
  _loading: "&[data-loading], &[aria-busy=true]",
  /**
   * Styles to apply when the ARIA attribute `aria-selected` is `true`
   *
   * - CSS selector `&[aria-selected=true]`
   */
  _selected: "&[aria-selected=true], &[data-selected]",
  /**
   * Styles for CSS Selector `[hidden=true]`
   */
  _hidden: "&[hidden], &[data-hidden]",
  /**
   * Styles for CSS Selector `&:-webkit-autofill`
   */
  _autofill: "&:-webkit-autofill",
  /**
   * Styles for CSS Selector `&:nth-child(even)`
   */
  _even: "&:nth-of-type(even)",
  /**
   * Styles for CSS Selector `&:nth-child(odd)`
   */
  _odd: "&:nth-of-type(odd)",
  /**
   * Styles for CSS Selector `&:first-of-type`
   */
  _first: "&:first-of-type",
  /**
   * Styles for CSS Selector `&:last-of-type`
   */
  _last: "&:last-of-type",
  /**
   * Styles for CSS Selector `&:not(:first-of-type)`
   */
  _notFirst: "&:not(:first-of-type)",
  /**
   * Styles for CSS Selector `&:not(:last-of-type)`
   */
  _notLast: "&:not(:last-of-type)",
  /**
   * Styles for CSS Selector `&:visited`
   */
  _visited: "&:visited",
  /**
   * Used to style the active link in a navigation
   * Styles for CSS Selector `&[aria-current=page]`
   */
  _activeLink: "&[aria-current=page]",
  /**
   * Styles to apply when the ARIA attribute `aria-checked` is `mixed`
   * - CSS selector `&[aria-checked=mixed]`
   */
  _indeterminate: "&:indeterminate, &[aria-checked=mixed], &[data-indeterminate]",
  /**
   * Styles to apply when parent is hovered
   */
  _groupHover: toGroup(group.hover),
  /**
   * Styles to apply when parent is focused
   */
  _groupFocus: toGroup(group.focus),
  /**
   * Styles to apply when parent is active
   */
  _groupActive: toGroup(group.active),
  /**
   * Styles to apply when parent is disabled
   */
  _groupDisabled: toGroup(group.disabled),
  /**
   * Styles to apply when parent is invalid
   */
  _groupInvalid: toGroup(group.invalid),
  /**
   * Styles to apply when parent is checked
   */
  _groupChecked: toGroup(group.checked),
  /**
   * Styles for CSS Selector `&::placeholder`.
   */
  _placeholder: "&::placeholder",
  /**
   * Styles for CSS Selector `&:fullscreen`.
   */
  _fullScreen: "&:fullscreen",
  /**
   * Styles for CSS Selector `&::selection`
   */
  _selection: "&::selection",
  /**
   * Styles for CSS Selector `[dir=rtl] &`
   * It is applied when any parent element has `dir="rtl"`
   */
  _rtl: "[dir=rtl] &",
  /**
   * Styles for CSS Selector `@media (prefers-color-scheme: dark)`
   * used when the user has requested the system
   * use a light or dark color theme.
   */
  _mediaDark: "@media (prefers-color-scheme: dark)",
  /**
   * Styles for when `.dark` is applied to any parent of
   * this component or element.
   */
  _dark: ".dark &, [data-theme=dark] &",
}

export type Pseudos = typeof pseudoSelectors

export const pseudoPropNames = objectKeys(pseudoSelectors)


text:
/**
 * Client tests
 */
import React from "react";
import { shallow, render } from "enzyme";
import VictoryLegend from "src/victory-legend/victory-legend";

const initialData = [{
  name: "Series 1",
  symbol: {
    type: "circle"
  }
}, {
  name: "Series 2",
  labels: {
    fill: "red"
  },
  symbol: {
    type: "triangleUp",
    fill: "blue"
  }
}];

describe("components/victory-legend", () => {
  let wrapper = shallow(<VictoryLegend data={initialData} />);

  it("has expected content with shallow render", () => {
    const output = wrapper.find("VictoryLabel");
    expect(output.length).to.equal(2);
  });

  it("has expected horizontal symbol position", () => {
    const wrappedLegend = shallow(<VictoryLegend data={initialData} orientation="horizontal" />);
    const output = wrappedLegend.find("Point");

    expect(output.at(0).prop("x")).to.equal(14);
    expect(output.at(1).prop("x")).to.equal(100.28016194331983);
    expect(output.at(0).prop("y")).to.equal(14);
    expect(output.at(1).prop("y")).to.equal(14);
  });

  it("has expected vertical symbol position", () => {
    const wrappedLegend = shallow(<VictoryLegend data={initialData} orientation="vertical" />);
    const output = wrappedLegend.find("Point");

    expect(output.at(0).prop("x")).to.equal(14);
    expect(output.at(1).prop("x")).to.equal(14);
    expect(output.at(0).prop("y")).to.equal(14);
    expect(output.at(1).prop("y")).to.equal(44.905);
  });

  it("has expected horizontal legend labels position", () => {
    const wrappedLegend = render(<VictoryLegend data={initialData} orientation="horizontal" />);
    const output = wrappedLegend.find("text");

    expect(output.eq(0).prop("x")).to.equal("30.8");
    expect(output.eq(1).prop("x")).to.equal("117.08016194331982");
    expect(output.eq(0).prop("y")).to.equal("14");
    expect(output.eq(1).prop("y")).to.equal("14");
  });

  it("has expected vertical legend labels position", () => {
    const wrappedLegend = render(<VictoryLegend data={initialData} orientation="vertical" />);
    const output = wrappedLegend.find("text");

    expect(output.eq(0).prop("x")).to.equal("30.8");
    expect(output.eq(1).prop("x")).to.equal("30.8");
    expect(output.eq(0).prop("y")).to.equal("14");
    expect(output.eq(1).prop("y")).to.equal("44.905");
  });

  describe("symbols", () => {
    const legendData = [{
      name: "Series 1",
      labels: {
        fontSize: 10
      },
      symbol: {
        type: "circle",
        fill: "red"
      }
    }, {
      name: "Long Series Name",
      labels: {
        fontSize: 12
      },
      symbol: {
        type: "triangleUp",
        fill: "blue"
      }
    }];

    wrapper = shallow(<VictoryLegend data={legendData} />);
    const output = wrapper.find("Point");

    it("has expected symbols length", () => {
      expect(output.length).to.equal(2);
    });

    it("has expected symbol colors", () => {
      expect(output.get(0).props.style.fill).to.equal("red");
      expect(output.get(1).props.style.fill).to.equal("blue");
    });

    it("has expected symbol type", () => {
      expect(output.get(0).props.symbol).to.equal("circle");
      expect(output.get(1).props.symbol).to.equal("triangleUp");
    });
  });

  describe("legend style prop", () => {
    const legendData = [{
      name: "Thing 1"
    }, {
      name: "Thing 2"
    }];

    const styleObject = {
      data: {
        type: "triangleUp",
        fill: "green"
      },
      labels: {
        fontSize: 16
      }
    };

    wrapper = shallow(<VictoryLegend data={legendData} style={styleObject} />);
    const outputPoints = wrapper.find("Point");
    const outputLabels = wrapper.find("VictoryLabel");

    it("has expected symbol type", () => {
      expect(outputPoints.at(0).prop("symbol")).to.equal("triangleUp");
      expect(outputPoints.at(1).prop("symbol")).to.equal("triangleUp");
    });

    it("has expected symbol colors", () => {
      expect(outputPoints.get(0).props.style.fill).to.equal("green");
      expect(outputPoints.get(1).props.style.fill).to.equal("green");
    });

    it("has expected label colors", () => {
      expect(outputLabels.get(0).props.style.fill).to.equal("#252525");
      expect(outputLabels.get(1).props.style.fill).to.equal("#252525");
    });
  });

  describe("itemsPerRow", () => {
    const legendData = [{
      name: "Thing 1"
    }, {
      name: "Thing 2"
    }, {
      name: "Thing 3"
    }, {
      name: "Thing 4"
    }, {
      name: "Thing 5"
    }, {
      name: "Thing 6"
    }];

    it("displays items in columns", () => {
      wrapper = shallow(<VictoryLegend data={legendData} itemsPerRow={3} />);
      const outputLabels = wrapper.find("VictoryLabel");
      const outputPoints = wrapper.find("Point");

      // items line up between columns
      expect(outputPoints.get(0).props.y).to.equal(outputPoints.get(3).props.y);
      expect(outputLabels.get(0).props.y).to.equal(outputLabels.get(3).props.y);
      expect(outputPoints.get(1).props.y).to.equal(outputPoints.get(4).props.y);
      expect(outputLabels.get(1).props.y).to.equal(outputLabels.get(4).props.y);
      expect(outputPoints.get(2).props.y).to.equal(outputPoints.get(5).props.y);
      expect(outputLabels.get(2).props.y).to.equal(outputLabels.get(2).props.y);

      // columns are the same distance apart
      expect(outputPoints.get(0).props.x - outputPoints.get(3).props.x)
        .to.equal(outputPoints.get(1).props.x - outputPoints.get(4).props.x).and
        .to.equal(outputPoints.get(2).props.x - outputPoints.get(5).props.x);
    });

    it("displays items in rows", () => {
      wrapper = shallow(
        <VictoryLegend
          data={legendData}
          itemsPerRow={3}
          orientation="horizontal"
        />
      );
      const outputLabels = wrapper.find("VictoryLabel");
      const outputPoints = wrapper.find("Point");

      // items line up between rows
      expect(outputPoints.get(0).props.x).to.equal(outputPoints.get(3).props.x);
      expect(outputLabels.get(0).props.x).to.equal(outputLabels.get(3).props.x);
      expect(outputPoints.get(1).props.x).to.equal(outputPoints.get(4).props.x);
      expect(outputLabels.get(1).props.x).to.equal(outputLabels.get(4).props.x);
      expect(outputPoints.get(2).props.x).to.equal(outputPoints.get(5).props.x);
      expect(outputLabels.get(2).props.x).to.equal(outputLabels.get(2).props.x);

      // rows are the same distance apart
      expect(outputPoints.get(0).props.y - outputPoints.get(3).props.y)
        .to.equal(outputPoints.get(1).props.y - outputPoints.get(4).props.y).and
        .to.equal(outputPoints.get(2).props.y - outputPoints.get(5).props.y);
    });
  });
});


text:
// ***********************************************************************
// Copyright (c) 2017 Dominik Lachance
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using AutoMapper;
using YellowJacket.Dashboard.Entities;
using YellowJacket.Models;

namespace YellowJacket.Dashboard.Mapping
{
    /// <inheritdoc />
    /// <summary>
    /// Initialize the different mapping profiles.
    /// </summary>
    /// <seealso cref="Profile" />
    public class MappingProfile : Profile
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="MappingProfile"/> class.
        /// </summary>
        public MappingProfile()
        {
            CreateMap<AgentEntity, AgentModel>();
            CreateMap<AgentModel, AgentEntity>();

            CreateMap<JobEntity, JobModel>();
            CreateMap<JobModel, JobEntity>();

            CreateMap<JobInstanceEntity, JobInstanceModel>();
            CreateMap<JobInstanceModel, JobInstanceEntity>();

            CreateMap<ConfigurationEntity, ConfigurationModel>();
            CreateMap<ConfigurationModel, ConfigurationEntity>();

            CreateMap<PackageEntity, PackageModel>();
            CreateMap<PackageModel, PackageEntity>();

            CreateMap<PackageEntity, PackageModel>();
            CreateMap<PackageModel, PackageEntity>();

            CreateMap<FeatureEntity, FeatureModel>();
            CreateMap<FeatureModel, FeatureEntity>();
        }

        #endregion
    }
}


text:
require 'test_helper'

class TownsControllerTest < ActionController::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.leftso</groupId>
	<artifactId>demo-security-oauth2-authorizationServer</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo-security-oauth2-authorizationServer</name>
	<description>Demo project for Spring Boot security</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.5.RELEASE</version><!-- 注意不能使用1.5.X -->
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
       <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.security.oauth</groupId>
         <artifactId>spring-security-oauth2</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-jwt</artifactId>
      </dependency>
      <dependency>
         <groupId>com.fasterxml.jackson.core</groupId>
         <artifactId>jackson-databind</artifactId>
         <scope>compile</scope>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>org.bitbucket.b_c</groupId>
         <artifactId>jose4j</artifactId>
         <version>0.5.1</version>
      </dependency>

      <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>

      <dependency>
      	<groupId>org.springframework.boot</groupId>
      	<artifactId>spring-boot-configuration-processor</artifactId>
      	<optional>true</optional>
      </dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
from django.db.models.fields.related import ForeignKey
from django.db.models import fields
from comboboxintegration import restfulcls_to_extjscombobox_xtype
from datepickerintegration import restfulcls_to_datepicker_xtype

#def find_foreign_field(model, path):
    #fieldname = path.pop(0)
    #field = model._meta.get_field_by_name(fieldname)[0]
    #if isinstance(field, ForeignKey):
        #model = field.related.parent_model
        #return find_foreign_field(model, path)
    #else:
        #return field

def djangofield_to_extjs_xtype(djangofield, foreignkey_restfulcls):
    if isinstance(djangofield, ForeignKey):
        if foreignkey_restfulcls == None:
            raise ValueError('Foreign key: {fieldname} has no foreignkey_restfulcls. '
                             'This is usually defined in Meta.foreignkey_fields in '
                             'the ModelRestfulView.'.format(fieldname=djangofield.name))
        return restfulcls_to_extjscombobox_xtype(foreignkey_restfulcls)
    elif isinstance(djangofield, fields.DateTimeField):
        return restfulcls_to_datepicker_xtype()
    elif isinstance(djangofield, fields.BooleanField):
        return "xtype: 'checkbox'"
    else:
        return "xtype: 'textfield'"

def djangofield_to_extjsformfield(model, fieldname, foreignkey_restfulcls):
    field = model._meta.get_field_by_name(fieldname)[0] #!!! INTERNAL DJANGO
    try:
        xtype = djangofield_to_extjs_xtype(field, foreignkey_restfulcls)
    except ValueError, e:
        raise ValueError('model: {module}.{modelname}: {error}'.format(module=model.__module__,
                                                                       modelname=model.__name__,
                                                                       error=e))
    extfield = '{{ name: "{fieldname}", fieldLabel: "{field.verbose_name}", '\
            '{xtype} }}'.format(fieldname=fieldname, field=field,
                                    xtype=xtype)
    return extfield


text:
import { globalBeforeEach } from '../../__jest__/before-each';
import { database } from '../../common/database';
import { ApiSpec } from '../api-spec';
import { CookieJar } from '../cookie-jar';
import { Environment } from '../environment';
import * as models from '../index';
import { WorkspaceScopeKeys } from '../workspace';
import { WorkspaceMeta } from '../workspace-meta';

describe('migrate()', () => {
  beforeEach(globalBeforeEach);

  it('migrates client certificates properly', async () => {
    const workspace = await models.workspace.create({
      name: 'My Workspace',
      certificates: [
        {
          key: 'key',
          passphrase: 'mypass',
        },
        {
          disabled: true,
          cert: 'cert',
        },
      ],
    });
    const migratedWorkspace = await models.workspace.migrate(workspace);
    const certs = await models.clientCertificate.findByParentId(workspace._id);

    // Delete modified and created so we can assert them
    for (const cert of certs) {
      expect(typeof cert.modified).toBe('number');
      expect(typeof cert.created).toBe('number');
      // @ts-expect-error delete in order to test
      delete cert.modified;
      // @ts-expect-error delete in order to test
      delete cert.created;
    }

    expect(certs.length).toBe(2);
    expect(certs.sort((c1, c2) => (c1._id > c2._id ? -1 : 1))).toEqual([
      {
        _id: 'crt_e3e96e5fdd6842298b66dee1f0940f3d',
        cert: 'cert',
        disabled: false,
        isPrivate: false,
        host: '',
        key: null,
        parentId: 'wrk_cc1dd2ca4275747aa88199e8efd42403',
        passphrase: null,
        pfx: null,
        type: 'ClientCertificate',
      },
      {
        _id: 'crt_dd2ccc1a2745477a881a9e8ef9d42403',
        cert: null,
        disabled: false,
        isPrivate: false,
        host: '',
        key: 'key',
        parentId: 'wrk_cc1dd2ca4275747aa88199e8efd42403',
        passphrase: 'mypass',
        pfx: null,
        type: 'ClientCertificate',
      },
    ]);
    expect(migratedWorkspace.certificates).toBeUndefined();
    // Make sure we don't create new certs if we migrate again
    await models.workspace.migrate(migratedWorkspace);
    const certsAgain = await models.clientCertificate.findByParentId(workspace._id);
    expect(certsAgain.length).toBe(2);
  });

  it('creates api spec for workspace id', async () => {
    const workspace = await models.workspace.create({
      name: 'My Workspace',
    });
    await models.apiSpec.removeWhere(workspace._id);
    expect(await models.apiSpec.getByParentId(workspace._id)).toBe(null);
    await models.workspace.migrate(workspace);
    const spec = await models.apiSpec.getByParentId(workspace._id);
    expect(spec).not.toBe(null);
    expect(spec?.fileName).toBe(workspace.name);
  });

  it('translates the scope correctly', async () => {
    const specW = await models.workspace.create({
      // @ts-expect-error intentionally incorrect - old scope type
      scope: 'spec',
    });
    const debugW = await models.workspace.create({
      // @ts-expect-error intentionally incorrect - old scope type
      scope: 'debug',
    });
    const nullW = await models.workspace.create({
      // @ts-expect-error intentionally incorrect - old scope type
      scope: null,
    });
    const somethingElseW = await models.workspace.create({
      // @ts-expect-error intentionally incorrect - old scope type
      scope: 'something',
    });
    const designW = await models.workspace.create({
      scope: WorkspaceScopeKeys.design,
    });
    const collectionW = await models.workspace.create({
      scope: WorkspaceScopeKeys.collection,
    });
    await models.workspace.migrate(specW);
    await models.workspace.migrate(debugW);
    await models.workspace.migrate(nullW);
    await models.workspace.migrate(somethingElseW);
    expect(specW.scope).toBe(WorkspaceScopeKeys.design);
    expect(debugW.scope).toBe(WorkspaceScopeKeys.collection);
    expect(nullW.scope).toBe(WorkspaceScopeKeys.collection);
    expect(somethingElseW.scope).toBe(WorkspaceScopeKeys.collection);
    expect(designW.scope).toBe(WorkspaceScopeKeys.design);
    expect(collectionW.scope).toBe(WorkspaceScopeKeys.collection);
  });
});

describe('ensureChildren()', () => {
  beforeEach(globalBeforeEach);

  it('creates children for workspace', async () => {
    const workspace = await models.workspace.create();
    await models.workspace.ensureChildren(workspace);

    const descendents = await database.withDescendants(workspace);

    expect(descendents).toHaveLength(5);
    expect(descendents).toStrictEqual(expect.arrayContaining([
      workspace,
      // ApiSpec is created as part of migration
      expect.objectContaining<Partial<ApiSpec>>({ parentId: workspace._id, type: models.apiSpec.type }),
      expect.objectContaining<Partial<Environment>>({ parentId: workspace._id, type: models.environment.type }),
      expect.objectContaining<Partial<CookieJar>>({ parentId: workspace._id, type: models.cookieJar.type }),
      expect.objectContaining<Partial<WorkspaceMeta>>({ parentId: workspace._id, type: models.workspaceMeta.type }),
    ]));
  });
});


text:
package com.taobao.tddl.optimizer.utils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import com.google.common.collect.Lists;
import com.taobao.tddl.optimizer.exceptions.FunctionException;

/**
 * @author jianghang 2013-11-8 下午7:55:16
 * @since 5.1.0
 */
public class PackageUtils {

    public static List<Class> findClassesInPackage(String packageName, ClassFilter filter) {
        try {
            List<String> classes = Lists.newArrayList();
            String packageDirName = packageName.replace('.', '/');
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

            Enumeration<URL> dirEnumeration = classLoader.getResources(packageDirName);
            List<URL> dirs = Lists.newArrayList();
            while (dirEnumeration.hasMoreElements()) {
                URL dir = dirEnumeration.nextElement();
                dirs.add(dir);
            }

            Iterator<URL> dirIterator = dirs.iterator();
            while (dirIterator.hasNext()) {
                URL url = dirIterator.next();
                String protocol = url.getProtocol();
                if ("file".equals(protocol)) {
                    findClassesInDirPackage(packageName, URLDecoder.decode(url.getFile(), "UTF-8"), classes);
                } else if ("jar".equals(protocol)) {
                    JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
                    Enumeration<JarEntry> entries = jar.entries();
                    while (entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
                        String name = entry.getName();
                        String pName = packageName;
                        if (name.charAt(0) == '/') {
                            name = name.substring(1);
                        }
                        if (name.startsWith(packageDirName)) {
                            int idx = name.lastIndexOf('/');
                            if (idx != -1) {
                                pName = name.substring(0, idx).replace('/', '.');
                            }

                            if (idx != -1) {
                                // it's not inside a deeper dir
                                if (name.endsWith(".class") && !entry.isDirectory()) {
                                    String className = name.substring(pName.length() + 1, name.length() - 6);
                                    classes.add(makeFullClassName(pName, className));
                                }
                            }
                        }
                    }
                }
            }

            List<Class> result = Lists.newArrayList();
            for (String clazz : classes) {
                if (filter == null || filter.preFilter(clazz)) {
                    Class<?> cls = null;
                    try {
                        cls = Class.forName(clazz);
                    } catch (Throwable e) {
                        // ignore
                    }

                    if (cls != null && (filter == null || filter.filter(cls))) {
                        result.add(cls);
                    }
                }
            }

            return result;
        } catch (IOException e) {
            throw new FunctionException("findClassesInPackage : " + packageName + " is failed. ", e);
        }

    }

    private static void findClassesInDirPackage(String packageName, String packagePath, List<String> classes) {
        File dir = new File(packagePath);
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }

        File[] dirfiles = dir.listFiles(new FileFilter() {

            @Override
            public boolean accept(File file) {
                return file.isDirectory() || (file.getName().endsWith(".class"));
            }
        });

        for (File file : dirfiles) {
            if (file.isDirectory()) {
                findClassesInDirPackage(makeFullClassName(packageName, file.getName()), file.getAbsolutePath(), classes);
            } else {
                String className = file.getName().substring(0, file.getName().lastIndexOf("."));
                classes.add(makeFullClassName(packageName, className));
            }
        }
    }

    private static String makeFullClassName(String pkg, String cls) {
        return pkg.length() > 0 ? pkg + "." + cls : cls;
    }

    public static interface ClassFilter {

        public boolean preFilter(String className);

        public boolean filter(Class clazz);
    }
}


text:
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;

namespace CafeBazarIab
{

	public class CafeBazarIabWindow : EditorWindow {

		public Texture2D CafeBazarLogo;
		public Texture2D Unity3dir;

		// Add menu item named "CafeBazarIabPlugin" to the Window menu
		private List<GameObject> items = new List<GameObject>();

		private int index = 0;
		private Vector2 scrollPos;

		[MenuItem("Window/CafeBazaar")]
		public static void ShowWindow()
		{
			//Show existing window instance. If one doesn't exist, make one.
			EditorWindow.GetWindow(typeof(CafeBazarIabWindow));
		}

		private float itemsHeight = 40;

		void OnGUI(){
			var script = MonoScript.FromScriptableObject( this );
			string path = AssetDatabase.GetAssetPath( script );
			path = path.Replace("CafeBazarIabWindow.cs" , "");
			CafeBazarLogo =(Texture2D) AssetDatabase.LoadAssetAtPath(path + "logo.png" , typeof(Texture2D));
			Unity3dir =(Texture2D) AssetDatabase.LoadAssetAtPath(path + "unity3dir.png" , typeof(Texture2D));

			EditorGUILayout.BeginVertical();

			scrollPos = EditorGUILayout.BeginScrollView(scrollPos);

			GUILayout.BeginHorizontal();
			GUILayout.FlexibleSpace();
			GUILayout.Label( new GUIContent("", CafeBazarLogo, "") , GUILayout.Height(150) , GUILayout.Width(300));
			GUILayout.FlexibleSpace();
			GUILayout.EndHorizontal();

			GUILayout.BeginHorizontal();
			GUILayout.FlexibleSpace();
			GUILayout.Label( new GUIContent("", Unity3dir, "") , GUILayout.Height(100), GUILayout.Width(300));
			GUILayout.FlexibleSpace();
			GUILayout.EndHorizontal();

			GUILayout.BeginHorizontal();
			GUILayout.FlexibleSpace();
			if(GUILayout.Button( new GUIContent("Add Item", null, "") ,GUILayout.Width(100), GUILayout.Height(50)))
			{
				addItem();
			}

			GUILayout.FlexibleSpace();
			if(GUILayout.Button(new GUIContent("Refresh", null, "") ,GUILayout.Width(100), GUILayout.Height(50)))
			{
				refreshItems();
			}
			GUILayout.FlexibleSpace();
			GUILayout.EndHorizontal();

			GUILayout.Box(new GUIContent("Items", null, "") , GUILayout.MinHeight(30) , GUILayout.ExpandWidth(true));

			GUILayout.BeginHorizontal();

			GUILayout.Label("SKU");
			GUILayout.FlexibleSpace();
			GUILayout.Label("Item Type");
			GUILayout.FlexibleSpace();
			GUILayout.Label("");
			GUILayout.EndHorizontal();

			for(int i = 0 ; i < items.Count ; i++) {

				if (items[i] == null) {
					items.RemoveAt(i);
					continue;
				}
				ShopItem shopitem = items[i].GetComponent<ShopItem>();

				GUILayout.Box(new GUIContent("", null, "") , GUILayout.MinHeight(5) , GUILayout.ExpandWidth(true));

				GUILayout.BeginHorizontal();

				shopitem.SKU = EditorGUILayout.TextField(shopitem.SKU , GUILayout.Height(itemsHeight));

				shopitem.gameObject.name = shopitem.SKU;

				GUILayout.FlexibleSpace();

				shopitem._Type = (ShopItemType) EditorGUILayout.EnumPopup(shopitem._Type);

				GUILayout.FlexibleSpace();

				if (GUILayout.Button(new GUIContent("Delete", null, "") , GUILayout.Height(itemsHeight)))
				{
					removeItem(i);
				}

				GUILayout.FlexibleSpace();
				GUILayout.EndHorizontal();
			}

			EditorGUILayout.EndScrollView();

			EditorGUILayout.EndVertical();

		}

		void refreshItems ()
		{
			StoreHandler storeHandler = GameObject.FindObjectOfType<StoreHandler>();
			items.Clear();
			for (int i = 0; i < storeHandler.gameObject.transform.childCount; i++) {
				items.Add(storeHandler.gameObject.transform.GetChild(i).gameObject);
			}

		}

		public Rect addPadding(Rect rect , int padding , int minWidth , int maxWidth)
		{
			if (rect.width < minWidth) {
				rect.width = minWidth;
				rect.x = (Screen.width - rect.width)/2;
			}
			if (rect.width > maxWidth) {
				rect.width = maxWidth;
				rect.x = (Screen.width - rect.width)/2;
			}
			rect.xMin += padding;
			rect.width = rect.width - padding;

			return rect;
			//return new Rect(rect.xMin + padding , rect.yMax , rect.width - 2 * padding , rect.height);
		}

		void removeItem (int i)
		{
			string objectName = items[i].name;
			DestroyImmediate(GameObject.Find(objectName));
			refreshItems();
		}

		void addItem()
		{
			StoreHandler storeHandler = GameObject.FindObjectOfType<StoreHandler>();
			GameObject newShopItemObject = new GameObject();
			newShopItemObject.name = index.ToString();
			newShopItemObject.AddComponent<ShopItem>();
			newShopItemObject.GetComponent<ShopItem>().SKU = "NewItem";
			newShopItemObject.GetComponent<ShopItem>()._Type = ShopItemType.inapp;
			newShopItemObject.transform.parent = storeHandler.gameObject.transform;
			refreshItems();
			//Debug.Log (index + " , " + texts.Count + " , " + times.Count);
		}

	}

}


text:
class CMFCAcceleratorKey : public CObject
{
public:
	CMFCAcceleratorKey();
	CMFCAcceleratorKey(LPACCEL lpAccel);
	virtual ~CMFCAcceleratorKey();

// Operations:
public:
	void Format(CString& str) const;

protected:
	void AddVirtKeyStr(CString& str, UINT uiVirtKey, BOOL bLast = FALSE) const;

// Atttributes:
public:
	void SetAccelerator(LPACCEL lpAccel)
	{
		m_lpAccel = lpAccel;
	}

protected:
	LPACCEL m_lpAccel;
};

#ifdef _AFX_MINREBUILD
#pragma component(minrebuild, on)
#endif

#ifdef _AFX_PACKING
#pragma pack(pop)
#endif


text:
<bill session="110" type="h" number="5434" updated="2009-01-09T04:09:38-05:00">
	<status><introduced date="1202878800" datetime="2008-02-13"/></status>

	<introduced date="1202878800" datetime="2008-02-13"/>
	<titles>
		<title type="short" as="introduced">Protecting Americans from Violent Crime Act of 2008</title>
		<title type="official" as="introduced">To protect innocent Americans from violent crime in national parks.</title>
	</titles>
	<sponsor id="400175"/>
	<cosponsors>
		<cosponsor id="400279" joined="2008-03-11"/>
		<cosponsor id="412252" joined="2008-03-11"/>
		<cosponsor id="400209" joined="2008-03-11"/>
		<cosponsor id="400317" joined="2008-03-11"/>
		<cosponsor id="400176" joined="2008-03-11"/>
		<cosponsor id="400652" joined="2008-03-11"/>
		<cosponsor id="400206" joined="2008-03-11"/>
		<cosponsor id="400287" joined="2008-03-11"/>
		<cosponsor id="400440" joined="2008-03-11"/>
		<cosponsor id="400141" joined="2008-03-11"/>
		<cosponsor id="400088" joined="2008-03-11"/>
		<cosponsor id="412191" joined="2008-03-11"/>
		<cosponsor id="412255" joined="2008-03-11"/>
	</cosponsors>
	<actions>
		<action date="1202878800" datetime="2008-02-13"><text>Referred to the House Committee on Natural Resources.</text></action>
		<action date="1203397200" datetime="2008-02-19"><text>Referred to the Subcommittee on Fisheries, Wildlife, and Oceans.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	2/13/2008--Introduced.<br/>Protecting Americans from Violent Crime Act of 2008 - Bars, except as provided under current federal criminal law regarding the possession or the causing to be present of firearms and other dangerous weapons in federal facilities (other than federal court facilities), the promulgation or enforcement of any regulation that prohibits an individual from possessing, transporting, or carrying a firearm, including an assembled or functional firearm, in any unit of the National Park System or the National Wildlife Refuge System if: (1) the individual is not otherwise prohibited by law from possessing, transporting, or carrying the firearm; and (2) the possession, transportation, or carrying of the firearm is in compliance with the law governing possession, transportation, or carrying of firearms in parks of the state in which the unit is located.
	</summary>
</bill>


text:
layout: post
title: Alive
---

I miss having my own balcony where I can go out whenever I want, sit down with my wine, smoke and look at the stars. That is when I decide to do things, I need that for my mind. Through a long and twisted series of circumstances,
that moment became part of who I am. It has a bit of everything, and it is short, like a break from everything, to remind me who I am. I do what I must, I worry and think about the future. I save money and eat right. But sometimes
I need to feel alive. Is that so hard to understand?


text:
<md-icon role="img" class="material-icons" aria-label="apps">apps</md-icon>
Products

  <app-loader [loading]="loading" [failed]="failed"></app-loader>

<app-products-list
  [products]="products"
  [count]="count"
  (viewProduct)="viewProduct($event)"
  (editProduct)="editProduct($event)">
</app-products-list>
<app-pagination [offset]="offset" [limit]="limit" [range]="range" [size]="count" (pageChange)="onPageChange($event)"></app-pagination>


text:
package io.leocad.dumbledoreexample.activities;

import io.leocad.dumbledoreexample.R;
import io.leocad.dumbledoreexample.models.Sith;
import io.leocad.dumbledoreexample.models.Suit;
import io.leocad.dumbledroid.net.NoConnectionException;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

public class SithActivity extends BaseActivity {

	private Dialog mDialog;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sith);

		if (Build.VERSION.SDK_INT >= 11) {
			// Show the Up button in the action bar.
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}

		loadContent();
	}

	private void loadContent() {
		new AsyncTask<Void, Void, Sith>() {

			@Override
			protected void onPreExecute() {
				mDialog = ProgressDialog.show(SithActivity.this, null, "Loading…");
			};

			@Override
			protected Sith doInBackground(Void... params) {

				try {
					Sith sith = new Sith();
					sith.load(SithActivity.this);
					return sith;

				} catch (NoConnectionException e) {
					onConnectionError();
					return null;

				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
			}

			@Override
			protected void onPostExecute(Sith sith) {

				if (sith != null) {
					printContent(sith);
				}
				mDialog.dismiss();
			}
		}.execute();
	}

	private void printContent(Sith sith) {
		((TextView) findViewById(R.id.tv_side)).setText( sith.getSide() );
		((TextView) findViewById(R.id.tv_names)).setText( sith.getNames() );
		Suit suit = sith.getSuit();
		((TextView) findViewById(R.id.tv_suit_color)).setText( suit.getColor() );
		((TextView) findViewById(R.id.tv_suit_cloak)).setText( String.valueOf(suit.hasCloak()) );
		((TextView) findViewById(R.id.tv_kills)).setText( String.valueOf(sith.getKills()) );
	}
}