text:
package org.pentaho.di.trans;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.pentaho.di.ExecutionConfiguration;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.RepositoryPluginType;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.repository.RepositoriesMeta;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryMeta;
import org.pentaho.di.trans.debug.TransDebugMeta;
import org.w3c.dom.Node;

public class TransExecutionConfiguration implements ExecutionConfiguration {
  public static final String XML_TAG = "transformation_execution_configuration";

  private final LogChannelInterface log = LogChannel.GENERAL;

  private boolean executingLocally;

  private boolean executingRemotely;
  private SlaveServer remoteServer;
  private boolean passingExport;

  private boolean executingClustered;
  private boolean clusterPosting;
  private boolean clusterPreparing;
  private boolean clusterStarting;
  private boolean clusterShowingTransformation;

  private Map<String, String> arguments;
  private Map<String, String> params;
  private Map<String, String> variables;

  private Date replayDate;
  private boolean safeModeEnabled;
  private LogLevel logLevel;
  private boolean clearingLog;

  private TransDebugMeta transDebugMeta;

  private Result previousResult;
  private Repository repository;

  private boolean gatheringMetrics;
  private boolean showingSubComponents;
  private boolean setLogfile;
  private boolean setAppendLogfile;
  private String logFileName;
  private boolean createParentFolder;
  private Long passedBatchId;

  private String runConfiguration;
  private boolean logRemoteExecutionLocally;

  public TransExecutionConfiguration() {
    executingLocally = true;

    clusterPosting = true;
    clusterPreparing = true;
    clusterStarting = true;
    clusterShowingTransformation = false;

    passingExport = false;

    arguments = new HashMap<String, String>();
    params = new HashMap<String, String>();
    variables = new HashMap<String, String>();

    transDebugMeta = null;

    logLevel = LogLevel.BASIC;

    clearingLog = true;

    gatheringMetrics = false;
    showingSubComponents = true;
  }

  public Object clone() {
    try {
      TransExecutionConfiguration configuration = (TransExecutionConfiguration) super.clone();

      configuration.params = new HashMap<String, String>();
      configuration.params.putAll( params );

      configuration.arguments = new HashMap<String, String>();
      configuration.arguments.putAll( arguments );

      configuration.variables = new HashMap<String, String>();
      configuration.variables.putAll( variables );

      return configuration;
    } catch ( CloneNotSupportedException e ) {
      return null;
    }
  }

  /**
   * @return the arguments
   */
  public Map<String, String> getArguments() {
    return arguments;
  }

  /**
   * @param arguments
   *          the arguments to set
   */
  public void setArguments( Map<String, String> arguments ) {
    this.arguments = arguments;
  }

  /**
   * @param params
   *          the parameters to set
   */
  public void setParams( Map<String, String> params ) {
    this.params = params;
  }

  /**
   * @return the parameters.
   */
  public Map<String, String> getParams() {
    return params;
  }

  /**
   * @param arguments
   *          the arguments to set
   */
  public void setArgumentStrings( String[] arguments ) {
    this.arguments = new HashMap<String, String>();
    if ( arguments != null ) {
      for ( int i = 0; i < arguments.length; i++ ) {
        this.arguments.put( "arg " + ( i + 1 ), arguments[i] );
      }
    }
  }

  /**
   * @return the clusteredExecution
   */
  public boolean isExecutingClustered() {
    return executingClustered;
  }

  /**
   * @param clusteredExecution
   *          the clusteredExecution to set
   */
  public void setExecutingClustered( boolean clusteredExecution ) {
    this.executingClustered = clusteredExecution;
  }

  /**
   * @return the notExecuting
   */
  public boolean isClusterStarting() {
    return clusterStarting;
  }

  /**
   * @param notExecuting
   *          the notExecuting to set
   */
  public void setClusterStarting( boolean notExecuting ) {
    this.clusterStarting = notExecuting;
  }

  /**
   * @return the showingTransformations
   */
  public boolean isClusterShowingTransformation() {
    return clusterShowingTransformation;
  }

  /**
   * @param showingTransformations
   *          the showingTransformations to set
   */
  public void setClusterShowingTransformation( boolean showingTransformations ) {
    this.clusterShowingTransformation = showingTransformations;
  }

  /**
   * @return the variables
   */
  public Map<String, String> getVariables() {
    return variables;
  }

  /**
   * @param variables
   *          the variables to set
   */
  public void setVariables( Map<String, String> variables ) {
    this.variables = variables;
  }

  public void setVariables( VariableSpace space ) {
    this.variables = new HashMap<String, String>();

    for ( String name : space.listVariables() ) {
      String value = space.getVariable( name );
      this.variables.put( name, value );
    }
  }

  /**
   * @return the remoteExecution
   */
  public boolean isExecutingRemotely() {
    return executingRemotely;
  }

  /**
   * @param remoteExecution
   *          the remoteExecution to set
   */
  public void setExecutingRemotely( boolean remoteExecution ) {
    this.executingRemotely = remoteExecution;
  }

  /**
   * @return the clusterPosting
   */
  public boolean isClusterPosting() {
    return clusterPosting;
  }

  /**
   * @param clusterPosting
   *          the clusterPosting to set
   */
  public void setClusterPosting( boolean clusterPosting ) {
    this.clusterPosting = clusterPosting;
  }

  /**
   * @return the localExecution
   */
  public boolean isExecutingLocally() {
    return executingLocally;
  }

  /**
   * @param localExecution
   *          the localExecution to set
   */
  public void setExecutingLocally( boolean localExecution ) {
    this.executingLocally = localExecution;
  }

  /**
   * @return the clusterPreparing
   */
  public boolean isClusterPreparing() {
    return clusterPreparing;
  }

  /**
   * @param clusterPreparing
   *          the clusterPreparing to set
   */
  public void setClusterPreparing( boolean clusterPreparing ) {
    this.clusterPreparing = clusterPreparing;
  }

  /**
   * @return the remoteServer
   */
  public SlaveServer getRemoteServer() {
    return remoteServer;
  }

  /**
   * @param remoteServer
   *          the remoteServer to set
   */
  public void setRemoteServer( SlaveServer remoteServer ) {
    this.remoteServer = remoteServer;
  }

  public void getAllVariables( TransMeta transMeta ) {
    Properties sp = new Properties();
    VariableSpace space = Variables.getADefaultVariableSpace();

    String[] keys = space.listVariables();
    for ( int i = 0; i < keys.length; i++ ) {
      sp.put( keys[i], space.getVariable( keys[i] ) );
    }

    String[] vars = transMeta.listVariables();
    if ( vars != null && vars.length > 0 ) {
      HashMap<String, String> newVariables = new HashMap<String, String>();

      for ( int i = 0; i < vars.length; i++ ) {
        String varname = vars[i];
        newVariables.put( varname, Const.NVL( variables.get( varname ), sp.getProperty( varname, "" ) ) );
      }
      // variables.clear();
      variables.putAll( newVariables );
    }

    // Also add the internal job variables if these are set...
    //
    for ( String variableName : Const.INTERNAL_JOB_VARIABLES ) {
      String value = transMeta.getVariable( variableName );
      if ( !Utils.isEmpty( value ) ) {
        variables.put( variableName, value );
      }
    }
  }

  public void getUsedVariables( TransMeta transMeta ) {
    Properties sp = new Properties();
    VariableSpace space = Variables.getADefaultVariableSpace();

    String[] keys = space.listVariables();
    for ( int i = 0; i < keys.length; i++ ) {
      sp.put( keys[i], space.getVariable( keys[i] ) );
    }

    List<String> vars = transMeta.getUsedVariables();
    if ( vars != null && vars.size() > 0 ) {
      HashMap<String, String> newVariables = new HashMap<String, String>();

      for ( int i = 0; i < vars.size(); i++ ) {
        String varname = vars.get( i );
        if ( !varname.startsWith( Const.INTERNAL_VARIABLE_PREFIX ) ) {
          newVariables.put( varname, Const.NVL( variables.get( varname ), sp.getProperty( varname, "" ) ) );
        }
      }
      // variables.clear();
      variables.putAll( newVariables );
    }

    // Also add the internal job variables if these are set...
    //
    for ( String variableName : Const.INTERNAL_JOB_VARIABLES ) {
      String value = transMeta.getVariable( variableName );
      if ( !Utils.isEmpty( value ) ) {
        variables.put( variableName, value );
      }
    }
  }

  public void getUsedArguments( TransMeta transMeta, String[] commandLineArguments ) {
    // OK, see if we need to ask for some arguments first...
    //
    Map<String, String> map = transMeta.getUsedArguments( commandLineArguments );
    for ( String key : map.keySet() ) {
      String value = map.get( key );
      if ( !arguments.containsKey( key ) ) {
        arguments.put( key, value );
      }
    }
  }

  /**
   * @return the replayDate
   */
  public Date getReplayDate() {
    return replayDate;
  }

  /**
   * @param replayDate
   *          the replayDate to set
   */
  public void setReplayDate( Date replayDate ) {
    this.replayDate = replayDate;
  }

  /**
   * @return the usingSafeMode
   */
  public boolean isSafeModeEnabled() {
    return safeModeEnabled;
  }

  /**
   * @param usingSafeMode
   *          the usingSafeMode to set
   */
  public void setSafeModeEnabled( boolean usingSafeMode ) {
    this.safeModeEnabled = usingSafeMode;
  }

  /**
   * @return the logLevel
   */
  public LogLevel getLogLevel() {
    return logLevel;
  }

  /**
   * @param logLevel
   *          the logLevel to set
   */
  public void setLogLevel( LogLevel logLevel ) {
    this.logLevel = logLevel;
  }

  public String getXML() throws IOException {
    StringBuilder xml = new StringBuilder( 200 );

    xml.append( "  <" + XML_TAG + ">" ).append( Const.CR );

    xml.append( "    " ).append( XMLHandler.addTagValue( "exec_local", executingLocally ) );

    xml.append( "    " ).append( XMLHandler.addTagValue( "exec_remote", executingRemotely ) );
    if ( remoteServer != null ) {
      xml.append( "    " ).append( remoteServer.getXML() ).append( Const.CR );
    }
    xml.append( "    " ).append( XMLHandler.addTagValue( "pass_export", passingExport ) );

    xml.append( "    " ).append( XMLHandler.addTagValue( "exec_cluster", executingClustered ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "cluster_post", clusterPosting ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "cluster_prepare", clusterPreparing ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "cluster_start", clusterStarting ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "cluster_show_trans", clusterShowingTransformation ) );

    // Serialize the parameters...
    //
    xml.append( "    <parameters>" ).append( Const.CR );
    List<String> paramNames = new ArrayList<String>( params.keySet() );
    Collections.sort( paramNames );
    for ( String name : paramNames ) {
      String value = params.get( name );
      xml.append( "    <parameter>" );
      xml.append( XMLHandler.addTagValue( "name", name, false ) );
      xml.append( XMLHandler.addTagValue( "value", value, false ) );
      xml.append( "</parameter>" ).append( Const.CR );
    }
    xml.append( "    </parameters>" ).append( Const.CR );

    // Serialize the variables...
    //
    xml.append( "    <variables>" ).append( Const.CR );
    List<String> variableNames = new ArrayList<String>( variables.keySet() );
    Collections.sort( variableNames );
    for ( String name : variableNames ) {
      String value = variables.get( name );
      xml.append( "    <variable>" );
      xml.append( XMLHandler.addTagValue( "name", name, false ) );
      xml.append( XMLHandler.addTagValue( "value", value, false ) );
      xml.append( "</variable>" ).append( Const.CR );
    }
    xml.append( "    </variables>" ).append( Const.CR );

    // Serialize the variables...
    //
    xml.append( "    <arguments>" ).append( Const.CR );
    List<String> argumentNames = new ArrayList<String>( arguments.keySet() );
    Collections.sort( argumentNames );
    for ( String name : argumentNames ) {
      String value = arguments.get( name );
      xml.append( "    <argument>" );
      xml.append( XMLHandler.addTagValue( "name", name, false ) );
      xml.append( XMLHandler.addTagValue( "value", value, false ) );
      xml.append( "</argument>" ).append( Const.CR );
    }
    xml.append( "    </arguments>" ).append( Const.CR );

    // IMPORTANT remote debugging is not yet supported
    //
    // xml.append(transDebugMeta.getXML());

    xml.append( "    " ).append( XMLHandler.addTagValue( "replay_date", replayDate ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "safe_mode", safeModeEnabled ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "log_level", logLevel.getCode() ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "log_file", setLogfile ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "log_filename", logFileName ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "log_file_append", setAppendLogfile ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "create_parent_folder", createParentFolder ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "clear_log", clearingLog ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "gather_metrics", gatheringMetrics ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "show_subcomponents", showingSubComponents ) );
    if ( passedBatchId != null ) {
      xml.append( "    " ).append( XMLHandler.addTagValue( "passedBatchId", passedBatchId ) );
    }
    xml.append( "    " ).append( XMLHandler.addTagValue( "run_configuration", runConfiguration ) );

    // The source rows...
    //
    if ( previousResult != null ) {
      xml.append( previousResult.getXML() );
    }

    // Send the repository name and user to the remote site...
    //
    if ( repository != null ) {
      xml.append( XMLHandler.openTag( "repository" ) );
      xml.append( XMLHandler.addTagValue( "name", repository.getName() ) );
      // File base repositories doesn't have user info
      if ( repository.getUserInfo() != null ) {
        xml.append( XMLHandler.addTagValue( "login", repository.getUserInfo().getLogin() ) );
        xml.append( XMLHandler.addTagValue( "password", Encr.encryptPassword( repository
          .getUserInfo().getPassword() ) ) );
      }
      xml.append( XMLHandler.closeTag( "repository" ) );
    }

    xml.append( "</" + XML_TAG + ">" ).append( Const.CR );
    return xml.toString();
  }

  public TransExecutionConfiguration( Node trecNode ) throws KettleException {
    this();

    executingLocally = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "exec_local" ) );

    executingRemotely = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "exec_remote" ) );
    Node remoteHostNode = XMLHandler.getSubNode( trecNode, SlaveServer.XML_TAG );
    if ( remoteHostNode != null ) {
      remoteServer = new SlaveServer( remoteHostNode );
    }
    passingExport = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "pass_export" ) );

    executingClustered = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "exec_cluster" ) );
    clusterPosting = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "cluster_post" ) );
    clusterPreparing = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "cluster_prepare" ) );
    clusterStarting = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "cluster_start" ) );
    clusterShowingTransformation = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "cluster_show_trans" ) );

    // Read the variables...
    //
    Node varsNode = XMLHandler.getSubNode( trecNode, "variables" );
    int nrVariables = XMLHandler.countNodes( varsNode, "variable" );
    for ( int i = 0; i < nrVariables; i++ ) {
      Node argNode = XMLHandler.getSubNodeByNr( varsNode, "variable", i );
      String name = XMLHandler.getTagValue( argNode, "name" );
      String value = XMLHandler.getTagValue( argNode, "value" );
      if ( !Utils.isEmpty( name ) ) {
        variables.put( name, Const.NVL( value, "" ) );
      }
    }

    // Read the arguments...
    //
    Node argsNode = XMLHandler.getSubNode( trecNode, "arguments" );
    int nrArguments = XMLHandler.countNodes( argsNode, "argument" );
    for ( int i = 0; i < nrArguments; i++ ) {
      Node argNode = XMLHandler.getSubNodeByNr( argsNode, "argument", i );
      String name = XMLHandler.getTagValue( argNode, "name" );
      String value = XMLHandler.getTagValue( argNode, "value" );
      if ( !Utils.isEmpty( name ) && !Utils.isEmpty( value ) ) {
        arguments.put( name, value );
      }
    }

    // Read the parameters...
    //
    Node parmsNode = XMLHandler.getSubNode( trecNode, "parameters" );
    int nrParams = XMLHandler.countNodes( parmsNode, "parameter" );
    for ( int i = 0; i < nrParams; i++ ) {
      Node parmNode = XMLHandler.getSubNodeByNr( parmsNode, "parameter", i );
      String name = XMLHandler.getTagValue( parmNode, "name" );
      String value = XMLHandler.getTagValue( parmNode, "value" );
      if ( !Utils.isEmpty( name ) ) {
        params.put( name, value );
      }
    }

    // IMPORTANT: remote preview and remote debugging is NOT yet supported.
    //

    replayDate = XMLHandler.stringToDate( XMLHandler.getTagValue( trecNode, "replay_date" ) );
    safeModeEnabled = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "safe_mode" ) );
    logLevel = LogLevel.getLogLevelForCode( XMLHandler.getTagValue( trecNode, "log_level" ) );
    setLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "log_file" ) );
    logFileName = XMLHandler.getTagValue( trecNode, "log_filename" );
    setAppendLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "log_file_append" ) );
    createParentFolder = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "create_parent_folder" ) );
    clearingLog = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "clear_log" ) );
    gatheringMetrics = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "gather_metrics" ) );
    showingSubComponents = "Y".equalsIgnoreCase( XMLHandler.getTagValue( trecNode, "show_subcomponents" ) );
    String sPassedBatchId = XMLHandler.getTagValue( trecNode, "passedBatchId" );
    if ( !StringUtils.isEmpty( sPassedBatchId ) ) {
      passedBatchId = Long.parseLong( sPassedBatchId );
    }
    runConfiguration = XMLHandler.getTagValue( trecNode, "run_configuration" );

    Node resultNode = XMLHandler.getSubNode( trecNode, Result.XML_TAG );
    if ( resultNode != null ) {
      try {
        previousResult = new Result( resultNode );
      } catch ( KettleException e ) {
        throw new KettleException( "Unable to hydrate previous result", e );
      }
    }

    // Try to get a handle to the repository from here...
    //
    Node repNode = XMLHandler.getSubNode( trecNode, "repository" );
    if ( repNode != null ) {
      String repositoryName = XMLHandler.getTagValue( repNode, "name" );
      String username = XMLHandler.getTagValue( repNode, "login" );
      String password = Encr.decryptPassword( XMLHandler.getTagValue( repNode, "password" ) );

      RepositoriesMeta repositoriesMeta = new RepositoriesMeta();
      repositoriesMeta.getLog().setLogLevel( log.getLogLevel() );
      try {
        repositoriesMeta.readData();
      } catch ( Exception e ) {
        throw new KettleException( "Unable to get a list of repositories to locate repository '" + repositoryName + "'" );
      }
      connectRepository( repositoriesMeta, repositoryName, username, password );
    }
  }

  public Repository connectRepository( RepositoriesMeta repositoriesMeta, String repositoryName, String username, String password ) throws KettleException {
    RepositoryMeta repositoryMeta = repositoriesMeta.findRepository( repositoryName );
    if ( repositoryMeta == null ) {
      log.logBasic( "I couldn't find the repository with name '" + repositoryName + "'" );
      return null;
    }
    Repository rep = PluginRegistry.getInstance().loadClass( RepositoryPluginType.class, repositoryMeta, Repository.class );
    if ( rep == null ) {
      log.logBasic( "Unable to load repository plugin for '" + repositoryName + "'" );
      return null;
    }
    rep.init( repositoryMeta );

    try {
      rep.connect( username, password );
      setRepository( rep );
      return rep;
    } catch ( Exception e ) {
      log.logBasic( "Unable to connect to the repository with name '" + repositoryName + "'" );
      return null;
    }
  }

  public String[] getArgumentStrings() {
    if ( arguments == null || arguments.size() == 0 ) {
      return null;
    }

    String[] argNames = arguments.keySet().toArray( new String[arguments.size()] );
    Arrays.sort( argNames );

    String[] values = new String[argNames.length];
    for ( int i = 0; i < argNames.length; i++ ) {
      if ( argNames[i].equalsIgnoreCase( Props.STRING_ARGUMENT_NAME_PREFIX + ( i + 1 ) ) ) {
        values[i] = arguments.get( argNames[i] );
      }
    }

    return values;
  }

  /**
   * @return the transDebugMeta
   */
  public TransDebugMeta getTransDebugMeta() {
    return transDebugMeta;
  }

  /**
   * @param transDebugMeta
   *          the transDebugMeta to set
   */
  public void setTransDebugMeta( TransDebugMeta transDebugMeta ) {
    this.transDebugMeta = transDebugMeta;
  }

  /**
   * @return the previousResult
   */
  public Result getPreviousResult() {
    return previousResult;
  }

  /**
   * @param previousResult
   *          the previousResult to set
   */
  public void setPreviousResult( Result previousResult ) {
    this.previousResult = previousResult;
  }

  /**
   * @return the repository
   */
  public Repository getRepository() {
    return repository;
  }

  /**
   * @param repository
   *          the repository to set
   */
  public void setRepository( Repository repository ) {
    this.repository = repository;
  }

  /**
   * @return the clearingLog
   */
  public boolean isClearingLog() {
    return clearingLog;
  }

  /**
   * @param clearingLog
   *          the clearingLog to set
   */
  public void setClearingLog( boolean clearingLog ) {
    this.clearingLog = clearingLog;
  }

  /**
   * @return the passingExport
   */
  public boolean isPassingExport() {
    return passingExport;
  }

  /**
   * @param passingExport
   *          the passingExport to set
   */
  public void setPassingExport( boolean passingExport ) {
    this.passingExport = passingExport;
  }

  /**
   * @return the gatheringMetrics
   */
  public boolean isGatheringMetrics() {
    return gatheringMetrics;
  }

  /**
   * @param gatheringMetrics
   *          the gatheringMetrics to set
   */
  public void setGatheringMetrics( boolean gatheringMetrics ) {
    this.gatheringMetrics = gatheringMetrics;
  }

  /**
   * @return the showingSubComponents
   */
  public boolean isShowingSubComponents() {
    return showingSubComponents;
  }

  /**
   * @param showingSubComponents
   *          the showingSubComponents to set
   */
  public void setShowingSubComponents( boolean showingSubComponents ) {
    this.showingSubComponents = showingSubComponents;
  }

  public boolean isSetLogfile() {
    return setLogfile;
  }

  public void setSetLogfile( boolean setLogfile ) {
    this.setLogfile = setLogfile;
  }

  public boolean isSetAppendLogfile() {
    return setAppendLogfile;
  }

  public void setSetAppendLogfile( boolean setAppendLogfile ) {
    this.setAppendLogfile = setAppendLogfile;
  }

  public String getLogFileName() {
    return logFileName;
  }

  public void setLogFileName( String fileName ) {
    this.logFileName = fileName;
  }

  public boolean isCreateParentFolder() {
    return createParentFolder;
  }

  public void setCreateParentFolder( boolean createParentFolder ) {
    this.createParentFolder = createParentFolder;
  }

  public Long getPassedBatchId() {
    return passedBatchId;
  }

  public void setPassedBatchId( Long passedBatchId ) {
    this.passedBatchId = passedBatchId;
  }

  public String getRunConfiguration() {
    return runConfiguration;
  }

  public void setRunConfiguration( String runConfiguration ) {
    this.runConfiguration = runConfiguration;
  }

  public boolean isLogRemoteExecutionLocally() {
    return logRemoteExecutionLocally;
  }

  public void setLogRemoteExecutionLocally( boolean logRemoteExecutionLocally ) {
    this.logRemoteExecutionLocally = logRemoteExecutionLocally;
  }
}


text:
package com.twitter.parrot.server

import com.twitter.finagle.Service
import com.twitter.parrot.config.ParrotServerConfig
import com.twitter.util.Future

class ParrotService[Req <: ParrotRequest, Rep](val queue: RequestQueue[Req, Rep]) extends Service[Req, Rep] {

  def apply(req: Req): Future[Rep] = {
    queue.addRequest(req)
  }

}

redpajama_set_name: RedPajamaGithub


text:
@interface PodsDummy_EXPermissions : NSObject
@end
@implementation PodsDummy_EXPermissions
@end


text:
require 'sprockets_test'
require 'sprockets/bundle'

silence_warnings do
  require 'sass'
end

class TestSourceMaps < Sprockets::TestCase
  def setup
    @env = Sprockets::Environment.new
    @env.append_path fixture_path('source-maps')
  end

  test "compile coffeescript source map" do
    assert asset = @env.find_asset("coffee/main.js")
    assert_equal fixture_path('source-maps/coffee/main.coffee'), asset.filename
    assert_equal "application/javascript", asset.content_type

    assert_match "(function() {", asset.source
    assert_match "Math.sqrt", asset.source

    assert asset = @env.find_asset("coffee/main.js.map")
    assert_equal fixture_path('source-maps/coffee/main.coffee'), asset.filename
    assert_equal "coffee/main.js.map", asset.logical_path
    assert_equal "application/js-sourcemap+json", asset.content_type

    # Dummy data, make it real in 4.x
    assert map = JSON.parse(asset.source)
    assert_equal({
      "version" => 3,
      "file" => "coffee/main.js",
      "mappings" => ";123"
    }, map)
  end

  test "use precompiled coffeescript source map" do
    assert asset = @env.find_asset("coffee/precompiled/main.js")
    assert_equal fixture_path('source-maps/coffee/precompiled/main.coffee'), asset.filename
    assert_equal "application/javascript", asset.content_type

    assert_match "(function() {", asset.source
    assert_match "Math.sqrt", asset.source

    assert asset = @env.find_asset("coffee/precompiled/main.js.map")
    assert_equal fixture_path('source-maps/coffee/precompiled/main.js.map'), asset.filename
    assert_equal "coffee/precompiled/main.js.map", asset.logical_path
    assert_equal "application/js-sourcemap+json", asset.content_type

    assert map = JSON.parse(asset.source)
    assert_equal 3, map['version']
    assert_equal "main.js", map['file']
    assert_equal 779, map['mappings'].size
  end

  test "compile scss source map" do
    asset = silence_warnings do
      @env.find_asset("sass/main.css")
    end
    assert asset
    assert_equal fixture_path('source-maps/sass/main.scss'), asset.filename
    assert_equal "text/css", asset.content_type

    assert_match "nav a {", asset.source

    asset = silence_warnings do
      @env.find_asset("sass/main.css.map")
    end
    assert asset
    assert_equal fixture_path('source-maps/sass/main.scss'), asset.filename
    assert_equal "sass/main.css.map", asset.logical_path
    assert_equal "application/css-sourcemap+json", asset.content_type

    # Dummy data, make it real in 4.x
    assert map = JSON.parse(asset.source)
    assert_equal({
      "version" => 3,
      "file" => "sass/main.css",
      "mappings" => ";123"
    }, map)
  end

  test "use precompiled scss source map" do
    asset = silence_warnings do
      @env.find_asset("sass/precompiled/main.css")
    end
    assert asset
    assert_equal fixture_path('source-maps/sass/precompiled/main.css'), asset.filename
    assert_equal "text/css", asset.content_type

    assert_match "nav a {", asset.source

    asset = silence_warnings do
      @env.find_asset("sass/precompiled/main.css.map")
    end
    assert asset
    assert_equal fixture_path('source-maps/sass/precompiled/main.css.map'), asset.filename
    assert_equal "sass/precompiled/main.css.map", asset.logical_path
    assert_equal "application/css-sourcemap+json", asset.content_type

    assert map = JSON.parse(asset.source)
    assert_equal 3, map['version']
    assert_equal "main.css", map['file']
    assert_equal 172, map['mappings'].size
  end
end


text:
package ch.idsia.evolution;

import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: julian
 * Date: May 24, 2009
 * Time: 11:12:32 PM
 * <p/>
 * Simple Recurrent Network (a.k.a. Elman network, Recurrent MLP)
 */
public class SRN implements FA<double[], double[]>, Evolvable
{

protected double[][] firstConnectionLayer;
protected double[][] recurrentConnectionLayer;
protected double[][] secondConnectionLayer;
protected double[] hiddenNeurons;
protected double[] hiddenNeuronsCopy;
protected double[] outputs;
protected double mutationMagnitude = 0.1;

private final Random random = new Random();

public SRN(int numberOfInputs, int numberOfHidden, int numberOfOutputs)
{
    firstConnectionLayer = new double[numberOfInputs][numberOfHidden];
    recurrentConnectionLayer = new double[numberOfHidden][numberOfHidden];
    secondConnectionLayer = new double[numberOfHidden][numberOfOutputs];
    hiddenNeurons = new double[numberOfHidden];
    hiddenNeuronsCopy = new double[numberOfHidden];
    outputs = new double[numberOfOutputs];
    mutate();
}

public SRN(double[][] firstConnectionLayer, double[][] recurrentConnectionLayer,
           double[][] secondConnectionLayer, int numberOfHidden,
           int numberOfOutputs)
{
    this.firstConnectionLayer = firstConnectionLayer;
    this.recurrentConnectionLayer = recurrentConnectionLayer;
    this.secondConnectionLayer = secondConnectionLayer;
    hiddenNeurons = new double[numberOfHidden];
    hiddenNeuronsCopy = new double[numberOfHidden];
    outputs = new double[numberOfOutputs];
}

public double[] propagate(double[] inputs)
{

    if (inputs.length != firstConnectionLayer.length)
        System.out.println("NOTE: only " + inputs.length + " inputs out of " + firstConnectionLayer.length + " are used in the network");

    System.arraycopy(hiddenNeurons, 0, hiddenNeuronsCopy, 0, hiddenNeurons.length);
    clear(hiddenNeurons);
    clear(outputs);
    propagateOneStep(inputs, hiddenNeurons, firstConnectionLayer);
    propagateOneStep(hiddenNeuronsCopy, hiddenNeurons, recurrentConnectionLayer);
    tanh(hiddenNeurons);
    propagateOneStep(hiddenNeurons, outputs, secondConnectionLayer);
    tanh(outputs);
    return outputs;
}

public SRN getNewInstance()
{
    return new SRN(firstConnectionLayer.length, secondConnectionLayer.length, outputs.length);
}

public SRN copy()
{
    return new SRN(copy(firstConnectionLayer), copy(recurrentConnectionLayer),
            copy(secondConnectionLayer), hiddenNeurons.length, outputs.length);
}

public void mutate()
{
    mutate(firstConnectionLayer);
    mutate(recurrentConnectionLayer);
    mutate(secondConnectionLayer);
}

public void reset()
{
    clear(hiddenNeurons);
    clear(hiddenNeuronsCopy);
}

public double[] approximate(double[] doubles)
{
    return propagate(doubles);
}

protected double[][] copy(double[][] original)
{
    double[][] copy = new double[original.length][original[0].length];
    for (int i = 0; i < original.length; i++)
    {
        System.arraycopy(original[i], 0, copy[i], 0, original[i].length);
    }
    return copy;
}

protected void mutate(double[] array)
{
    for (int i = 0; i < array.length; i++)
    {
        array[i] += random.nextGaussian() * mutationMagnitude;
    }
}

protected void mutate(double[][] array)
{
    for (double[] anArray : array)
    {
        mutate(anArray);
    }
}

protected void propagateOneStep(double[] fromLayer, double[] toLayer, double[][] connections)
{
    for (int from = 0; from < fromLayer.length; from++)
    {
        for (int to = 0; to < toLayer.length; to++)
        {
            toLayer[to] += fromLayer[from] * connections[from][to];
        }
    }
}

protected void clear(double[] array)
{
    for (int i = 0; i < array.length; i++)
    {
        array[i] = 0;
    }
}

protected void tanh(double[] array)
{
    for (int i = 0; i < array.length; i++)
    {
        array[i] = Math.tanh(array[i]);
    }
}

public String toString()
{
    return "RecurrentMLP:" + firstConnectionLayer.length + "/" + secondConnectionLayer.length + "/" + outputs.length;
}

public void setMutationMagnitude(double mutationMagnitude)
{
    this.mutationMagnitude = mutationMagnitude;
}

}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::Web::ImageConfig::contigviewtop;

use strict;
use warnings;

use previous qw(init_cacheable);

use parent qw(EnsEMBL::Web::ImageConfig::Genoverse);

sub init_cacheable {
  my $self = shift;

  $self->PREV::init_cacheable(@_);

  $self->init_genoverse;
  $self->set_parameter('zoom', 'no');
}

sub reset {
  shift->reset_genoverse(@_);
}

sub glyphset_tracks {
  shift->_glyphset_tracks(@_);
}

1;


text:
package openblocks.common.item;

import java.util.List;

import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import openblocks.Config;
import openblocks.integration.TurtleIds;
import openblocks.integration.TurtleUtils;

public class MetaMiracleMagnet extends MetaGeneric {
	public MetaMiracleMagnet(String name, Object... recipes) {
		super(name, recipes);
	}

	@Override
	public void registerIcons(IIconRegister register) {
		registerIcon(register, "crane_magnet"); // reuse!
	}

	@Override
	public boolean hasEffect(int renderPass) {
		return true;
	}

	@Override
	public void addToCreativeList(Item item, int meta, List<ItemStack> result) {
		super.addToCreativeList(item, meta, result);

		if (Config.enableCraneTurtles && Config.showCraneTurtles) {
			TurtleUtils.addUpgradedTurtles(result, TurtleIds.MAGNET_TURTLE_ID);
		}
	}
}


text:
package templates

import (
	"context"
	"fmt"
	"time"

	g "github.com/onsi/ginkgo"
	o "github.com/onsi/gomega"
	"k8s.io/apimachinery/pkg/api/apitesting"

	corev1 "k8s.io/api/core/v1"
	storagev1 "k8s.io/api/storage/v1"
	kerrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/kubernetes/pkg/api/legacyscheme"

	authorizationv1 "github.com/openshift/api/authorization/v1"
	routev1 "github.com/openshift/api/route/v1"
	templatev1 "github.com/openshift/api/template/v1"
	userv1 "github.com/openshift/api/user/v1"

	exutil "github.com/openshift/origin/test/extended/util"
)

// Check that objects created through the TemplateInstance mechanism are done
// impersonating the requester, and that privilege escalation is not possible.
var _ = g.Describe("[sig-devex][Feature:Templates] templateinstance security tests", func() {
	defer g.GinkgoRecover()

	var (
		cli = exutil.NewCLI("templates")

		adminuser, edituser, editbygroupuser *userv1.User
		editgroup                            *userv1.Group

		dummyroute = &routev1.Route{
			TypeMeta: metav1.TypeMeta{
				Kind:       "Route",
				APIVersion: "route.openshift.io/v1",
			},
			ObjectMeta: metav1.ObjectMeta{
				Name:      "route",
				Namespace: "${NAMESPACE}",
			},
			Spec: routev1.RouteSpec{
				To: routev1.RouteTargetReference{
					Name: "dummyroute",
				},
			},
		}

		dummyrolebinding = &authorizationv1.RoleBinding{
			TypeMeta: metav1.TypeMeta{
				Kind:       "RoleBinding",
				APIVersion: "authorization.openshift.io/v1",
			},
			ObjectMeta: metav1.ObjectMeta{
				Name:      "rolebinding",
				Namespace: "${NAMESPACE}",
			},
			RoleRef: corev1.ObjectReference{
				Name: "admin",
			},
		}

		storageclass = &storagev1.StorageClass{
			TypeMeta: metav1.TypeMeta{
				Kind:       "StorageClass",
				APIVersion: "storage.k8s.io/v1",
			},
			ObjectMeta: metav1.ObjectMeta{
				Name: "storageclass",
			},
			Provisioner: "no-provisioning",
		}
	)

	g.Context("[apigroup:authorization.openshift.io][apigroup:template.openshift.io]", func() {
		g.BeforeEach(func() {
			adminuser = createUser(cli, "adminuser", "admin")
			edituser = createUser(cli, "edituser", "edit")
			editbygroupuser = createUser(cli, "editbygroupuser", "")

			editgroup = createGroup(cli, "editgroup", "edit")
			addUserToGroup(cli, editbygroupuser.Name, editgroup.Name)

			// I think we get flakes when the group cache hasn't yet noticed the
			// new group membership made above.  Wait until all it looks like
			// all the users above have access to the namespace as expected.
			err := wait.PollImmediate(time.Second, 30*time.Second, func() (done bool, err error) {
				for _, user := range []*userv1.User{adminuser, edituser, editbygroupuser} {
					cli.ChangeUser(user.Name)
					sar, err := cli.AuthorizationClient().AuthorizationV1().LocalSubjectAccessReviews(cli.Namespace()).Create(context.Background(), &authorizationv1.LocalSubjectAccessReview{
						Action: authorizationv1.Action{
							Verb:     "get",
							Resource: "pods",
						},
					}, metav1.CreateOptions{})
					if err != nil {
						return false, err
					}
					if !sar.Allowed {
						return false, nil
					}
				}
				return true, nil
			})
			o.Expect(err).NotTo(o.HaveOccurred())
		})

		g.AfterEach(func() {
			if g.CurrentGinkgoTestDescription().Failed {
				templateinstances, err := cli.AdminTemplateClient().TemplateV1().TemplateInstances(cli.Namespace()).List(context.Background(), metav1.ListOptions{})
				if err == nil {
					fmt.Fprintf(g.GinkgoWriter, "TemplateInstances: %#v", templateinstances.Items)
				}
			}

			deleteUser(cli, adminuser)
			deleteUser(cli, edituser)
			deleteUser(cli, editbygroupuser)

			deleteGroup(cli, editgroup)
		})

		g.It("should pass security tests [apigroup:route.openshift.io]", func() {
			tests := []struct {
				by              string
				user            *userv1.User
				namespace       string
				objects         []runtime.Object
				expectCondition templatev1.TemplateInstanceConditionType
				checkOK         func(namespace string) bool
			}{
				{
					by:              "checking edituser can create an object in a permitted namespace",
					user:            edituser,
					namespace:       cli.Namespace(),
					objects:         []runtime.Object{dummyroute},
					expectCondition: templatev1.TemplateInstanceReady,
					checkOK: func(namespace string) bool {
						_, err := cli.AdminRouteClient().RouteV1().Routes(namespace).Get(context.Background(), dummyroute.Name, metav1.GetOptions{})
						return err == nil
					},
				},
				{
					by:              "checking editbygroupuser can create an object in a permitted namespace",
					user:            editbygroupuser,
					namespace:       cli.Namespace(),
					objects:         []runtime.Object{dummyroute},
					expectCondition: templatev1.TemplateInstanceReady,
					checkOK: func(namespace string) bool {
						_, err := cli.AdminRouteClient().RouteV1().Routes(namespace).Get(context.Background(), dummyroute.Name, metav1.GetOptions{})
						return err == nil
					},
				},
				{
					by:              "checking edituser can't create an object in a non-permitted namespace",
					user:            edituser,
					namespace:       "default",
					objects:         []runtime.Object{dummyroute},
					expectCondition: templatev1.TemplateInstanceInstantiateFailure,
					checkOK: func(namespace string) bool {
						_, err := cli.AdminRouteClient().RouteV1().Routes(namespace).Get(context.Background(), dummyroute.Name, metav1.GetOptions{})
						return err != nil && kerrors.IsNotFound(err)
					},
				},
				{
					by:              "checking editbygroupuser can't create an object in a non-permitted namespace",
					user:            editbygroupuser,
					namespace:       "default",
					objects:         []runtime.Object{dummyroute},
					expectCondition: templatev1.TemplateInstanceInstantiateFailure,
					checkOK: func(namespace string) bool {
						_, err := cli.AdminRouteClient().RouteV1().Routes(namespace).Get(context.Background(), dummyroute.Name, metav1.GetOptions{})
						return err != nil && kerrors.IsNotFound(err)
					},
				},
				{
					by:              "checking edituser can't create an object that requires admin",
					user:            edituser,
					namespace:       cli.Namespace(),
					objects:         []runtime.Object{dummyrolebinding},
					expectCondition: templatev1.TemplateInstanceInstantiateFailure,
					checkOK: func(namespace string) bool {
						_, err := cli.AdminAuthorizationClient().AuthorizationV1().RoleBindings(namespace).Get(context.Background(), dummyrolebinding.Name, metav1.GetOptions{})
						return err != nil && kerrors.IsNotFound(err)
					},
				},
				{
					by:              "checking editbygroupuser can't create an object that requires admin",
					user:            editbygroupuser,
					namespace:       cli.Namespace(),
					objects:         []runtime.Object{dummyrolebinding},
					expectCondition: templatev1.TemplateInstanceInstantiateFailure,
					checkOK: func(namespace string) bool {
						_, err := cli.AdminAuthorizationClient().AuthorizationV1().RoleBindings(namespace).Get(context.Background(), dummyrolebinding.Name, metav1.GetOptions{})
						return err != nil && kerrors.IsNotFound(err)
					},
				},
				{
					by:              "checking adminuser can create an object that requires admin",
					user:            adminuser,
					namespace:       cli.Namespace(),
					objects:         []runtime.Object{dummyrolebinding},
					expectCondition: templatev1.TemplateInstanceReady,
					checkOK: func(namespace string) bool {
						_, err := cli.AdminAuthorizationClient().AuthorizationV1().RoleBindings(namespace).Get(context.Background(), dummyrolebinding.Name, metav1.GetOptions{})
						return err == nil
					},
				},
				{
					by:              "checking adminuser can't create an object that requires more than admin",
					user:            adminuser,
					namespace:       cli.Namespace(),
					objects:         []runtime.Object{storageclass},
					expectCondition: templatev1.TemplateInstanceInstantiateFailure,
					checkOK: func(namespace string) bool {
						_, err := cli.AdminKubeClient().StorageV1().StorageClasses().Get(context.Background(), storageclass.Name, metav1.GetOptions{})
						return err != nil && kerrors.IsNotFound(err)
					},
				},
			}

			targetVersions := []schema.GroupVersion{storagev1.SchemeGroupVersion}
			targetVersions = append(targetVersions, legacyscheme.Scheme.PrioritizedVersionsAllGroups()...)

			for _, test := range tests {
				g.By(test.by)
				cli.ChangeUser(test.user.Name)

				secret, err := cli.KubeClient().CoreV1().Secrets(cli.Namespace()).Create(context.Background(), &corev1.Secret{
					ObjectMeta: metav1.ObjectMeta{
						Name: "secret",
					},
					Data: map[string][]byte{
						"NAMESPACE": []byte(test.namespace),
					},
				}, metav1.CreateOptions{})
				o.Expect(err).NotTo(o.HaveOccurred())

				templateinstance := &templatev1.TemplateInstance{
					ObjectMeta: metav1.ObjectMeta{
						Name: "templateinstance",
					},
					Spec: templatev1.TemplateInstanceSpec{
						Template: templatev1.Template{
							ObjectMeta: metav1.ObjectMeta{
								Name:      "template",
								Namespace: cli.Namespace(),
							},
							Parameters: []templatev1.Parameter{
								{
									Name:     "NAMESPACE",
									Required: true,
								},
							},
						},
						Secret: &corev1.LocalObjectReference{
							Name: "secret",
						},
					},
				}

				_, testCodecFactory := apitesting.SchemeForOrDie(routev1.Install, authorizationv1.Install, storagev1.AddToScheme)
				testCodec := testCodecFactory.LegacyCodec(routev1.GroupVersion, authorizationv1.SchemeGroupVersion, storagev1.SchemeGroupVersion)

				for i := range test.objects {
					templateinstance.Spec.Template.Objects = append(templateinstance.Spec.Template.Objects, runtime.RawExtension{
						Raw:    []byte(runtime.EncodeOrDie(testCodec, test.objects[i])),
						Object: test.objects[i],
					})
				}

				templateinstance, err = cli.TemplateClient().TemplateV1().TemplateInstances(cli.Namespace()).Create(context.Background(), templateinstance, metav1.CreateOptions{})
				o.Expect(err).NotTo(o.HaveOccurred())

				err = wait.Poll(100*time.Millisecond, 1*time.Minute, func() (bool, error) {
					templateinstance, err = cli.TemplateClient().TemplateV1().TemplateInstances(cli.Namespace()).Get(context.Background(), templateinstance.Name, metav1.GetOptions{})
					if err != nil {
						return false, err
					}
					return len(templateinstance.Status.Conditions) != 0, nil
				})
				o.Expect(err).NotTo(o.HaveOccurred())

				o.Expect(TemplateInstanceHasCondition(templateinstance, test.expectCondition, corev1.ConditionTrue)).To(o.Equal(true))
				o.Expect(test.checkOK(test.namespace)).To(o.BeTrue())

				foreground := metav1.DeletePropagationForeground
				err = cli.TemplateClient().TemplateV1().TemplateInstances(cli.Namespace()).Delete(context.Background(), templateinstance.Name, metav1.DeleteOptions{PropagationPolicy: &foreground})
				o.Expect(err).NotTo(o.HaveOccurred())

				// wait for garbage collector to do its thing
				err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) {
					_, err = cli.TemplateClient().TemplateV1().TemplateInstances(cli.Namespace()).Get(context.Background(), templateinstance.Name, metav1.GetOptions{})
					if kerrors.IsNotFound(err) {
						return true, nil
					}
					return false, err
				})
				o.Expect(err).NotTo(o.HaveOccurred())

				err = cli.KubeClient().CoreV1().Secrets(cli.Namespace()).Delete(context.Background(), secret.Name, metav1.DeleteOptions{})
				o.Expect(err).NotTo(o.HaveOccurred())
			}
		})
	})
})

func TemplateInstanceHasCondition(templateInstance *templatev1.TemplateInstance, typ templatev1.TemplateInstanceConditionType, status corev1.ConditionStatus) bool {
	for _, c := range templateInstance.Status.Conditions {
		if c.Type == typ && c.Status == status {
			return true
		}
	}
	return false
}


text:
var _ = require('lodash');

// if exports is an array, it will be the same like loading multiple files...
//module.exports = require('cqrs-domain').defineCommand({
module.exports = require('../../../../../../../').defineCommand({
  name: 'unregisterAllContactInformation',  // optional, default is file name without extension
  version: 2, // optional, default 0
  payload: '' // if not defined it will use what is defined as default in aggregate or pass the whole command...
}, function (cmd, aggregate) {

  _.each(aggregate.get('phoneNumbers'), function(number) {
    aggregate.apply('unregisteredPhoneNumber', {
      number: number
    });
    // or
    // aggregate.apply({
    //   event: 'unregisteredPhoneNumber',
    //   payload: {
    //     number: number
    //   }
    // });
  });

  _.each(aggregate.get('emails'), function(mail) {
    aggregate.apply('unregisteredEMailAddress', {
      email: mail
    });
    // or
    // aggregate.apply(aggregate.toEvent({
    //   event: 'unregisteredEMailAddress',
    //   payload: {
    //     email: mail
    //   }
    // });
  });
});


text:
"use strict";

var GrammarError = require("../../grammar-error"),
    asts         = require("../asts"),
    visitor      = require("../visitor");

/*
 * Reports expressions that don't consume any input inside |*| or |+| in the
 * grammar, which prevents infinite loops in the generated parser.
 */
function reportInfiniteLoops(ast) {
  var check = visitor.build({
    zero_or_more: function(node) {
      if (asts.matchesEmpty(ast, node.expression)) {
        throw new GrammarError("Infinite loop detected.", node.location);
      }
    },

    one_or_more: function(node) {
      if (asts.matchesEmpty(ast, node.expression)) {
        throw new GrammarError("Infinite loop detected.", node.location);
      }
    }
  });

  check(ast);
}

module.exports = reportInfiniteLoops;


text:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;

namespace NOBuildTools.ReferenceAnalyzer
{
    /// <summary>
    /// Exception display helper
    /// </summary>
    internal static class ExceptionDisplayer
    {
        /// <summary>
        /// Shows exception as string message box to the user
        /// </summary>
        /// <param name="parent">modal parent</param>
        /// <param name="exception">exception as any</param>
        public static void ShowException(IWin32Window parent, Exception exception)
        {
            string message = "An error is occured." + Environment.NewLine;
            string detailsMessage = "Details: " + Environment.NewLine;

            while (null != exception)
            {
                detailsMessage += "Exception: " + exception.GetType().Name + Environment.NewLine;
                detailsMessage += "Exception: " + exception.Message + Environment.NewLine;

                exception = exception.InnerException;
            }

            MessageBox.Show(parent, message + detailsMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
クラス org.apache.mina.proxy.ProxyAuthException の使用 (Apache MINA Core 2.0.0-RC1 API)
</TITLE>

<META NAME="date" CONTENT="2010-05-29">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      概要
      パッケージ
      クラス
    使用
      階層ツリー
      非推奨 API
      索引
      ヘルプ

 前
 次

  フレームあり
 フレームなし

  すべてのクラス

クラス
org.apache.mina.proxy.ProxyAuthException の使用

ProxyAuthException を使用しているパッケージ

org.apache.mina.proxy

org.apache.mina.proxy.filter

org.apache.mina.proxy.handlers.http

org.apache.mina.proxy.handlers.http.basic

org.apache.mina.proxy.handlers.http.digest

org.apache.mina.proxy.handlers.http.ntlm

org.apache.mina.proxy での ProxyAuthException の使用

ProxyAuthException をスローする org.apache.mina.proxy のメソッド

 void
ProxyLogicHandler.doHandshake(IoFilter.NextFilter nextFilter)

          Called at each step of the handshake procedure.

 void
ProxyLogicHandler.messageReceived(IoFilter.NextFilter nextFilter,
                IoBuffer buf)

          Handle incoming data during the handshake process.

org.apache.mina.proxy.filter での ProxyAuthException の使用

ProxyAuthException をスローする org.apache.mina.proxy.filter のメソッド

 void
ProxyFilter.messageReceived(IoFilter.NextFilter nextFilter,
                IoSession session,
                java.lang.Object message)

          Receives data from the remote host, passes to the handler if a handshake is in progress,
 otherwise passes on transparently.

org.apache.mina.proxy.handlers.http での ProxyAuthException の使用

ProxyAuthException をスローする org.apache.mina.proxy.handlers.http のメソッド

 void
HttpProxyRequest.checkRequiredProperties(java.lang.String... propNames)

          Check if the given property(ies) is(are) set.

 void
HttpSmartProxyHandler.doHandshake(IoFilter.NextFilter nextFilter)

          Performs the handshake processing.

abstract  void
AbstractAuthLogicHandler.doHandshake(IoFilter.NextFilter nextFilter)

          Method called at each step of the handshaking process.

static AbstractAuthLogicHandler
HttpAuthenticationMethods.getNewHandler(int method,
              ProxyIoSession proxyIoSession)

          Creates an AbstractAuthLogicHandler to handle the authentication mechanism.

 AbstractAuthLogicHandler
HttpAuthenticationMethods.getNewHandler(ProxyIoSession proxyIoSession)

          Creates an AbstractAuthLogicHandler to handle the authentication mechanism.

 void
HttpSmartProxyHandler.handleResponse(HttpProxyResponse response)

          Handle a HTTP response from the proxy server.

abstract  void
AbstractHttpLogicHandler.handleResponse(HttpProxyResponse response)

          Handles a HTTP response from the proxy server.

abstract  void
AbstractAuthLogicHandler.handleResponse(HttpProxyResponse response)

          Handles a HTTP response from the proxy server.

 void
AbstractHttpLogicHandler.messageReceived(IoFilter.NextFilter nextFilter,
                IoBuffer buf)

          Handles incoming data during the handshake process.

protected  void
AbstractAuthLogicHandler.writeRequest(IoFilter.NextFilter nextFilter,
             HttpProxyRequest request)

          Sends an HTTP request.

ProxyAuthException をスローする org.apache.mina.proxy.handlers.http のコンストラクタ

AbstractAuthLogicHandler(ProxyIoSession proxyIoSession)

          Instantiates a handler for the given proxy session.

org.apache.mina.proxy.handlers.http.basic での ProxyAuthException の使用

ProxyAuthException をスローする org.apache.mina.proxy.handlers.http.basic のメソッド

 void
HttpNoAuthLogicHandler.doHandshake(IoFilter.NextFilter nextFilter)

          Method called at each step of the handshaking process.

 void
HttpBasicAuthLogicHandler.doHandshake(IoFilter.NextFilter nextFilter)

          Method called at each step of the handshaking process.

 void
HttpNoAuthLogicHandler.handleResponse(HttpProxyResponse response)

          Handles a HTTP response from the proxy server.

 void
HttpBasicAuthLogicHandler.handleResponse(HttpProxyResponse response)

          Handles a HTTP response from the proxy server.

ProxyAuthException をスローする org.apache.mina.proxy.handlers.http.basic のコンストラクタ

HttpBasicAuthLogicHandler(ProxyIoSession proxyIoSession)

HttpNoAuthLogicHandler(ProxyIoSession proxyIoSession)

org.apache.mina.proxy.handlers.http.digest での ProxyAuthException の使用

ProxyAuthException をスローする org.apache.mina.proxy.handlers.http.digest のメソッド

 void
HttpDigestAuthLogicHandler.doHandshake(IoFilter.NextFilter nextFilter)

 void
HttpDigestAuthLogicHandler.handleResponse(HttpProxyResponse response)

ProxyAuthException をスローする org.apache.mina.proxy.handlers.http.digest のコンストラクタ

HttpDigestAuthLogicHandler(ProxyIoSession proxyIoSession)

org.apache.mina.proxy.handlers.http.ntlm での ProxyAuthException の使用

ProxyAuthException をスローする org.apache.mina.proxy.handlers.http.ntlm のメソッド

 void
HttpNTLMAuthLogicHandler.doHandshake(IoFilter.NextFilter nextFilter)

          Method called at each step of the handshaking process.

 void
HttpNTLMAuthLogicHandler.handleResponse(HttpProxyResponse response)

          Handles a HTTP response from the proxy server.

ProxyAuthException をスローする org.apache.mina.proxy.handlers.http.ntlm のコンストラクタ

HttpNTLMAuthLogicHandler(ProxyIoSession proxyIoSession)

      概要
      パッケージ
      クラス
    使用
      階層ツリー
      非推奨 API
      索引
      ヘルプ

 前
 次

  フレームあり
 フレームなし

  すべてのクラス

Copyright © 2004-2010 Apache MINA Project. All Rights Reserved.


text:
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <crush/dbfr.h>
#include <crush/ffutils.h>
#include <crush/general.h>
#include <crush/hashtbl.h>

#include "hashjoin_main.h"

char default_delim[] = {0xfe, 0x00};

static void extract_fields(int *field_list, size_t n_fields,
                           const char *line, char *target, size_t target_sz,
                           const char *ifs, const char *ofs);

static size_t hash_dimension_file(struct cmdargs *args, hashtbl_t *ht);

static void decrement(int *lst, size_t n);

/** @brief Application entry point.
  *
  * @param args contains the parsed cmd-line options & arguments.
  * @param argc number of cmd-line arguments.
  * @param argv list of cmd-line arguments
  * @param optind index of the first non-option cmd-line argument.
  *
  * @return exit status for main() to return.
  */
int hashjoin (struct cmdargs *args, int argc, char *argv[], int optind) {
  hashtbl_t dimension;
  FILE *infile;
  dbfr_t *datareader;

  char *keybuffer = NULL;
  size_t keybuffer_sz = 0;

  char *value, *empty_value;
  size_t n_values, i;

  int *key_fields = NULL;
  size_t n_key_fields = 0;

  if (! args->key_labels &&
      ! (args->data_key_fields && args->dimension_key_fields)) {
    fprintf(stderr, "%s: missing key field argument(s)\n", getenv("_"));
    return EXIT_FAILURE;
  }

  if (! args->dimension_field_labels &&
      ! args->dimension_fields) {
    fprintf(stderr, "%s: missing dimension field argument\n", getenv("_"));
    return EXIT_FAILURE;
  }

  if (! args->delim) {
    args->delim = getenv("DELIMITER");
    if (! args->delim) {
      args->delim = default_delim;
    }
  }
  expand_chars(args->delim);
  if (! args->dimension_delim) {
    args->dimension_delim = args->delim;
  }

  ht_init(&dimension, 1024, NULL, NULL);
  n_values = hash_dimension_file(args, &dimension);

  empty_value = xmalloc(strlen(args->delim) * n_values);
  empty_value[0] = '\0';
  for (i = 0; i < n_values - 1; i++) {
    strcat(empty_value, args->delim);
  }

  if (argc > optind)
    infile = nextfile(argc, argv, &optind, "r");
  else
    infile = stdin;

  if (! args->key_labels) {
    n_key_fields = expand_nums(args->data_key_fields,
                               &key_fields, &n_key_fields);
    decrement(key_fields, n_key_fields);
  }

  while (infile) {
    datareader = dbfr_init(infile);

    if (args->key_labels) {
      n_key_fields = expand_label_list(args->key_labels, datareader->next_line,
                                       args->delim, &key_fields,
                                       &n_key_fields);
      decrement(key_fields, n_key_fields);
    }

    /* Add user-supplied dimension labels to the header row. */
    if (args->dimension_labels && ! args->dimension_field_labels) {
      dbfr_getline(datareader);
      chomp(datareader->current_line);
      printf("%s%s%s\n", datareader->current_line,
             args->delim, args->dimension_labels);
    }

    if (! keybuffer) {
      keybuffer = xmalloc(datareader->next_line_len);
      keybuffer_sz = datareader->next_line_len;
    }

    while (dbfr_getline(datareader) > 0) {
      if (datareader->current_line_len > keybuffer_sz) {
        keybuffer = xrealloc(keybuffer, datareader->current_line_len);
        keybuffer_sz = datareader->current_line_len;
      }
      chomp(datareader->current_line);
      extract_fields(key_fields, n_key_fields, datareader->current_line,
                     keybuffer, keybuffer_sz,
                     args->delim, args->delim);

      value = ht_get(&dimension, keybuffer);
      if (! value)
        value = empty_value;
      printf("%s%s%s\n", datareader->current_line, args->delim, value);
    }

    infile = nextfile(argc, argv, &optind, "r");
  }

  return EXIT_OKAY;
}

/** @brief Extracts a list of fields from a string and stores them in a target
  * buffer.
  *
  * The field separator used in the input string can be different from the
  * output field separator.
  *
  * @param field_list an array of 0-based indexes.
  * @param n_fields the number of elements in field_list.
  * @param line the input string.
  * @param target the output string buffer.
  * @param target_sz the size of target.
  * @param ifs field separator used in line.
  * @param ofs field separator to use in target.
  */
static void extract_fields(int *field_list, size_t n_fields,
                           const char *line, char *target, size_t target_sz,
                           const char *ifs, const char *ofs) {
  int i;
  size_t target_len = 0,
         field_len,
         ofs_len = strlen(ofs);
  target[0] = '\0';

  for (i=0; i < n_fields; i++) {
    field_len = get_line_field(target + target_len, line,
                               target_sz - target_len, field_list[i], ifs);
    if (field_len < 0) {
      /* TODO(jhinds): Maybe do something better than silently treating missing
       * fields as empty. */
      field_len = 0;
    }
    target_len += field_len;
    if (i < n_fields - 1) {
      strncat(target, ofs, target_sz - target_len);
      target_len += ofs_len;
    }
  }
}

static void decrement(int *lst, size_t n) {
  int i;
  for (i=0; i < n; i++)
    lst[i]--;
}

/** @brief Stores key and value fields from a dimension file in a hashtable.
  *
  * @param args commandline options.
  * @param ht the hashtable to hold the data.
  * @param filename the name of the dimension file.
  *
  * @return the number of value fields.  Hackish, but hashjoin() needs to know
  *         and has no other reason to parse the value arguments.
  */
static size_t hash_dimension_file(struct cmdargs *args, hashtbl_t *ht) {
  char *value;
  char *field_buffer = NULL;
  size_t field_buffer_len = 0,
         field_buffer_sz = 0;
  int *key_fields = NULL,
      *val_fields = NULL;
  size_t key_fields_sz = 0,
         val_fields_sz = 0;
  int n_key_fields = 0,
      n_val_fields = 0;
  dbfr_t *dim_file = dbfr_open(args->dimension_file);

  if (! dim_file) {
    warn(args->dimension_file);
    exit(EXIT_FAILURE);
  }

  if (args->key_labels) {
    n_key_fields = expand_label_list(args->key_labels, dim_file->next_line,
                                     args->dimension_delim, &key_fields,
                                     &key_fields_sz);
  } else {
    n_key_fields = expand_nums(args->dimension_key_fields,
                               &key_fields, &key_fields_sz);
  }

  if (n_key_fields <= 0) {
    fprintf(stderr, "%s: error parsing dimension key field list.\n",
            getenv("_"));
    exit(EXIT_FAILURE);
  }

  if (args->dimension_field_labels) {
    n_val_fields = expand_label_list(args->dimension_field_labels,
                                     dim_file->next_line,
                                     args->dimension_delim, &val_fields,
                                     &val_fields_sz);
  } else {
    n_val_fields = expand_nums(args->dimension_fields,
                               &val_fields, &val_fields_sz);
  }

  if (n_val_fields <= 0) {
    fprintf(stderr, "%s: error parsing dimension value field list.\n",
            getenv("_"));
    exit(EXIT_FAILURE);
  }

  decrement(key_fields, n_key_fields);
  decrement(val_fields, n_val_fields);

  field_buffer = xmalloc(dim_file->next_line_len);
  field_buffer_sz = dim_file->next_line_len;

  while (dbfr_getline(dim_file) > 0) {
    if (dim_file->current_line_len > field_buffer_sz) {
      field_buffer = xrealloc(field_buffer, dim_file->current_line_len);
      field_buffer_sz = dim_file->current_line_len;
    }

    extract_fields(val_fields, n_val_fields, dim_file->current_line,
                   field_buffer, field_buffer_sz,
                   args->dimension_delim, args->delim);
    value = xstrdup(field_buffer);

    extract_fields(key_fields, n_key_fields, dim_file->current_line,
                   field_buffer, field_buffer_sz,
                   args->dimension_delim, args->delim);

    ht_put(ht, field_buffer, value);
  }

  dbfr_close(dim_file);
  free(field_buffer);

  return n_val_fields;
}


text:
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office.impl;
import com.wilutions.com.*;

@SuppressWarnings("all")
@CoClass(guid="{C09B9AAA-A463-DB41-5DAE-69E7A5F7FCBC}")
public class Ruler2Impl extends Dispatch implements com.wilutions.mslib.office.Ruler2 {
  @DeclDISPID(1610743808)  public IDispatch getApplication() throws ComException {
    final Object obj = this._dispatchCall(1610743808,"Application", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (IDispatch)obj;
  }
  @DeclDISPID(1610743809)  public Integer getCreator() throws ComException {
    final Object obj = this._dispatchCall(1610743809,"Creator", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (Integer)obj;
  }
  @DeclDISPID(1)  public IDispatch getParent() throws ComException {
    final Object obj = this._dispatchCall(1,"Parent", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return (IDispatch)obj;
  }
  @DeclDISPID(2)  public com.wilutions.mslib.office.RulerLevels2 getLevels() throws ComException {
    final Object obj = this._dispatchCall(2,"Levels", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return Dispatch.as(obj, com.wilutions.mslib.office.impl.RulerLevels2Impl.class);
  }
  @DeclDISPID(3)  public com.wilutions.mslib.office.TabStops2 getTabStops() throws ComException {
    final Object obj = this._dispatchCall(3,"TabStops", DISPATCH_PROPERTYGET,null);
    if (obj == null) return null;
    return Dispatch.as(obj, com.wilutions.mslib.office.impl.TabStops2Impl.class);
  }
  public Ruler2Impl(String progId) throws ComException {
    super(progId, "{000C03C1-0000-0000-C000-000000000046}");
  }
  protected Ruler2Impl(long ndisp) {
    super(ndisp);
  }
  public String toString() {
    return "[Ruler2Impl" + super.toString() + "]";
  }
}


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>XPC Demo</title>

<input type="text" id="txt" size="20" /><input id="send" type="button" value="发送" />


text:
#import "CloudPlugsRequest.h"

@implementation CloudPlugsRequest{
    NSURLConnection* urlConnection;
}

@synthesize httpMethod;
@synthesize path;
@synthesize headers;
@synthesize query;
@synthesize body;

-(id) initWithNSURLConnection:(NSURLConnection*) c
{
    self = [super init];
    if(self){
        urlConnection = c;
    }
    return self;
}
-(void) cancel
{
    [urlConnection cancel];
}
@end


text:
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container"
    android:background="@android:color/white">

    <android.support.design.widget.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/app_bar"
        android:fitsSystemWindows="true">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            android:transitionName="@string/toolbar"
            app:layout_scrollFlags="scroll">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="?attr/actionBarSize">
                <ImageView
                    android:layout_width="75dp"
                    android:layout_height="100dp"
                    android:layout_alignParentRight="true"
                    android:layout_marginRight="16dp"
                    android:layout_alignBottom="@+id/headline"
                    android:src="@drawable/droidcon_windmolen"
                    android:alpha="0.2"
                    />
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="24sp"
                    android:paddingTop="16dp"
                    android:paddingRight="16dp"
                    android:paddingBottom="16dp"
                    android:transitionName="@string/headline"
                    android:textColor="@color/textColorPrimary"
                    android:id="@+id/headline"/>
            </RelativeLayout>
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_below="@+id/toolbar">
        <RelativeLayout android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="16dp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/text"
                android:layout_below="@+id/dascription"
                android:layout_marginBottom="16dp"
                android:lineSpacingExtra="2dp"
                android:paddingBottom="16dp"
                android:textSize="14sp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/date"
                android:layout_marginTop="8dp"
                android:textSize="14sp"
                android:textStyle="bold"
                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/location"
                android:layout_toRightOf="@+id/date"
                android:layout_marginTop="8dp"
                android:textSize="14sp"
                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/dascription"
                android:text="@string/text_title"
                android:layout_below="@+id/location"
                android:layout_marginTop="8dp"
                android:textSize="20sp"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/speaker_title"
                android:text="@string/speaker_title"
                android:layout_below="@+id/text"
                android:layout_marginTop="8dp"
                android:textSize="20sp"/>

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:transitionName="@string/image"
                android:layout_below="@+id/speaker_title"
                android:layout_marginTop="8dp"
                android:id="@+id/image"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:textSize="14sp"
                android:gravity="center_vertical"
                android:layout_below="@+id/speaker_title"
                android:layout_marginTop="8dp"
                android:layout_marginLeft="56dp"
                android:layout_marginStart="56dp"
                android:layout_marginBottom="16dp"
                android:transitionName="@string/speaker"
                android:id="@+id/speaker"/>

        </RelativeLayout>
    </android.support.v4.widget.NestedScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="16dp"
        android:layout_marginEnd="16dp"
        app:fabSize="mini"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|right"/>

</android.support.design.widget.CoordinatorLayout>


text:
// -----------------------------------------------------------------------
//  <copyright file="OrganizationInputDto.cs" company="OSharp开源团队">
//      Copyright (c) 2014-2015 OSharp. All rights reserved.
//  </copyright>
//  <site>http://www.osharp.org</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2015-10-14 3:38</last-date>
// -----------------------------------------------------------------------

using System.ComponentModel.DataAnnotations;

using OSharp.Core.Data;

namespace OSharp.Demo.Dtos.Identity
{
    public class OrganizationInputDto : IInputDto<int>
    {
        [Required, StringLength(50)]
        public string Name { get; set; }

        [StringLength(500)]
        public string Remark { get; set; }

        [Range(0, 999)]
        public int SortCode { get; set; }

        public int? ParentId { get; set; }

        /// <summary>
        /// 获取或设置 主键,唯一标识
        /// </summary>
        public int Id { get; set; }
    }
}


text:
@implementation NSMutableArray (OAAdditions)

- (id)removeRandomObject {
	NSUInteger count = [self count];
	if (count) {
		NSUInteger index = arc4random() % count;
		id object = [self objectAtIndex:index];
		[self removeObjectAtIndex:index];
		return object;
	} else {
		return nil;
	}
}

@end


text:
url: bar
status: draft
foo: bar


text:
var Promise = require('promise');

module.exports = function() {
  module.exports.prototype.deleteCount = 0;
  module.exports.prototype.messageCount = 0;

  module.exports.prototype.exec = function(sqs, queueUrl, ids) {
    var self = this;
    return groupBy10(ids).map(function(batch) {
      return new Promise(function(resolve, reject) {
        var params = makeParams(queueUrl, batch);
        self.deleteCount++;
        sqs.deleteMessageBatch(params, function(err, data) {
          if (err) {
            console.warn(err, err.stack);
            reject(err);
          } else {
            self.messageCount += data.Successful.length;
            if (data.Failed.length > 0) {
              console.warn(data.Failed);
              reject(data.Failed);
            } else {
              resolve(data.Successful);
            }
          }
        });
      });
    });
  };
};

function groupBy10(ids) {
  var ret = [];
  var origin = ids.slice();
  while (origin.length > 0) {
    ret.push(origin.splice(0, 10));
  }
  return ret;
}

function makeParams(queueUrl, ids) {
  return {
    Entries: ids,
    QueueUrl: queueUrl
  };
}


text: SUnit tests for the size of objects in memory


text:
#include "modules/perception/obstacle/common/file_system_util.h"

#include "gtest/gtest.h"
#include "modules/common/log.h"

namespace apollo {
namespace perception {

TEST(FileSystemUtilTest, GetFileNamesInFolderById) {
  std::string data_path = "modules/perception/data/hm_tracker_test/";
  std::vector<std::string> seg_filenames;
  GetFileNamesInFolderById(data_path, ".seg", &seg_filenames);
  std::vector<std::string> pose_filenames;
  GetFileNamesInFolderById(data_path, ".pose", &pose_filenames);
  EXPECT_EQ(seg_filenames.size(), 8);
  EXPECT_EQ(pose_filenames.size(), 8);
}

}  // namespace perception
}  // namespace apollo


text:
package ch.heigvd.amt.ats.gamification.dao.entities;

public class AppsId {
    String apiKey;

    public AppsId(String apiKey) {
        this.apiKey = apiKey;
    }
}


text:
class AuthController < ApplicationController

  def signup
    @user = User.create auth_params
    render json: { token: Token.encode(@user.id) }
  end

  def login
    @user = User.find_by email: params[:email] if params[:email].present?

    if @user && @user.authenticate(params[:password])
      render json: { token: Token.encode(@user.id) }
    else
      render json: { message: 'Invalid credentials' }, status: :unauthorized
    end
  end

  def authenticate
    @oauth = "Oauth::#{params['provider'].titleize}".constantize.new(params)
    if @oauth.authorized?
      @user = User.from_auth(@oauth.formatted_user_data, current_user)
      if @user
        render_success(token: @oauth.access_token, authentication_token: @user.authentication_token, id: @user.id)
      else
        render_error "This #{params[:provider]} account is used already"
      end
    else
      render_error("There was an error with #{params['provider']}. please try again.")
    end
  end

  # Twitter don't support auth2 protocol yet, so it has it's own implementation for now
  def twitter
    if params[:oauth_token].blank?
      render_success({ oauth_token: twitter_oauth.request_token })
    else
      render_success({ token: twitter_oauth.access_token })
    end
  end

  def twitter_step_2
    if twitter_oauth.authorized?
      if User.from_auth(twitter_oauth.formatted_account_info, current_user)
        render_success("connected twitter to profile successfuly")
      else
        render_error "This twitter account is used already"
      end
    else
      render_error("There was an error with twitter. please try again.")
    end
  end

  private

    def twitter_oauth
      @oauth ||= Oauth::Twitter.new(params)
    end

    def auth_params
      params.require(:auth).permit(:email, :password, :displayName)
    end

end


text: <i class="js-edit-button editor__icons icon-edit fa fa-edit"></i>


text:
namespace nano
{
class wallet_value
{
public:
	wallet_value () = default;
	wallet_value (nano::db_val<MDB_val> const &);
	wallet_value (nano::uint256_union const &, uint64_t);
	nano::db_val<MDB_val> val () const;
	nano::uint256_union key;
	uint64_t work;
};
}


text:
! PR fortran/27916
! Test whether allocatable privatized arrays has "not currently allocated"
! status at the start of OpenMP constructs.
! { dg-do run }

program pr27916
  integer :: n, i
  logical :: r
  integer, dimension(:), allocatable :: a

  r = .false.
!$omp parallel do num_threads (4) default (private) &
!$omp & reduction (.or.: r) schedule (static)
  do n = 1, 16
    r = r .or. allocated (a)
    allocate (a (16))
    r = r .or. .not. allocated (a)
    do i = 1, 16
      a (i) = i
    end do
    deallocate (a)
    r = r .or. allocated (a)
  end do
 !$omp end parallel do
  if (r) call abort
end program pr27916


text:
QUnit.module('Compound Path');

test('moveTo / lineTo', function() {
    var path = new CompoundPath();

    var lists = [
        [new Point(279, 151), new Point(149, 151), new Point(149, 281), new Point(279, 281)],
        [new Point(319, 321), new Point(109, 321), new Point(109, 111), new Point(319, 111)]
    ];

    for (var i = 0; i < lists.length; i++) {
        var list = lists[i];
        for (var j = 0; j < list.length; j++) {
            path[j === 0 ? 'moveTo' : 'lineTo'](list[j]);
        }
    }

    path.fillColor = 'black';

    equals(function() {
        return path.children.length;
    }, 2);
});

test('clockwise', function() {
    var path1 = new Path.Rectangle([200, 200], [100, 100]);
    var path2 = new Path.Rectangle([50, 50], [200, 200]);
    var path3 = new Path.Rectangle([0, 0], [400, 400]);

    equals(function() {
        return path1.clockwise;
    }, true);
    equals(function() {
        return path2.clockwise;
    }, true);
    equals(function() {
        return path3.clockwise;
    }, true);

    var compound = new CompoundPath(path1, path2, path3);

    equals(function() {
        return compound.lastChild == path3;
    }, true);
    equals(function() {
        return compound.firstChild == path1;
    }, true);
    equals(function() {
        return path1.clockwise;
    }, true);
    equals(function() {
        return path2.clockwise;
    }, false);
    equals(function() {
        return path3.clockwise;
    }, false);
});

test('Cloning with non-standard clockwise settings', function() {
    var path1 = new Path.Rectangle([200, 200], [100, 100]);
    var path2 = new Path.Rectangle([50, 50], [200, 200]);
    var path3 = new Path.Rectangle([0, 0], [400, 400]);
    path1.clockwise = false;
    path2.clockwise = true;
    path3.clockwise = true;
    var compound = new CompoundPath(path1, path2, path3);
    equals(function() {
        return path1.clockwise;
    }, false);
    equals(function() {
        return path2.clockwise;
    }, true);
    equals(function() {
        return path3.clockwise;
    }, true);
});