text:
package com.intellij.refactoring.changeSignature;

import com.intellij.lang.Language;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.refactoring.util.CanonicalTypes;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

import static com.intellij.refactoring.changeSignature.ChangeSignatureUtil.deepTypeEqual;

/**
 * @author Jeka
 * @since Sep 17, 2001
 */
public class JavaChangeInfoImpl extends UserDataHolderBase implements JavaChangeInfo {
  private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.changeSignature.JavaChangeInfoImpl");

  @PsiModifier.ModifierConstant final String newVisibility;
  private PsiMethod method;
  String oldName;
  final String oldType;
  String[] oldParameterNames;
  String[] oldParameterTypes;
  final String newName;
  final CanonicalTypes.Type newReturnType;
  final ParameterInfoImpl[] newParms;
  ThrownExceptionInfo[] newExceptions;
  final boolean[] toRemoveParm;
  boolean isVisibilityChanged;
  boolean isNameChanged;
  boolean isReturnTypeChanged;
  boolean isParameterSetOrOrderChanged;
  boolean isExceptionSetChanged;
  boolean isExceptionSetOrOrderChanged;
  boolean isParameterNamesChanged;
  boolean isParameterTypesChanged;
  boolean isPropagationEnabled = true;
  final boolean wasVararg;
  final boolean retainsVarargs;
  final boolean obtainsVarags;
  final boolean arrayToVarargs;
  PsiIdentifier newNameIdentifier;
  final PsiExpression[] defaultValues;

  final boolean isGenerateDelegate;
  final Set<PsiMethod> propagateParametersMethods;
  final Set<PsiMethod> propagateExceptionsMethods;

  private boolean myCheckUnusedParameter = false;

  /**
   * @param newExceptions null if not changed
   */
  public JavaChangeInfoImpl(@PsiModifier.ModifierConstant String newVisibility,
                    PsiMethod method,
                    String newName,
                    CanonicalTypes.Type newType,
                    @NotNull ParameterInfoImpl[] newParms,
                    ThrownExceptionInfo[] newExceptions,
                    boolean generateDelegate,
                    Set<PsiMethod> propagateParametersMethods,
                    Set<PsiMethod> propagateExceptionsMethods) {
    this(newVisibility, method, newName, newType, newParms, newExceptions, generateDelegate, propagateParametersMethods,
         propagateExceptionsMethods, method.getName());
  }

  /**
   * @param newExceptions null if not changed
   * @param oldName
   */
  public JavaChangeInfoImpl(@PsiModifier.ModifierConstant String newVisibility,
                            PsiMethod method,
                            String newName,
                            CanonicalTypes.Type newType,
                            @NotNull ParameterInfoImpl[] newParms,
                            ThrownExceptionInfo[] newExceptions,
                            boolean generateDelegate,
                            Set<PsiMethod> propagateParametersMethods,
                            Set<PsiMethod> propagateExceptionsMethods,
                            String oldName) {
    PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();

    this.newVisibility = newVisibility;
    this.method = method;
    this.newName = newName;
    newReturnType = newType;
    this.newParms = newParms;
    wasVararg = method.isVarArgs();

    this.isGenerateDelegate = generateDelegate;
    this.propagateExceptionsMethods = propagateExceptionsMethods;
    this.propagateParametersMethods = propagateParametersMethods;

    this.oldName = oldName;

    if (!method.isConstructor()){
      PsiType type = method.getReturnType();
      assert type != null : method;
      oldType = factory.createTypeElement(type).getText();
    }
    else{
      oldType = null;
    }

    fillOldParams(method);

    isVisibilityChanged = !method.hasModifierProperty(newVisibility);

    isNameChanged = !newName.equals(this.oldName);

    if (oldParameterNames.length != newParms.length){
      isParameterSetOrOrderChanged = true;
    }
    else {
      for(int i = 0; i < newParms.length; i++){
        ParameterInfoImpl parmInfo = newParms[i];

        if (i != parmInfo.oldParameterIndex){
          isParameterSetOrOrderChanged = true;
          break;
        }
        if (!parmInfo.getName().equals(oldParameterNames[i])){
          isParameterNamesChanged = true;
        }
        try {
          if (!parmInfo.getTypeText().equals(oldParameterTypes[i])){
            isParameterTypesChanged = true;
          }
        }
        catch (IncorrectOperationException e) {
          isParameterTypesChanged = true;
        }
      }
    }

    setupPropagationEnabled(method.getParameterList().getParameters(), newParms);

    setupExceptions(newExceptions, method);

    toRemoveParm = new boolean[oldParameterNames.length];
    Arrays.fill(toRemoveParm, true);
    for (ParameterInfoImpl info : newParms) {
      if (info.oldParameterIndex < 0) continue;
      toRemoveParm[info.oldParameterIndex] = false;
    }

    defaultValues = new PsiExpression[newParms.length];
    for(int i = 0; i < newParms.length; i++){
      ParameterInfoImpl info = newParms[i];
      if (info.oldParameterIndex < 0 && !info.isVarargType()){
        if (StringUtil.isEmpty(info.defaultValue)) continue;
        try{
          defaultValues[i] = factory.createExpressionFromText(info.defaultValue, method);
        }
        catch(IncorrectOperationException e){
          LOG.info(e);
        }
      }
    }

    if (this.newParms.length == 0) {
      retainsVarargs = false;
      obtainsVarags = false;
      arrayToVarargs = false;
    }
    else {
      final ParameterInfoImpl lastNewParm = this.newParms[this.newParms.length - 1];
      obtainsVarags = lastNewParm.isVarargType();
      retainsVarargs = lastNewParm.oldParameterIndex >= 0 && obtainsVarags;
      if (retainsVarargs) {
        arrayToVarargs = oldParameterTypes[lastNewParm.oldParameterIndex].endsWith("[]");
      }
      else {
        arrayToVarargs = false;
      }
    }

    if (isNameChanged) {
      newNameIdentifier = factory.createIdentifier(newName);
    }
  }

  @Override
  public boolean checkUnusedParameter() {
    return myCheckUnusedParameter;
  }

  public void setCheckUnusedParameter() {
    myCheckUnusedParameter = true;
  }

  protected void fillOldParams(PsiMethod method) {
    PsiParameter[] parameters = method.getParameterList().getParameters();
    oldParameterNames = new String[parameters.length];
    oldParameterTypes = new String[parameters.length];

    PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
    for (int i = 0; i < parameters.length; i++) {
      PsiParameter parameter = parameters[i];
      oldParameterNames[i] = parameter.getName();
      oldParameterTypes[i] = factory.createTypeElement(parameter.getType()).getText();
    }
    if (!method.isConstructor()){
      try {
        isReturnTypeChanged = !deepTypeEqual(newReturnType.getType(this.method), this.method.getReturnType());
      }
      catch (IncorrectOperationException e) {
        isReturnTypeChanged = true;
      }
    }
  }

  @NotNull
  public JavaParameterInfo[] getNewParameters() {
    return newParms;
  }

  @PsiModifier.ModifierConstant
  public String getNewVisibility() {
    return newVisibility;
  }

  public boolean isParameterSetOrOrderChanged() {
    return isParameterSetOrOrderChanged;
  }

  private void setupExceptions(ThrownExceptionInfo[] newExceptions, final PsiMethod method) {
    if (newExceptions == null) {
      newExceptions = JavaThrownExceptionInfo.extractExceptions(method);
    }

    this.newExceptions = newExceptions;

    PsiClassType[] types = method.getThrowsList().getReferencedTypes();
    isExceptionSetChanged = newExceptions.length != types.length;
    if (!isExceptionSetChanged) {
      for (int i = 0; i < newExceptions.length; i++) {
        try {
          if (newExceptions[i].getOldIndex() < 0 || !deepTypeEqual(types[i], newExceptions[i].createType(method, method.getManager()))) {
            isExceptionSetChanged = true;
            break;
          }
        }
        catch (IncorrectOperationException e) {
          isExceptionSetChanged = true;
        }
        if (newExceptions[i].getOldIndex() != i) isExceptionSetOrOrderChanged = true;
      }
    }

    isExceptionSetOrOrderChanged |= isExceptionSetChanged;
  }

  protected void setupPropagationEnabled(final PsiParameter[] parameters, final ParameterInfoImpl[] newParms) {
    if (parameters.length >= newParms.length) {
      isPropagationEnabled = false;
    }
    else {
      isPropagationEnabled = !propagateParametersMethods.isEmpty();
      for (int i = 0; i < parameters.length; i++) {
        final ParameterInfoImpl newParm = newParms[i];
        if (newParm.oldParameterIndex != i) {
          isPropagationEnabled = false;
          break;
        }
      }
    }
  }

  public PsiMethod getMethod() {
    return method;
  }

  public CanonicalTypes.Type getNewReturnType() {
    return newReturnType;
  }

  public void updateMethod(PsiMethod method) {
    this.method = method;
  }

  @Override
  public Collection<PsiMethod> getMethodsToPropagateParameters() {
    return propagateParametersMethods;
  }

  public ParameterInfoImpl[] getCreatedParmsInfoWithoutVarargs() {
    List<ParameterInfoImpl> result = new ArrayList<>();
    for (ParameterInfoImpl newParm : newParms) {
      if (newParm.oldParameterIndex < 0 && !newParm.isVarargType()) {
        result.add(newParm);
      }
    }
    return result.toArray(new ParameterInfoImpl[result.size()]);
  }

  @Nullable
  public PsiExpression getValue(int i, PsiCallExpression expr) throws IncorrectOperationException {
    if (defaultValues[i] != null) return defaultValues[i];
    final PsiElement valueAtCallSite = newParms[i].getActualValue(expr, PsiSubstitutor.EMPTY);
    return valueAtCallSite instanceof PsiExpression ? (PsiExpression)valueAtCallSite : null;
  }

  public boolean isVisibilityChanged() {
    return isVisibilityChanged;
  }

  public boolean isNameChanged() {
    return isNameChanged;
  }

  public boolean isReturnTypeChanged() {
    return isReturnTypeChanged;
  }

  public String getNewName() {
    return newName;
  }

  public Language getLanguage() {
    return JavaLanguage.INSTANCE;
  }

  public boolean isExceptionSetChanged() {
    return isExceptionSetChanged;
  }

  public boolean isExceptionSetOrOrderChanged() {
    return isExceptionSetOrOrderChanged;
  }

  public boolean isParameterNamesChanged() {
    return isParameterNamesChanged;
  }

  public boolean isParameterTypesChanged() {
    return isParameterTypesChanged;
  }

  public boolean isGenerateDelegate() {
    return isGenerateDelegate;
  }

  @NotNull
  public String[] getOldParameterNames() {
    return oldParameterNames;
  }

  @NotNull
  public String[] getOldParameterTypes() {
    return oldParameterTypes;
  }

  public ThrownExceptionInfo[] getNewExceptions() {
    return newExceptions;
  }

  public boolean isRetainsVarargs() {
    return retainsVarargs;
  }

  public boolean isObtainsVarags() {
    return obtainsVarags;
  }

  public boolean isArrayToVarargs() {
    return arrayToVarargs;
  }

  public PsiIdentifier getNewNameIdentifier() {
    return newNameIdentifier;
  }

  public String getOldName() {
    return oldName;
  }

  public boolean wasVararg() {
    return wasVararg;
  }

  public boolean[] toRemoveParm() {
    return toRemoveParm;
  }

  protected boolean checkMethodEquality() {
    return true;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof JavaChangeInfoImpl)) return false;

    JavaChangeInfoImpl that = (JavaChangeInfoImpl)o;

    if (arrayToVarargs != that.arrayToVarargs) return false;
    if (isExceptionSetChanged != that.isExceptionSetChanged) return false;
    if (isExceptionSetOrOrderChanged != that.isExceptionSetOrOrderChanged) return false;
    if (isGenerateDelegate != that.isGenerateDelegate) return false;
    if (isNameChanged != that.isNameChanged) return false;
    if (isParameterNamesChanged != that.isParameterNamesChanged) return false;
    if (isParameterSetOrOrderChanged != that.isParameterSetOrOrderChanged) return false;
    if (isParameterTypesChanged != that.isParameterTypesChanged) return false;
    if (isPropagationEnabled != that.isPropagationEnabled) return false;
    if (isReturnTypeChanged != that.isReturnTypeChanged) return false;
    if (isVisibilityChanged != that.isVisibilityChanged) return false;
    if (obtainsVarags != that.obtainsVarags) return false;
    if (retainsVarargs != that.retainsVarargs) return false;
    if (wasVararg != that.wasVararg) return false;
    if (!Arrays.equals(defaultValues, that.defaultValues)) return false;
    if (checkMethodEquality() && !method.equals(that.method)) return false;
    if (!Arrays.equals(newExceptions, that.newExceptions)) return false;
    if (!newName.equals(that.newName)) return false;
    if (newNameIdentifier != null ? !newNameIdentifier.equals(that.newNameIdentifier) : that.newNameIdentifier != null) return false;
    if (!Arrays.equals(newParms, that.newParms)) return false;
    if (newReturnType != null
        ? that.newReturnType == null || !Comparing.strEqual(newReturnType.getTypeText(), that.newReturnType.getTypeText())
        : that.newReturnType != null) {
      return false;
    }
    if (newVisibility != null ? !newVisibility.equals(that.newVisibility) : that.newVisibility != null) return false;
    if (!oldName.equals(that.oldName)) return false;
    if (!Arrays.equals(oldParameterNames, that.oldParameterNames)) return false;
    if (!Arrays.equals(oldParameterTypes, that.oldParameterTypes)) return false;
    if (oldType != null ? !oldType.equals(that.oldType) : that.oldType != null) return false;
    if (!propagateExceptionsMethods.equals(that.propagateExceptionsMethods)) return false;
    if (!propagateParametersMethods.equals(that.propagateParametersMethods)) return false;
    if (!Arrays.equals(toRemoveParm, that.toRemoveParm)) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = newVisibility != null ? newVisibility.hashCode() : 0;
    if (checkMethodEquality()) {
      result = 31 * result + method.hashCode();
    }
    result = 31 * result + oldName.hashCode();
    result = 31 * result + (oldType != null ? oldType.hashCode() : 0);
    result = 31 * result + Arrays.hashCode(oldParameterNames);
    result = 31 * result + Arrays.hashCode(oldParameterTypes);
    result = 31 * result + newName.hashCode();
    result = 31 * result + (newReturnType != null ? newReturnType.getTypeText().hashCode() : 0);
    result = 31 * result + Arrays.hashCode(newParms);
    result = 31 * result + Arrays.hashCode(newExceptions);
    result = 31 * result + Arrays.hashCode(toRemoveParm);
    result = 31 * result + (isVisibilityChanged ? 1 : 0);
    result = 31 * result + (isNameChanged ? 1 : 0);
    result = 31 * result + (isReturnTypeChanged ? 1 : 0);
    result = 31 * result + (isParameterSetOrOrderChanged ? 1 : 0);
    result = 31 * result + (isExceptionSetChanged ? 1 : 0);
    result = 31 * result + (isExceptionSetOrOrderChanged ? 1 : 0);
    result = 31 * result + (isParameterNamesChanged ? 1 : 0);
    result = 31 * result + (isParameterTypesChanged ? 1 : 0);
    result = 31 * result + (isPropagationEnabled ? 1 : 0);
    result = 31 * result + (wasVararg ? 1 : 0);
    result = 31 * result + (retainsVarargs ? 1 : 0);
    result = 31 * result + (obtainsVarags ? 1 : 0);
    result = 31 * result + (arrayToVarargs ? 1 : 0);
    result = 31 * result + (newNameIdentifier != null ? newNameIdentifier.hashCode() : 0);
    result = 31 * result + (defaultValues != null ? Arrays.hashCode(defaultValues) : 0);
    result = 31 * result + (isGenerateDelegate ? 1 : 0);
    result = 31 * result + propagateParametersMethods.hashCode();
    result = 31 * result + propagateExceptionsMethods.hashCode();
    return result;
  }
}


text:
module restore my_default

source /home/ekoch/.bashrc
source /home/ekoch/preload.bash

job_num=$SLURM_ARRAY_TASK_ID

# Build in a slight offset for each job to avoid starting a bunch of CASA
# sessions at once
# sleep $(($job_num + 30))

# Move to scratch space b/c casa write out the temporary files into the same folder
export scratch_path=/home/ekoch/scratch/17B-162_imaging/

export channel_folder_name=HI_nocontsub_0_42kms

cd $scratch_path

Xvfb :1 &
export DISPLAY=:1

# Set which imaging stage to run: the initial 5-sigma clean (1) or the full clean with a mask to (2)
stage=1

if (( $stage==1 )); then
    script_name="${HOME}/code/VLA_Lband/17B-162/HI/imaging/HI_single_channel_clean.py"
    # Parameter file for tclean
    param_file="/home/ekoch/code/VLA_Lband/17B-162/HI/imaging/param_files/14B_17B_04kms_nocontsub.saved"

    # Start 4 channels running on the node
    # This is well-suited for the cedar base nodes
    start_chan=$(($job_num * 4))
    end_chan=$((($job_num + 1) * 4))

elif (( $stage==2 )); then
    script_name="${HOME}/code/VLA_Lband/17B-162/HI/imaging/HI_single_channel_clean_stage2.py"
    param_file="/home/ekoch/code/VLA_Lband/17B-162/HI/imaging/param_files/14B_17B_04kms_nocontsub_stage2.saved"

    # Start 8 channels running on the node
    # cleaning takes most of the time but uses fewer CPUs
    # overload cpu usage
    # This is well-suited for the cedar base nodes
    start_chan=$(($job_num * 8))
    end_chan=$((($job_num + 1) * 8))

else
    echo "Stage must be 1 or 2, not ${stage}".
    exit 1
fi

# Path to the casa files
export casa_scratch_path="$HOME/scratch/casa-release-5.4.1-32.el7"

# B/c CASA spawns other processes internally, and if something crashes in the scripts,
# the wait command may hang until the job is killed
# Try recording the casa interpreter PIDs and only make wait subject to those.
pids=

for (( chan_num = $start_chan; chan_num < $end_chan; chan_num++ )); do

    echo "Running channel "$chan_num

    # Make a new directory on the node storage
    tmp_dir=$SLURM_TMPDIR/run_chan_${chan_num}
    mkdir $tmp_dir

    cd $tmp_dir

    # Move the data to the temp path
    mkdir ${channel_folder_name}
    mkdir ${channel_folder_name}/channel_${chan_num}
    cp -r $scratch_path/${channel_folder_name}/channel_${chan_num}/* ${channel_folder_name}/channel_${chan_num}/

    # Copy a new casa instance to avoid slower i/o on scratch or in home
    cp -r $casa_scratch_path .

    # Copy the init file
    mkdir .casa
    cp $HOME/.casa/init.py .casa/

    rc_path="${tmp_dir}/.casa"

    (casa-release-5.4.1-32.el7/bin/mpicasa -n 8 casa-release-5.4.1-32.el7/bin/casa --rcdir ${rc_path} --nologger --nogui --logfile $scratch_path/${channel_folder_name}/casa_M33_HI_14B_17B_042kms_nocontsub_${chan_num}_${SLURM_JOB_ID}_$(date "+%Y%m%d-%H%M%S")_stage${stage}.log --nocrashreport -c $script_name $chan_num $param_file "${channel_folder_name}"; cp -r ${channel_folder_name}/channel_${chan_num}/* $scratch_path/${channel_folder_name}/channel_${chan_num}/) &
    pids+=" $!"

    cd $tmp_dir

    # Avoid starting up multiple CASA sessions at once. Runs into ipython database issues.
    sleep 10

done

wait $pids || { echo "There was an error" >&2; exit 1; }

echo "All CASA jobs exited."

redpajama_set_name: RedPajamaGithub


text:
package storage

import (
	"fmt"
	"os"
	"time"

	"github.com/chrislusf/seaweedfs/weed/glog"
)

func loadVolumeWithoutIndex(dirname string, collection string, id VolumeId, needleMapKind NeedleMapType) (v *Volume, e error) {
	v = &Volume{dir: dirname, Collection: collection, Id: id}
	v.SuperBlock = SuperBlock{}
	v.needleMapKind = needleMapKind
	e = v.load(false, false, needleMapKind, 0)
	return
}

func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind NeedleMapType, preallocate int64) error {
	var e error
	fileName := v.FileName()

	if exists, canRead, canWrite, modifiedTime := checkFile(fileName + ".dat"); exists {
		if !canRead {
			return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
		}
		if canWrite {
			v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
			v.lastModifiedTime = uint64(modifiedTime.Unix())
		} else {
			glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
			v.dataFile, e = os.Open(fileName + ".dat")
			v.readOnly = true
		}
	} else {
		if createDatIfMissing {
			v.dataFile, e = createVolumeFile(fileName+".dat", preallocate)
		} else {
			return fmt.Errorf("Volume Data file %s.dat does not exist.", fileName)
		}
	}

	if e != nil {
		if !os.IsPermission(e) {
			return fmt.Errorf("cannot load Volume Data %s.dat: %v", fileName, e)
		}
	}

	if v.ReplicaPlacement == nil {
		e = v.readSuperBlock()
	} else {
		e = v.maybeWriteSuperBlock()
	}
	if e == nil && alsoLoadIndex {
		var indexFile *os.File
		if v.readOnly {
			glog.V(1).Infoln("open to read file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
				return fmt.Errorf("cannot read Volume Index %s.idx: %v", fileName, e)
			}
		} else {
			glog.V(1).Infoln("open to write file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
				return fmt.Errorf("cannot write Volume Index %s.idx: %v", fileName, e)
			}
		}
		if e = CheckVolumeDataIntegrity(v, indexFile); e != nil {
			v.readOnly = true
			glog.V(0).Infof("volumeDataIntegrityChecking failed %v", e)
		}
		switch needleMapKind {
		case NeedleMapInMemory:
			glog.V(0).Infoln("loading index", fileName+".idx", "to memory readonly", v.readOnly)
			if v.nm, e = LoadCompactNeedleMap(indexFile); e != nil {
				glog.V(0).Infof("loading index %s to memory error: %v", fileName+".idx", e)
			}
		case NeedleMapLevelDb:
			glog.V(0).Infoln("loading leveldb", fileName+".ldb")
			if v.nm, e = NewLevelDbNeedleMap(fileName+".ldb", indexFile); e != nil {
				glog.V(0).Infof("loading leveldb %s error: %v", fileName+".ldb", e)
			}
		case NeedleMapBoltDb:
			glog.V(0).Infoln("loading boltdb", fileName+".bdb")
			if v.nm, e = NewBoltDbNeedleMap(fileName+".bdb", indexFile); e != nil {
				glog.V(0).Infof("loading boltdb %s error: %v", fileName+".bdb", e)
			}
		case NeedleMapBtree:
			glog.V(0).Infoln("loading index", fileName+".idx", "to btree readonly", v.readOnly)
			if v.nm, e = LoadBtreeNeedleMap(indexFile); e != nil {
				glog.V(0).Infof("loading index %s to btree error: %v", fileName+".idx", e)
			}
		}
	}

	return e
}

func checkFile(filename string) (exists, canRead, canWrite bool, modTime time.Time) {
	exists = true
	fi, err := os.Stat(filename)
	if os.IsNotExist(err) {
		exists = false
		return
	}
	if fi.Mode()&0400 != 0 {
		canRead = true
	}
	if fi.Mode()&0200 != 0 {
		canWrite = true
	}
	modTime = fi.ModTime()
	return
}


text:
<?php

namespace DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRStructureDefinition;

use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement\FHIRStructureDefinition\FHIRStructureDefinitionDifferential;

/**
 * Class FHIRStructureDefinitionDifferentialTest
 * @package \DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRStructureDefinition
 */
class FHIRStructureDefinitionDifferentialTest extends TestCase
{
    public function testCanConstructTypeNoArgs()
    {
        $type = new FHIRStructureDefinitionDifferential();
        $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRBackboneElement\FHIRStructureDefinition\FHIRStructureDefinitionDifferential', $type);
    }
}


text: export * from './rectangle.component';


text:
FROM busybox
COPY hello.txt hello.txt
CMD cat hello.txt


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace NodeEditor
{
    /// <summary>
    /// Class that represents output/input type of execution path.
    /// </summary>
    [Serializable]
    public class ExecutionPath : ISerializable
    {
        public bool IsSignaled { get; internal set; }

        public void Signal()
        {
            IsSignaled = true;
        }

        public ExecutionPath()
        {

        }

        private ExecutionPath(SerializationInfo info, StreamingContext ctx)
        {

        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {

        }
    }
}


text:
using namespace boost;

// Check to make you can apply a vertex filter with the
// make_filtered_graph function, to fix bug #480175.

struct NotMuchOfAFilter
{
    template<class Vertex> bool operator()(Vertex key)
    const { return true; }
};

int main()
{
    adjacency_list<> graph;
    make_filtered_graph(graph, keep_all(), NotMuchOfAFilter());
}


text:
<?php
/**
 * Helper para formatear en json paginador
 *
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 * @author Ing. Eduardo Ortiz
 *
 */
namespace Adteam\Core\Admin\Checkout;

use Doctrine\ORM\EntityManager;
use Zend\ServiceManager\ServiceManager;
use Adteam\Core\Admin\Checkout\Entity\CoreOrders;
use Adteam\Core\Admin\Checkout\Entity\OauthUsers;
use Adteam\Core\Admin\Checkout\Entity\CoreProducts;
use Adteam\Core\Admin\Checkout\Entity\CoreUserTransactions;
use Adteam\Core\Admin\Checkout\Validator;
use Adteam\Core\Common\ViewHelper;
class Checkout
{
    /**
     *
     * @var type
     */
    protected $service;

    /**
     *
     * @var type
     */
    protected $identity;

    /**
     *
     * @var type
     */
    protected $em;

    protected  $url;
    /**
     *
     * @param ServiceManager $service
     */
    public function __construct(ServiceManager $service) {
        $this->service = $service;

        $this->identity = $this->service->get('authentication')
                ->getIdentity()->getAuthenticationIdentity();
        $this->em = $service->get(EntityManager::class);
        $ViewHelper = new ViewHelper($service);
        $this->url = $ViewHelper->getUrl('img/');
    }

    public function fetchAll($params)
    {
        return $this->em->getRepository(CoreOrders::class)->fetchAll($params,$this->url);
    }

    public function fetch($id)
    {
        return $this->em->getRepository(CoreOrders::class)->fetch($id,$this->url);
    }

    public function create($dataObject)
    {
        $items = (array)$dataObject;
        $cart = $this->setPrducts($items);
        $userId = isset($items['userId'])?$items['userId']:0;
        $params = [
                'identity'=>$this->getUserById($userId),
                'createdById'=>$this->getUserByUsername($this->identity['user_id']),
                'cart'=>$cart,
                'balance'=>$this->getBalance($userId),
                'totalcart'=>  $this->getTotalCart($cart)
                ];
        $validator = new Validator($params);
        if($validator->isValid()){
            return $this->insertOrders($params);
        }
    }

    public function insertOrders($items)
    {
        $em = $this->em->getRepository(CoreOrders::class);
        return $em->create($items);
    }

    public function delete($id)
    {
        return $this->em->getRepository(CoreOrders::class)->delete($id);
    }

    /**
     * Obtiene usuario mediante username
     *
     * @param type $username
     * @return type
     */
    public function getUserById($id)
    {
        try{
            return $this->em->getRepository(OauthUsers::class)
                    ->createQueryBuilder('U')
                    ->select('U.id,U.displayName,U.username')
                    ->where('U.id = :id')
                    ->setParameter('id', $id)
                    ->getQuery()->getSingleResult();
        } catch (\Exception $ex) {
            return null;
        }
    }

    /**
     * Obtiene usuario mediante username
     *
     * @param type $username
     * @return type
     */
    public function getUserByUsername($username)
    {
        try{
            return $this->em->getRepository(OauthUsers::class)
                    ->createQueryBuilder('U')
                    ->select('U.id,U.displayName,U.username')
                    ->where('U.username = :username')
                    ->setParameter('username', $username)
                    ->getQuery()->getSingleResult();
        } catch (\Exception $ex) {
            return null;
        }
    }

    public function setPrducts($items)
    {
        $entities = [];
        $products = isset($items['products'])?$items['products']:[];
        foreach ($products as $item){
            try{
                $producto = $this->em->getRepository(CoreProducts::class)
                        ->createQueryBuilder('P')
                        ->select('P.id,P.sku,P.description,P.brand,P.title,P.realPrice,P.price,P.payload')
                        ->where('P.id = :id')
                        ->setParameter('id', $item['id'])
                        ->andWhere('P.enabled = 1')
                        ->getQuery()->getSingleResult();
                $producto['quantity']=$item['quantity'];
                $entities[] = $producto;
            } catch (\Exception $ex) {

            }
        }
        return $entities;
    }

    /**
     *
     * @param type $userId
     * @return type
     */
    public function getBalance($userId)
    {
        try{
            return $this->em->getRepository(CoreUserTransactions::class)
                    ->createQueryBuilder('U')
                    ->select('SUM(U.amount) as amount')
                    ->innerJoin('U.user', 'R')
                    ->where('R.id = :id')
                    ->setParameter('id', $userId)
                    ->getQuery()->getSingleResult();
        } catch (\Exception $ex) {
            return 0;
        }

    }

    /**
     *
     * @param type $cart
     * @return type
     */
    private function getTotalCart($cart)
    {
        $total = 0;
        foreach ($cart as $item){
            $total += $item['price']*$item['quantity'];
        }
        return $total;
    }

}


text:
angular.module('app.topnav', [])

.directive('topNav', function() {

  function link(scope, element, attrs) {

  }

  return {
    restrict: 'E',
    templateUrl: 'com/topnav.tpl.html',
    link: link,
    scope: true
  };
})

;


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Liferay.SDK.Service.V62.ResourcePermission
{
	public class ResourcePermissionService : ServiceBase
	{
		public ResourcePermissionService(ISession session)
			: base(session)
		{
		}

		public async Task AddResourcePermissionAsync(long groupId, long companyId, string name, int scope, string primKey, long roleId, string actionId)
		{
			var _parameters = new JsonObject();

			_parameters.Add("groupId", groupId);
			_parameters.Add("companyId", companyId);
			_parameters.Add("name", name);
			_parameters.Add("scope", scope);
			_parameters.Add("primKey", primKey);
			_parameters.Add("roleId", roleId);
			_parameters.Add("actionId", actionId);

			var _command = new JsonObject()
			{
				{ "/resourcepermission/add-resource-permission", _parameters }
			};

			await this.Session.InvokeAsync(_command);
		}

		public async Task RemoveResourcePermissionAsync(long groupId, long companyId, string name, int scope, string primKey, long roleId, string actionId)
		{
			var _parameters = new JsonObject();

			_parameters.Add("groupId", groupId);
			_parameters.Add("companyId", companyId);
			_parameters.Add("name", name);
			_parameters.Add("scope", scope);
			_parameters.Add("primKey", primKey);
			_parameters.Add("roleId", roleId);
			_parameters.Add("actionId", actionId);

			var _command = new JsonObject()
			{
				{ "/resourcepermission/remove-resource-permission", _parameters }
			};

			await this.Session.InvokeAsync(_command);
		}

		public async Task RemoveResourcePermissionsAsync(long groupId, long companyId, string name, int scope, long roleId, string actionId)
		{
			var _parameters = new JsonObject();

			_parameters.Add("groupId", groupId);
			_parameters.Add("companyId", companyId);
			_parameters.Add("name", name);
			_parameters.Add("scope", scope);
			_parameters.Add("roleId", roleId);
			_parameters.Add("actionId", actionId);

			var _command = new JsonObject()
			{
				{ "/resourcepermission/remove-resource-permissions", _parameters }
			};

			await this.Session.InvokeAsync(_command);
		}

		public async Task SetIndividualResourcePermissionsAsync(long groupId, long companyId, string name, string primKey, IDictionary<string, object> roleIdsToActionIds)
		{
			var _parameters = new JsonObject();

			_parameters.Add("groupId", groupId);
			_parameters.Add("companyId", companyId);
			_parameters.Add("name", name);
			_parameters.Add("primKey", primKey);
			_parameters.Add("roleIdsToActionIds", roleIdsToActionIds);

			var _command = new JsonObject()
			{
				{ "/resourcepermission/set-individual-resource-permissions", _parameters }
			};

			await this.Session.InvokeAsync(_command);
		}

		public async Task SetIndividualResourcePermissionsAsync(long groupId, long companyId, string name, string primKey, long roleId, IEnumerable<string> actionIds)
		{
			var _parameters = new JsonObject();

			_parameters.Add("groupId", groupId);
			_parameters.Add("companyId", companyId);
			_parameters.Add("name", name);
			_parameters.Add("primKey", primKey);
			_parameters.Add("roleId", roleId);
			_parameters.Add("actionIds", actionIds);

			var _command = new JsonObject()
			{
				{ "/resourcepermission/set-individual-resource-permissions", _parameters }
			};

			await this.Session.InvokeAsync(_command);
		}
	}
}


text:
from datetime import date
from django.db import models

class JournalEntry(models.Model):
    @staticmethod
    def get_entry_date():
        return date.today()

    def get_entry_wrapper():
        return JournalEntry.get_entry_date()

    text = models.TextField(default='')
    date = models.DateField(default=get_entry_wrapper)


text:
package apis

import (
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/go-ozzo/ozzo-routing"
	"github.com/go-ozzo/ozzo-routing/auth"
	"github.com/Zhanat87/go/app"
	"github.com/Zhanat87/go/errors"
	"github.com/Zhanat87/go/responses"
	"github.com/Zhanat87/go/daos"
	"github.com/Zhanat87/go/models"
	"strings"
	"github.com/Zhanat87/go/db"
	"github.com/Zhanat87/go/helpers"
	"github.com/Zhanat87/go/jwtlocal"
	golang_errors "errors"
	"github.com/go-redis/redis"
	"github.com/satori/go.uuid"
	"fmt"
	"os"
	"github.com/go-ozzo/ozzo-dbx"
	"database/sql"
)

type Credential struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

/*
https://godoc.org/golang.org/x/oauth2/jwt
https://jwt.io/
 */
func SignIn(signingKey string) routing.Handler {
	return func(c *routing.Context) error {
		var credential Credential
		err := c.Read(&credential)
		if err != nil {
			return errors.Unauthorized(err.Error())
		}

		rs := app.GetRequestScope(c)
		var user *models.User
		if strings.Contains(credential.Email, "@") {
			user, err = daos.NewUserDAO().FindByEmail(rs, credential.Email)
			if err != nil {
				return errors.Unauthorized("user with this email not found")
			}
		} else {
			user, err = daos.NewUserDAO().FindByUsername(rs, credential.Email)
			if err != nil {
				return errors.Unauthorized("user with this username not found")
			}
		}
		if !user.ValidatePassword(credential.Password) {
			return errors.Unauthorized("password not valid")
		}

		token, err := createToken(user, signingKey)
		if err != nil {
			return errors.Unauthorized(err.Error())
		}

		return c.Write(responses.MakeSignInSuccessResponse(token, user))
	}
}

func JWTHandler(c *routing.Context, j *jwt.Token) error {
	if ok, err := jwtlocal.CheckJWTTokenIsValid(c); ok != true {
		return golang_errors.New(err.Error())
	}
	// @link http://stackoverflow.com/questions/18041334/convert-interface-to-int-in-golang
	userID := int(j.Claims.(jwt.MapClaims)["id"].(float64))
	app.GetRequestScope(c).SetUserID(userID)
	// src/github.com/go-ozzo/ozzo-routing/auth/handlers.go:208
	c.Set("JWT", j)
	return nil
}

func SignOut() routing.Handler {
	return func(c *routing.Context) error {
		claims := c.Get("JWT").(*jwt.Token).Claims.(jwt.MapClaims)
		unixTime := int64(claims["exp"].(float64))
		t := time.Now().Unix()
		delta := unixTime - t

		err := db.NewRedis().Set(jwtlocal.GetJWTToken(c), true, time.Second * time.Duration(delta)).Err()
		if err != nil {
			errors.InternalServerError(err)
		}

		return c.Write(responses.APISuccess{Status: 200, Message: "token_invalidated"})
	}
}

func SignUp(service userService) routing.Handler {
	return func(c *routing.Context) error {
		var model models.User
		if err := c.Read(&model); err != nil {
			return err
		}
		model.Username = model.Email
		model.Status = 1
		_, err := service.Create(app.GetRequestScope(c), &model)
		if err != nil {
			return err
		}

		return c.Write(responses.APISuccess{Status: 200, Message: "user success registered!"})
	}
}

func RefreshJWTToken(signingKey string) routing.Handler {
	return func(c *routing.Context) error {
		client := db.NewRedis()
		token := jwtlocal.GetJWTToken(c)
		_, err := client.Get(token + "_refresh").Result()
		if err == redis.Nil {
			userDAO := daos.NewUserDAO()
			user, err := userDAO.Get(app.GetRequestScope(c), app.GetRequestScope(c).UserID())
			if err != nil {
				return errors.NotFound("user")
			}
			token, err := createToken(user, signingKey)
			if err != nil {
				return errors.Unauthorized(err.Error())
			}

			client.Set(token + "_refresh", true, time.Hour * 24).Err()
			if err != nil {
				errors.InternalServerError(err)
			}

			return c.Write(responses.APISuccess{Status: 200, Message: token})
		} else if err != nil {
			return errors.InternalServerError(err)
		} else {
			return errors.Unauthorized("token can refreshed only one time")
		}
	}
}

func createToken(user *models.User, signingKey string) (string, error) {
	return auth.NewJWT(jwt.MapClaims{
		"id":       user.GetId(),
		"username": user.GetUsername(),
		"email":    user.GetEmail(),
		"exp":      time.Now().Add(time.Hour * 24).Unix(),
	}, signingKey)
}

func PasswordResetRequest(userDAO *daos.UserDAO) routing.Handler {
	return func(c *routing.Context) error {
		// @link https://github.com/go-ozzo/ozzo-routing#reading-request-data
		data := &struct{
			Email string
		}{}
		if err := c.Read(&data); err != nil {
			return err
		}

		rs := app.GetRequestScope(c)
		user, err := userDAO.FindByEmail(rs, data.Email)
		if err != nil {
			return err
		}

		token := uuid.NewV4().String()
		// @link https://groups.google.com/forum/#!topic/golang-nuts/2MzMl_sff4E
		//user.PasswordResetToken = &token
		user.PasswordResetToken = models.JsonNullString{sql.NullString{String: token, Valid:true}}
		msg := fmt.Sprintf("reset password",
			os.Getenv("CLIENT_BASE_URL"), token)
		_, err = helpers.SendEmail(user.Email, "Golang app: request password reset", msg)
		if err != nil {
			return err
		}
		dbBuilder := rs.Tx()
		_, err = dbBuilder.Update("user", dbx.Params{"password_reset_token": token},
			dbx.HashExp{"id": user.Id}).Execute()
		if err != nil {
			return err
		}

		return c.Write(responses.APISuccess{Status: 200, Message: "Check your email for further instructions!"})
	}
}

func PasswordReset(userDAO *daos.UserDAO) routing.Handler {
	return func(c *routing.Context) error {
		// @link https://github.com/go-ozzo/ozzo-routing#reading-request-data
		data := &struct{
			Password string
		}{}
		if err := c.Read(&data); err != nil {
			return err
		}

		rs := app.GetRequestScope(c)
		user, err := userDAO.FindByField(rs, "password_reset_token", c.Param("token"))
		if err != nil {
			return err
		}
		hash, err := user.Hash(data.Password)
		if err != nil {
			return err
		}

		dbBuilder := rs.Tx()
		_, err = dbBuilder.Update("user", dbx.Params{"password_reset_token": nil, "password_hash": hash},
			dbx.HashExp{"id": user.Id}).Execute()
		if err != nil {
			return err
		}

		return c.Write(responses.APISuccess{Status: 200, Message: "Password success changed!"})
	}
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'katex2html'


text:
package org.apache.maven.wrapper;

import static org.mockito.AdditionalMatchers.or;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.maven.wrapper.PathAssembler.LocalDistribution;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

/**
 * @author Hans Dockter
 */
public class InstallerTest {
    private File testDir = new File("target/test-files/SystemPropertiesHandlerTest-" + System.currentTimeMillis());
    private Installer install;
    private File distributionDir;
    private File zipStore;
    private File mavenHomeDir;
    private File zipDestination;
    private File checksumDestination;
    private WrapperConfiguration configuration = new WrapperConfiguration();
    private Downloader download;
    private PathAssembler pathAssembler;
    private LocalDistribution localDistribution;
    private static URI WORKING_DISTRIBUTION_URI = URI.create("http://server/maven-0.9.zip");
    private static URI BROKEN_DISTRIBUTION_URI = URI.create("http://server.down/maven-0.9.zip");
    private static URI CHECKSUM_URI = URI.create("http://server/maven-0.9.zip.sha1");

    @Before
    public void setup() throws Exception {
        testDir.mkdirs();
        configuration.setZipBase(PathAssembler.PROJECT_STRING);
        configuration.setZipPath("someZipPath");
        configuration.setDistributionBase(PathAssembler.MAVEN_USER_HOME_STRING);
        configuration.setDistributionPath("someDistPath");
        configuration.setDistributionUris(Collections.singletonList(WORKING_DISTRIBUTION_URI));
        configuration.setAlwaysDownload(false);
        configuration.setAlwaysUnpack(false);
        distributionDir = new File(testDir, "someDistPath");
        mavenHomeDir = new File(distributionDir, "maven-0.9");
        zipStore = new File(testDir, "zips");
        zipDestination = new File(zipStore, "maven-0.9.zip");
        checksumDestination = new File(zipStore, "maven-0.9.zip.checksum");

        download = mock(Downloader.class);
        pathAssembler = mock(PathAssembler.class);
        localDistribution = mock(LocalDistribution.class);

        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(final InvocationOnMock invocationOnMock) throws Throwable {
                File downloadTarget = (File) invocationOnMock.getArguments()[1];
                FileUtils.copyFile(zipDestination, downloadTarget);
                return null;
            }
        }).when(download).download(eq(WORKING_DISTRIBUTION_URI), any(File.class));

        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(final InvocationOnMock invocationOnMock) throws Throwable {
                URI address = (URI) invocationOnMock.getArguments()[0];
                throw new IOException("Connection refused to '" + address + "'.");
            }
        }).when(download).download(eq(BROKEN_DISTRIBUTION_URI), any(File.class));

        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(final InvocationOnMock invocationOnMock) throws Throwable {
                File downloadTarget = (File) invocationOnMock.getArguments()[1];
                FileUtils.copyFile(checksumDestination, downloadTarget);
                return null;
            }
        }).when(download).download(eq(CHECKSUM_URI), any(File.class));
        when(localDistribution.getZipFile()).thenReturn(zipDestination);
        when(localDistribution.getDistributionDir()).thenReturn(distributionDir);
        when(pathAssembler.getDistribution(configuration, WORKING_DISTRIBUTION_URI)).thenReturn(localDistribution);
        when(pathAssembler.getDistribution(configuration, BROKEN_DISTRIBUTION_URI)).thenReturn(localDistribution);

        install = new Installer(download, pathAssembler);
    }

    private void createTestZip(File zipDestination) throws Exception {
        File explodedZipDir = new File(testDir, "explodedZip");
        explodedZipDir.mkdirs();
        zipDestination.getParentFile().mkdirs();
        File mavenScript = new File(explodedZipDir, "maven-0.9/bin/mvn");
        mavenScript.getParentFile().mkdirs();
        FileUtils.write(mavenScript, "something");

        zipTo(explodedZipDir, zipDestination);
    }

    private void createChecksum(final File checksumDestination, final String checksum) throws Exception {
        FileUtils.write(checksumDestination, checksum);
    }

    public void testCreateDist() throws Exception {
        File homeDir = install.createDist(configuration);

        Assert.assertEquals(mavenHomeDir, homeDir);
        Assert.assertTrue(homeDir.isDirectory());
        Assert.assertTrue(new File(homeDir, "bin/mvn").exists());
        Assert.assertTrue(zipDestination.exists());

        Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration, WORKING_DISTRIBUTION_URI));
        Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
        Assert.assertEquals(zipDestination, localDistribution.getZipFile());

        download.download(new URI("http://some/test"), distributionDir);
        verify(download).download(new URI("http://some/test"),
        distributionDir);
    }

    @Test
    public void testCreateDistWithExistingDistribution() throws Exception {
        FileUtils.touch(zipDestination);
        mavenHomeDir.mkdirs();
        File someFile = new File(mavenHomeDir, "some-file");
        FileUtils.touch(someFile);

        File homeDir = install.createDist(configuration);

        Assert.assertEquals(mavenHomeDir, homeDir);
        Assert.assertTrue(mavenHomeDir.isDirectory());
        Assert.assertTrue(new File(homeDir, "some-file").exists());
        Assert.assertTrue(zipDestination.exists());

        Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration, WORKING_DISTRIBUTION_URI));
        Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
        Assert.assertEquals(zipDestination, localDistribution.getZipFile());
    }

    @Test
    public void testCreateDistWithExistingDistAndZipAndAlwaysUnpackTrue() throws Exception {
        createTestZip(zipDestination);
        mavenHomeDir.mkdirs();
        File garbage = new File(mavenHomeDir, "garbage");
        FileUtils.touch(garbage);
        configuration.setAlwaysUnpack(true);

        File homeDir = install.createDist(configuration);

        Assert.assertEquals(mavenHomeDir, homeDir);
        Assert.assertTrue(mavenHomeDir.isDirectory());
        Assert.assertFalse(new File(homeDir, "garbage").exists());
        Assert.assertTrue(zipDestination.exists());

        Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration, WORKING_DISTRIBUTION_URI));
        Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
        Assert.assertEquals(zipDestination, localDistribution.getZipFile());
    }

    @Test
    public void testCreateDistWithExistingZipAndDistAndAlwaysDownloadTrue() throws Exception {
        createTestZip(zipDestination);
        File garbage = new File(mavenHomeDir, "garbage");
        FileUtils.touch(garbage);
        configuration.setAlwaysUnpack(true);

        File homeDir = install.createDist(configuration);

        Assert.assertEquals(mavenHomeDir, homeDir);
        Assert.assertTrue(mavenHomeDir.isDirectory());
        Assert.assertTrue(new File(homeDir, "bin/mvn").exists());
        Assert.assertFalse(new File(homeDir, "garbage").exists());
        Assert.assertTrue(zipDestination.exists());

        Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration, WORKING_DISTRIBUTION_URI));
        Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
        Assert.assertEquals(zipDestination, localDistribution.getZipFile());

        // download.download(new URI("http://some/test"), distributionDir);
        // verify(download).download(new URI("http://some/test"),
        // distributionDir);
    }

    @Test
    public void testVerifyDownload() throws Exception {
        configuration.setAlwaysDownload(true);
        configuration.setVerifyDownload(true);
        // configuration.setChecksum(Collections.singletonList(CHECKSUM_URI));
        configuration.setChecksumAlgorithm(Checksum.SHA1);

        createTestZip(zipDestination);
        createChecksum(checksumDestination, Checksum.SHA1.generate(new FileInputStream(zipDestination)));
        mavenHomeDir.mkdirs();
        File garbage = new File(mavenHomeDir, "garbage");
        FileUtils.touch(garbage);
        configuration.setAlwaysUnpack(true);

        File homeDir = install.createDist(configuration);

        Assert.assertEquals(mavenHomeDir, homeDir);
        Assert.assertTrue(mavenHomeDir.isDirectory());
        Assert.assertTrue(new File(homeDir, "bin/mvn").exists());
        Assert.assertFalse(new File(homeDir, "garbage").exists());
        Assert.assertTrue(zipDestination.exists());

        Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration, WORKING_DISTRIBUTION_URI));
        Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
        Assert.assertEquals(zipDestination, localDistribution.getZipFile());
    }

    @Test
    public void testVerifyDownloadFails() throws Exception {
        configuration.setAlwaysDownload(true);
        configuration.setVerifyDownload(true);
        configuration.setChecksumAlgorithm(Checksum.SHA1);

        createTestZip(zipDestination);
        createChecksum(checksumDestination, "Foo-Bar");
        mavenHomeDir.mkdirs();
        File garbage = new File(mavenHomeDir, "garbage");
        FileUtils.touch(garbage);
        configuration.setAlwaysUnpack(true);

        try {
            install.createDist(configuration);
            Assert.fail("Expected RuntimeException");
        } catch (final RuntimeException e) {
            Assert.assertEquals("Maven distribution '" + WORKING_DISTRIBUTION_URI.toString() + "' failed to verify against '"
                    + CHECKSUM_URI.toString() + "'.", e.getMessage());
        }
    }

    @Test
    public void testMultipleDistributionsFirstSucceeds() throws Exception {
        configuration.setAlwaysDownload(true);
        configuration.setDistributionUris(Arrays.asList(WORKING_DISTRIBUTION_URI, BROKEN_DISTRIBUTION_URI));

        createTestZip(zipDestination);
        mavenHomeDir.mkdirs();
        File garbage = new File(mavenHomeDir, "garbage");
        FileUtils.touch(garbage);
        configuration.setAlwaysUnpack(true);

        File homeDir = install.createDist(configuration);

        Assert.assertEquals(mavenHomeDir, homeDir);
        Assert.assertTrue(mavenHomeDir.isDirectory());
        Assert.assertTrue(new File(homeDir, "bin/mvn").exists());
        Assert.assertFalse(new File(homeDir, "garbage").exists());
        Assert.assertTrue(zipDestination.exists());

        Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration, WORKING_DISTRIBUTION_URI));
        Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
        Assert.assertEquals(zipDestination, localDistribution.getZipFile());

        verify(download).download(eq(WORKING_DISTRIBUTION_URI), any(File.class));
    }

    @Test
    public void testMultipleDistributionsFirstFail() throws Exception {
        configuration.setAlwaysDownload(true);
        configuration.setDistributionUris(Arrays.asList(BROKEN_DISTRIBUTION_URI, WORKING_DISTRIBUTION_URI));

        createTestZip(zipDestination);
        mavenHomeDir.mkdirs();
        File garbage = new File(mavenHomeDir, "garbage");
        FileUtils.touch(garbage);
        configuration.setAlwaysUnpack(true);

        File homeDir = install.createDist(configuration);

        Assert.assertEquals(mavenHomeDir, homeDir);
        Assert.assertTrue(mavenHomeDir.isDirectory());
        Assert.assertTrue(new File(homeDir, "bin/mvn").exists());
        Assert.assertFalse(new File(homeDir, "garbage").exists());
        Assert.assertTrue(zipDestination.exists());

        Assert.assertEquals(localDistribution, pathAssembler.getDistribution(configuration, WORKING_DISTRIBUTION_URI));
        Assert.assertEquals(distributionDir, localDistribution.getDistributionDir());
        Assert.assertEquals(zipDestination, localDistribution.getZipFile());

        verify(download, times(2)).download(or(eq(BROKEN_DISTRIBUTION_URI), eq(WORKING_DISTRIBUTION_URI)), any(File.class));
    }

    @Test
    public void testMultipleDistributionsBothFail() throws Exception {
        configuration.setAlwaysDownload(true);
        configuration.setDistributionUris(Arrays.asList(BROKEN_DISTRIBUTION_URI, BROKEN_DISTRIBUTION_URI));

        createTestZip(zipDestination);
        mavenHomeDir.mkdirs();
        File garbage = new File(mavenHomeDir, "garbage");
        FileUtils.touch(garbage);
        configuration.setAlwaysUnpack(true);

        try {
            install.createDist(configuration);
            Assert.fail("Expected RuntimeException");
        } catch (final IOException e) {
            Assert.assertEquals("Connection refused to '" + BROKEN_DISTRIBUTION_URI + "'.", e.getMessage());
        }

        verify(download, times(2)).download(eq(BROKEN_DISTRIBUTION_URI), any(File.class));
    }

    private static void zipTo(File directoryToZip, File destFile) throws IOException {
        FileOutputStream fos = null;
        ZipOutputStream zout = null;

        try {
            fos = new FileOutputStream(destFile);
            zout = new ZipOutputStream(fos);

            for (File f : directoryToZip.listFiles()) {
                zipFiles("", zout, f);
            }
        } finally {
            if (zout != null) {
                zout.close();
            }

            if (fos != null) {
                fos.close();
            }
        }
    }

    private static void zipFile(String prefixPath, ZipOutputStream zout, File f) throws IOException {
        InputStream fin = null;

        try {
            ZipEntry ze = new ZipEntry(prefixPath + f.getName());
            ze.setTime(f.lastModified());
            zout.putNextEntry(ze);
            fin = new FileInputStream(f);
            byte[] buffer = new byte[4096];

            for (int n; (n = fin.read(buffer)) > 0;) {
                zout.write(buffer, 0, n);
            }

            zout.closeEntry();
        } finally {
            if (fin != null) {
                fin.close();
            }
        }

    }

    private static void zipFolder(String prefixPath, ZipOutputStream zout, File f) throws IOException {
        ZipEntry ze = new ZipEntry(prefixPath + f.getName() + '/');
        ze.setTime(f.lastModified());
        zout.putNextEntry(ze);
        zout.closeEntry();

        for (File file : f.listFiles()) {
            zipFiles(prefixPath + f.getName(), zout, file);
        }
    }

    private static void zipFiles(String prefix, ZipOutputStream zout, File f) throws IOException {
        String prefixPath = prefix + "/";

        if (prefixPath.startsWith("/")) {
            prefixPath = prefixPath.substring(1);
        }

        if (f.isFile()) {
            zipFile(prefixPath, zout, f);
        } else {
            zipFolder(prefixPath, zout, f);
        }
    }

}


text:
int P2PTest( _MYNAMESPACE_::MPI::Environment::CommPtr &comm );
int BcastTest( _MYNAMESPACE_::MPI::Environment::CommPtr &comm );
int CorrectiveTest( _MYNAMESPACE_::MPI::Environment::CommPtr &comm );
int CorrectiveAllTest( _MYNAMESPACE_::MPI::Environment::CommPtr &comm );
int WindowObjectTest(  _MYNAMESPACE_::MPI::Environment::CommPtr &comm );

#endif // P2PTEST_H


text:
/*!
	@file
	@author		Denis Koronchik
	@author		Georgiy Evmenov
	@date		09/2007
*/
/*
	This file is part of MyGUI.

	MyGUI is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	MyGUI is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with MyGUI.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_DynLib.h"

#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
#	include <Windows.h>
#elif MYGUI_PLATFORM == MYGUI_PLATFORM_LINUX
#       include <dlfcn.h>
#endif

namespace MyGUI
{
	DynLib::DynLib( const std::string& name )
	{
		mName = name;
		mInstance = nullptr;
	}

	DynLib::~DynLib()
	{
	}

	bool DynLib::load()
	{
		// Log library load
		MYGUI_LOG(Info, "Loading library " << mName);

#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
		//APPLE SPECIFIC CODE HERE
#else
		mInstance = (MYGUI_DYNLIB_HANDLE)MYGUI_DYNLIB_LOAD( mName.c_str() );
#endif

		return mInstance != 0;
	}

	void DynLib::unload()
	{
		// Log library unload
		MYGUI_LOG(Info, "Unloading library " << mName);
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
		//APPLE SPECIFIC CODE HERE
#else
		if (MYGUI_DYNLIB_UNLOAD(mInstance))
		{
			MYGUI_EXCEPT("Could not unload dynamic library '" << mName << "'. System Error: " << dynlibError());
		}
#endif
	}

	void* DynLib::getSymbol( const std::string& strName ) const throw()
	{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_APPLE
		//APPLE SPECIFIC CODE HERE
		return nullptr;
#else
		return (void*)MYGUI_DYNLIB_GETSYM(mInstance, strName.c_str());
#endif
	}

	std::string DynLib::dynlibError() const
	{
#if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32
		LPVOID lpMsgBuf;
		FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER |
			FORMAT_MESSAGE_FROM_SYSTEM |
			FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			GetLastError(),
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			(LPTSTR) &lpMsgBuf,
			0,
			NULL
		);
		std::string ret = (char*)lpMsgBuf;
		// Free the buffer.
		LocalFree( lpMsgBuf );
		return ret;
#else
		return "no unix error function defined yet";
#endif
	}

	std::string DynLib::getName(void) const
	{
		return mName;
	}

} // namespace MyGUI


text:
RabbitMQ Dockerfile
===================

Build
-----
```
docker build -t dokku/rabbitmq github.com/jlachowski/dokku-rabbitmq-dockerfiles.git
```

Usage
-----
Start with 'admin' user and `<admin password>`
```
docker run -p 5672 -p 15672 -d dokku/rabbitmq /usr/bin/start-rabbitmq.sh <admin password>
```

Start with persistent database (`<volume>` - host directory)
```
docker run -v <volume>:/opt/rabbitmq -p 5672 -p 15672 -d dokku/rabbitmq /usr/bin/start-rabbitmq.sh <admin password>
```

TODO:
-----
- improve creation of admin user