text:
usage()
{
	e=`basename "$0"`
	cat<<END
Usage: $e modulenames
END
}

find_nitc()
{
	recent=`ls -t ../src/nitc ../src/nitc_[0-9] ../bin/nitc ../c_src/nitc 2>/dev/null | head -1`
	if [[ "x$recent" == "x" ]]; then
		echo 'Could not find nitc, aborting'
		exit 1
	fi
	echo 'Using nitc from: '$recent
	NITC=$recent
}

# The default nitc compiler
[ -z "$NITC" ] && find_nitc

if [ $# = 0 ]; then
	usage;
	exit
fi

ok=""
nok=""

# Process each files given as arguments
for ii in "$@"; do
	if [ ! -f $ii ]; then
		echo "File '$ii' does not exist."
		continue
	fi

	# Prepare the includes
	tmp=${ii/../AA}
	if [ "x$tmp" = "x$ii" ]; then
		oincludes="-I . -I ../lib/standard -I ../lib/standard/collection"
	else
		oincludes=""
	fi

	# Process each alternatives in the current file
	for alt in "" `sed -n 's/.*#!*\(alt[0-9]*\)#.*/\1/p' "$ii" | sort -u`; do
		f=`basename "$ii" .nit`
		d=`dirname "$ii"`
		ff="$f"
		i="$ii"
		includes="$oincludes"

		if [ "x$alt" != "x" ]; then
			test -d alt || mkdir -p alt
			i="alt/${f}_$alt.nit"
			ff="${ff}_$alt"
			sed "s/#$alt#//g;/#!$alt#/d" "$ii" > "$i"
			includes="$includes -I alt"
		fi
		ff="$ff$MARK"

		echo -n "=> $i: "

		# Clean-up before compile and tests
		rm -rf .nit_compile 2> /dev/null

		# Compile
		# The point of ICode testing is to validate analysis/optimizations
		# Force '--global' option !
		$NITC $OPT --global --output-format icode "$i" $includes 2> "$ff.cmp.err" > "$ff.compile.log"
		ERR=$?
		if [ "$ERR" != 0 ]; then
			# Could not compile
			echo "! [======= fail: Compilation error =======]"
			nok="$nok $ff"
		else
			TEST_FILE=$d/$ff.tests
			if [ ! -f $TEST_FILE ]; then
				# Could not find the .tests file associated with this test
				echo ". [======= fail: Cannot open test file =======]"
				nok="$nok $ff"
				continue
			fi
			echo "."

			# Execute tests
			# Each lines in the .tests file describe a test to execute on the generated
			# ICode. The file has 4 parameters:
			# - The class
			# - The method
			# - The type of test
			# - Arguments for the test
			# We use the class to open the right icode file.
			# We use a special method named "no-file" to ensure that the class file does not exist.
			# If the method is different from "no-file" then we search in said method for the expression given
			# with the _arguments_ field. This expression will be evaluated as a awk regexp.
			# We have two types of tests :
			# - has : the given argument must be found for the test to be successful
			# - no :  the given argument must NOT be found for the test to be successful
			cptr=0
			while IFS=, read CLASS METHOD TYPE ATTR
			do
				ICODE_FILE=$d/.nit_compile/$CLASS.icode
				let cptr+=1
				echo -n '==> Test #'$cptr' ...... '

				if [ -f $ICODE_FILE ]; then
					# Check if the file should exist
					if [ "x$METHOD" = "xno-file" ]; then
						# this is not normal, the file should not exist
						echo "Failed"
						nok="$nok $ff#$cptr"
						continue
					fi

					# Use awk to get the method in the file and search in it for the argument
					awk '
					BEGIN{
						process=0
					}
					/'"$METHOD"'/{
						process=1
					}
					/^$/ {
						process=0
					}
					/'"$ATTR"'/{
						if(process){
							exit -3
						}
					}
					' $ICODE_FILE
					awkstatus=$?

					if [ $awkstatus -ne 0 ] ; then
						# Found the value !
						if [ "x$TYPE" = "xno" ]; then
							# Should not have beed found
							echo "Failed"
							nok="$nok $ff#$cptr"
						elif [ "x$TYPE" = "xhas" ]; then
							# Should have been found
							echo "Ok"
							ok="$ok $ff#$cptr"
						else
							echo "Test file format error !!!"
							exit -1
						fi
					else
						# Value not found
						if [ "x$TYPE" = "xno" ]; then
							# Should not have beed found
							echo "Ok"
							ok="$ok $ff#$cptr"
						elif [ "x$TYPE" = "xhas" ]; then
							# Should have been found
							echo "Failed"
							nok="$nok $ff#$cptr"
						else
							echo "Test file format error !!!"
							exit -1
						fi
					fi
				else
					# The class file was not found
					if [ "x$METHOD" = "xno-file" ]; then
						# this is normal
						echo "Ok"
						ok="$ok $ff#$cptr"
					else
						# Should have been found
						echo "Failed"
						nok="$nok $ff#$cptr"
					fi
				fi
			done < $TEST_FILE
		fi
	done
done

echo "ok: " `echo $ok | wc -w` "/" `echo $ok $nok $nos | wc -w`

if [ -n "$nok" ]; then
	echo "fail: $nok"
	echo "There were $(echo $nok | wc -w) errors !"
fi
if [ -n "$nos" ]; then
	echo "no sav: $nos"
fi

if [ -n "$nok" ]; then
	exit 1
else
	exit 0
fi


text:
#ifndef __TEST_HTTP_SERVER_H_
#define __TEST_HTTP_SERVER_H_

#include "network/network_error.h"
#include "network/network.h"
#include "basics/basics.h"

class TestHttpServer {
 public:
  // Constructor
  TestHttpServer(EventLoopImpl* ss, NetworkOptions& options);

  // Destructor
  ~TestHttpServer();

  // Handle for a URL meta request
  void HandleMetaRequest(IncomingHTTPRequest* _request);

  // Handler for any type of generic request
  void HandleGenericRequest(IncomingHTTPRequest* _request);

  // Handle for a URL terminate request
  void HandleTerminateRequest(IncomingHTTPRequest* _request);

 private:
  HTTPServer* server_;
};

#endif

redpajama_set_name: RedPajamaGithub


text:
! *****************************************************************************
! ... lineargs.f90
! ... Routines to simplify the processing of input arguments.
! ... COSMO project
! ... Quim Ballabrera, March 2017
! ... Version 0.1, released October 2017
! *****************************************************************************

module module_lineargs

use module_types, only: sp,dp,maxlen
use module_constants, only: nan,nan4
use module_utils

implicit none

integer                                          :: lineargs_nargs = 0
integer, dimension(:), allocatable               :: lineargs_used
character(len=maxlen), dimension(:), allocatable :: lineargs_val

contains
! ...
! ========================================================================
! ...
integer function lineargs () result(na)

integer i,j,jj,nn,iu
logical read_from_file
character(len=maxlen) word,line

na = iargc()
if (na.eq.0) return

read_from_file = .false.
call getarg(1,word)
if (word(1:3).eq.'--o') read_from_file = .true.
if (word(1:3).eq.'--O') read_from_file = .true.

if (read_from_file) then
! ... Read execution options from a file
! ...
  call getarg(2,word)
  iu = unitfree()
  open(iu,file=word,status='old')
  nn = numlines(iu,'ascii')
  na = 0
  do i=1,nn
    read(iu,'(A)') line
    if (line(1:1).ne.'#') na = na + numwords(line)
  enddo
  lineargs_nargs = na
  allocate (lineargs_val(na))
  allocate (lineargs_used(na))
  lineargs_used(:)  = 0

  rewind(iu)
  jj = 0
  do i=1,nn
    read(iu,'(A)') line
    if (line(1:1).ne.'#') then
      do j=1,numwords(line)
        jj = jj + 1
        call line_word(line,j,lineargs_val(jj))
      enddo
    endif
  enddo
  if (jj.NE.na) call stop_error (1,'something wrong in lineargs_ini')
  close(iu)
else
! ... Read execution options from command line
! ...
  lineargs_nargs = na
  allocate (lineargs_val(na))
  allocate (lineargs_used(na))
  lineargs_used(:)  = 0
  lineargs_val(:) = ''
  do i=1,lineargs_nargs
    call getarg(i,lineargs_val(i))
  enddo
endif

return
end function lineargs
! ...
! ========================================================================
! ...
subroutine argflg (label,flag)

character(len=*), intent(in)     :: label
logical, intent(inout)           :: flag

integer n,k

n = len_trim(label)

do k=1,lineargs_nargs
 if (lineargs_used(k).EQ.0) then
 if (lineargs_val(k)(:n).EQ.label(:n)) then
  lineargs_used(k) = 1
  flag = .true.
  return
 endif
 endif
enddo

return
end subroutine argflg
! ...
! ====================================================================
! ...
subroutine argflt (label,flag,val)
! ... Returns a float value from user arguments

character(len=*), intent(in)        :: label
logical, intent(inout)              :: flag
real(sp), intent(out)               :: val

! ... Local variables
! ...
integer n,k
character lett

if (flag) return

n = len_trim(label)
DO k=1,lineargs_nargs
 if (lineargs_used(k).EQ.0) then
 if (lineargs_val(k)(:n).EQ.label(:n)) then
  if (k+1.GT.lineargs_nargs) call stop_error(1,'Invalid option')
  if (lineargs_used(k+1).EQ.1) then
    write(6,*) 'Option ',TRIM(lineargs_val(k+1)),' already used.'
    call stop_error (1,'Invalid option')
  endif
  flag      = .true.
  lett      = lineargs_val(k+1)(1:1)
  if (lett.EQ.'N'.OR.lett.EQ.'n') then
  val     = nan4
  else
    read(lineargs_val(k+1),*) val
  endif
  lineargs_used(k)   = 1
  lineargs_used(k+1) = 1
  return
 endif
 endif
enddo

return
end subroutine argflt
! ...
! ====================================================================
! ...
subroutine argint (label,flag,val)
! ... Returns an integer value from user arguments

character(len=*), intent(in)        :: label
logical, intent(inout)              :: flag
integer, intent(out)                :: val

integer n,k

if (flag) return

n = len_trim(label)
DO k=1,lineargs_nargs
 if (lineargs_used(k).EQ.0) then
 if (lineargs_val(k)(:n).EQ.label(:n)) then
  if (k+1.GT.lineargs_nargs) call stop_error(1,'Invalid option')
  if (lineargs_used(k+1).EQ.1) then
    write(6,*) 'Option ',TRIM(lineargs_val(k+1)),' already used.'
    call stop_error (1,'Invalid option')
  endif
  flag      = .true.
  read(lineargs_val(k+1),*) val
  lineargs_used(k)   = 1
  lineargs_used(k+1) = 1
  return
 endif
 endif
enddo

return
end subroutine argint
! ...
! ====================================================================
! ...
subroutine argstr (label,flag,val)

character(len=*), intent(in)        :: label
logical, intent(inout)              :: flag
character(LEN=*), intent(out)       :: val

integer n,k

if (flag) return
n = len_trim(label)

DO k=1,lineargs_nargs
 if (lineargs_used(k).EQ.0) then
 if (lineargs_val(k)(:n).EQ.label(:n)) then
  if (k+1.GT.lineargs_nargs) call stop_error (1,'Invalid option')
  if (lineargs_used(k+1).EQ.1) then
    write(6,*) 'Option ',TRIM(lineargs_val(k+1)),' already used.'
    call stop_error (1,'Invalid option')
  endif
  flag      = .true.
  val       = TRIM(lineargs_val(k+1))
  lineargs_used(k)   = 1
  lineargs_used(k+1) = 1
  return
 endif
 endif
enddo

return
end subroutine argstr
! ...
! ====================================================================
! ...
subroutine arglst (label,flag,list)

character(LEN=*), intent(in)        :: label
logical, intent(inout)              :: flag
character(LEN=*), intent(out)       :: list

integer n,j,k

if (flag) return

list = ''
n = len_trim(label)

DO k=1,lineargs_nargs
 if (lineargs_used(k).EQ.0) then
 if (lineargs_val(k)(:n).EQ.label(:n)) then
  if (k+1.GT.lineargs_nargs) call stop_error(1,'Invalid option')
  flag = .true.
  lineargs_used(k) = 1
  DO j=1,lineargs_nargs-k
    if (lineargs_val(k+j)(1:1).EQ.'-') EXIT
    call strcat (list,lineargs_val(k+j))
    lineargs_used(k+j) = 1
  enddo
  return
 endif
 endif
enddo

return
end subroutine arglst
! ...
! ====================================================================
! ...
subroutine argdbl (label,flag,val)

character(LEN=*), intent(in)        :: label
logical, intent(inout)              :: flag
REAL(dp), intent(out)               :: val

character(LEN=1) lett
integer n,k

if (flag) return

n = len_trim(label)
DO k=1,lineargs_nargs
 if (lineargs_used(k).EQ.0) then
 if (lineargs_val(k)(:n).EQ.label(:n)) then
  if (k+1.GT.lineargs_nargs) call stop_error(1,'Invalid option')
  if (lineargs_used(k+1).EQ.1) then
    write(6,*) 'Option ',TRIM(lineargs_val(k+1)),' already used.'
    call stop_error (1,'Invalid option')
  endif
  flag      = .true.
  lett      = lineargs_val(k+1)(1:1)
  if (lett.EQ.'N'.OR.lett.EQ.'n') then
    val     = nan
  else
    read(lineargs_val(k+1),*) val
  endif
  lineargs_used(k)   = 1
  lineargs_used(k+1) = 1
  return
 endif
 endif
enddo

return
end subroutine argdbl
! ...
! ====================================================================
! ...
subroutine checkopts

integer i

if (lineargs_nargs.EQ.0) return

if (SUM(lineargs_used).NE.lineargs_nargs) then
  write(*,'(A)',ADVANCE="no") 'Unknown options : '
  DO i=1,lineargs_nargs
    if (lineargs_used(i).EQ.0) write(*,'(A)',ADVANCE="no") TRIM(lineargs_val(i))//' '
  enddo
  write(*,*)
  call stop_error(1,'Invalid options')
endif

end subroutine checkopts
! ...
! =======================================================================
! ...
subroutine arglast (file)

character(LEN=*), intent(out)  :: file

if (lineargs_used(lineargs_nargs).EQ.0) then
  file = lineargs_val(lineargs_nargs)
  lineargs_used(lineargs_nargs) = 1
else
  call stop_error(1,'Last argument already used in arglast')
endif

return
end subroutine arglast
! ...
! ========================================================================
! ...
end module module_lineargs


text:
html, body {
  height: 100%;
}

header.front-header {
  height: 300px;
}

header.front-header .jumbotron {
  height: 100%;
  width: 100%;
  background-image: url('/images/wings-bg.jpeg');
  background-position: 50% 30%;
  background-size: cover;
  padding: 2em;
  color: white;
  position: relative;
}

header.front-header .jumbotron div {
  position: absolute;
  bottom: 2em;
}

header.front-header h1,
header.front-header p {
  margin-bottom: 0px;
}

#content {
  min-height: 100%;
  margin-bottom: -8em;
}

#content:after {
  content: "";
  display: block;
  height: 2em
}

footer, #content:after {
  height: 8em;
}

footer {
  border-top: 1px solid #e7e7e7;
  background-color: #f8f8f8;
  margin-top: 2em;
}

footer, footer a {
  text-decoration: none;
  color: #777;
}

footer .container {
  padding-top: 2em;
}


text:
initializeWorkingDirAndScriptDir() {
    # Set working directory and remove all symbolic links
    workingDir=`pwd -P`

    # Go the script directory
    cd `dirname $0`
    # If the file itself is a symbolic link (ignoring parent directory links), then follow that link recursively
    # Note that scriptDir=`pwd -P` does not do that and cannot cope with a link directly to the file
    scriptFileBasename=`basename $0`
    while [ -L "$scriptFileBasename" ] ; do
        scriptFileBasename=`readlink $scriptFileBasename` # Follow the link
        cd `dirname $scriptFileBasename`
        scriptFileBasename=`basename $scriptFileBasename`
    done
    # Set script directory and remove other symbolic links (parent directory links)
    scriptDir=`pwd -P`
}
initializeWorkingDirAndScriptDir
droolsjbpmOrganizationDir="$scriptDir/../../.."
withoutJbpm="$withoutJbpm"

if [ $# != 1 ] && [ $# != 2 ] ; then
    echo
    echo "Usage:"
    echo "  $0 droolsReleaseTagName [jbpmReleaseTagName]"
    echo "For example:"
    echo "  $0 5.2.0.Final 5.1.0.Final"
    echo
    exit 1
fi

echo "The drools, guvnor, ... release tag name is $1"
if [ "$withoutJbpm" != 'true' ]; then
    echo "The jbpm release tag name is $2"
fi
echo -n "Is this ok? (Hit control-c if is not): "
read ok

startDateTime=`date +%s`

cd $droolsjbpmOrganizationDir

for repository in `cat ${scriptDir}/../repository-list.txt` ; do
    echo
    if [ ! -d $droolsjbpmOrganizationDir/$repository ]; then
        echo "==============================================================================="
        echo "Missing Repository: $repository. SKIPPING!"
        echo "==============================================================================="
    elif [ $repository = 'jbpm' ] && [ "$withoutJbpm" = 'true' ]; then
        echo "==============================================================================="
        echo "Without repository: $repository. SKIPPING!"
        echo "==============================================================================="
    else
        echo "==============================================================================="
        echo "Repository: $repository"
        echo "==============================================================================="
        cd $repository

        releaseTagName=$1
        if [ $repository = 'jbpm' ]; then
            releaseTagName=$2
        fi
        # note when retagging you 'll need add -f in here:
        git tag -a $releaseTagName -m "Tagging $releaseTagName"

        returnCode=$?
        cd ..
        if [ $returnCode != 0 ] ; then
            exit $returnCode
        fi
    fi
done

endDateTime=`date +%s`
spentSeconds=`expr $endDateTime - $startDateTime`

echo
echo "Total time: ${spentSeconds}s"


text:
package org.apache.druid.sql.calcite.rel;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptCost;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelWriter;
import org.apache.calcite.rel.core.Filter;
import org.apache.calcite.rel.logical.LogicalFilter;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexUtil;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.guava.Accumulator;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.guava.Sequences;
import org.apache.druid.query.ResourceLimitExceededException;
import org.apache.druid.segment.DimensionHandlerUtils;
import org.apache.druid.sql.calcite.planner.PlannerContext;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * DruidRel that has a main query, and also a subquery "right" that is used to filter the main query.
 */
public class DruidSemiJoin extends DruidRel<DruidSemiJoin>
{
  private final List<RexNode> leftExpressions;
  private final List<Integer> rightKeys;
  private final int maxSemiJoinRowsInMemory;
  private DruidRel<?> left;
  private RelNode right;

  private DruidSemiJoin(
      final RelOptCluster cluster,
      final RelTraitSet traitSet,
      final DruidRel<?> left,
      final RelNode right,
      final List<RexNode> leftExpressions,
      final List<Integer> rightKeys,
      final int maxSemiJoinRowsInMemory,
      final QueryMaker queryMaker
  )
  {
    super(cluster, traitSet, queryMaker);
    this.left = left;
    this.right = right;
    this.leftExpressions = ImmutableList.copyOf(leftExpressions);
    this.rightKeys = ImmutableList.copyOf(rightKeys);
    this.maxSemiJoinRowsInMemory = maxSemiJoinRowsInMemory;
  }

  public static DruidSemiJoin create(
      final DruidRel left,
      final DruidRel right,
      final List<Integer> leftKeys,
      final List<Integer> rightKeys,
      final PlannerContext plannerContext
  )
  {
    final ImmutableList.Builder<RexNode> listBuilder = ImmutableList.builder();

    final PartialDruidQuery leftPartialQuery = left.getPartialDruidQuery();
    if (leftPartialQuery.stage().compareTo(PartialDruidQuery.Stage.AGGREGATE) >= 0) {
      throw new ISE("LHS must not be an Aggregate");
    }

    if (leftPartialQuery.getSelectProject() != null) {
      for (int key : leftKeys) {
        listBuilder.add(leftPartialQuery.getSelectProject().getChildExps().get(key));
      }
    } else {
      for (int key : leftKeys) {
        listBuilder.add(RexInputRef.of(key, leftPartialQuery.getRowType()));
      }
    }

    return new DruidSemiJoin(
        left.getCluster(),
        left.getTraitSet(),
        left,
        right,
        listBuilder.build(),
        rightKeys,
        plannerContext.getPlannerConfig().getMaxSemiJoinRowsInMemory(),
        left.getQueryMaker()
    );
  }

  @Override
  public PartialDruidQuery getPartialDruidQuery()
  {
    return left.getPartialDruidQuery();
  }

  @Override
  public DruidSemiJoin withPartialQuery(final PartialDruidQuery newQueryBuilder)
  {
    return new DruidSemiJoin(
        getCluster(),
        getTraitSet().plusAll(newQueryBuilder.getRelTraits()),
        left.withPartialQuery(newQueryBuilder),
        right,
        leftExpressions,
        rightKeys,
        maxSemiJoinRowsInMemory,
        getQueryMaker()
    );
  }

  @Nullable
  @Override
  public DruidQuery toDruidQuery(final boolean finalizeAggregations)
  {
    final DruidRel rel = getLeftRelWithFilter();
    return rel != null ? rel.toDruidQuery(finalizeAggregations) : null;
  }

  @Override
  public DruidQuery toDruidQueryForExplaining()
  {
    return left.toDruidQueryForExplaining();
  }

  @Override
  public DruidSemiJoin asDruidConvention()
  {
    return new DruidSemiJoin(
        getCluster(),
        getTraitSet().replace(DruidConvention.instance()),
        left,
        RelOptRule.convert(right, DruidConvention.instance()),
        leftExpressions,
        rightKeys,
        maxSemiJoinRowsInMemory,
        getQueryMaker()
    );
  }

  @Override
  public Set<String> getDataSourceNames()
  {
    final DruidRel<?> druidRight = (DruidRel) this.right;
    Set<String> dataSourceNames = new LinkedHashSet<>();
    dataSourceNames.addAll(left.getDataSourceNames());
    dataSourceNames.addAll(druidRight.getDataSourceNames());
    return dataSourceNames;
  }

  @Override
  public int getQueryCount()
  {
    return left.getQueryCount() + ((DruidRel) right).getQueryCount();
  }

  @Override
  public Sequence<Object[]> runQuery()
  {
    final DruidRel<?> rel = getLeftRelWithFilter();
    if (rel != null) {
      return rel.runQuery();
    } else {
      return Sequences.empty();
    }
  }

  @Override
  protected RelDataType deriveRowType()
  {
    return left.getRowType();
  }

  @Override
  public List<RelNode> getInputs()
  {
    return ImmutableList.of(right);
  }

  @Override
  public void replaceInput(int ordinalInParent, RelNode p)
  {
    if (ordinalInParent != 0) {
      throw new IndexOutOfBoundsException(StringUtils.format("Invalid ordinalInParent[%s]", ordinalInParent));
    }
    // 'right' is the only one Calcite concerns. See getInputs().
    this.right = p;
  }

  @Override
  public RelNode copy(final RelTraitSet traitSet, final List<RelNode> inputs)
  {
    return new DruidSemiJoin(
        getCluster(),
        getTraitSet(),
        left,
        Iterables.getOnlyElement(inputs),
        leftExpressions,
        rightKeys,
        maxSemiJoinRowsInMemory,
        getQueryMaker()
    );
  }

  @Override
  public RelWriter explainTerms(RelWriter pw)
  {
    final String queryString;

    try {
      queryString = getQueryMaker().getJsonMapper().writeValueAsString(toDruidQueryForExplaining().getQuery());
    }
    catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }

    return super.explainTerms(pw)
                .input("right", right)
                .item("query", queryString)
                .item("leftExpressions", leftExpressions)
                .item("rightKeys", rightKeys);
  }

  @Override
  public RelOptCost computeSelfCost(final RelOptPlanner planner, final RelMetadataQuery mq)
  {
    return right.computeSelfCost(planner, mq).plus(left.computeSelfCost(planner, mq).multiplyBy(50));
  }

  /**
   * Returns a copy of the left rel with the filter applied from the right-hand side. This is an expensive operation
   * since it actually executes the right-hand side query.
   */
  private DruidRel<?> getLeftRelWithFilter()
  {
    final DruidRel<?> druidRight = (DruidRel) this.right;

    // Build list of acceptable values from right side.
    final Set<List<String>> valuess = new HashSet<>();
    final List<RexNode> conditions = druidRight.runQuery().accumulate(
        new ArrayList<>(),
        new Accumulator<List<RexNode>, Object[]>()
        {
          int numRows;

          @Override
          public List<RexNode> accumulate(final List<RexNode> theConditions, final Object[] row)
          {
            final List<String> values = new ArrayList<>(rightKeys.size());

            for (int i : rightKeys) {
              final Object value = row[i];
              if (value == null) {
                // NULLs are not supposed to match NULLs in a join. So ignore them.
                continue;
              }
              final String stringValue = DimensionHandlerUtils.convertObjectToString(value);
              values.add(stringValue);
            }

            if (valuess.add(values)) {
              if (++numRows > maxSemiJoinRowsInMemory) {
                throw new ResourceLimitExceededException(
                    StringUtils.format("maxSemiJoinRowsInMemory[%,d] exceeded", maxSemiJoinRowsInMemory)
                );
              }
              final List<RexNode> subConditions = new ArrayList<>();

              for (int i = 0; i < values.size(); i++) {
                final String value = values.get(i);
                // NULLs are not supposed to match NULLs in a join. So ignore them.
                if (value != null) {
                  subConditions.add(
                      getCluster().getRexBuilder().makeCall(
                          SqlStdOperatorTable.EQUALS,
                          leftExpressions.get(i),
                          getCluster().getRexBuilder().makeLiteral(value)
                      )
                  );
                }
                theConditions.add(makeAnd(subConditions));
              }
            }
            return theConditions;
          }
        }
    );

    valuess.clear();

    if (!conditions.isEmpty()) {
      // Add a filter to the left side.
      final PartialDruidQuery leftPartialQuery = left.getPartialDruidQuery();
      final Filter whereFilter = leftPartialQuery.getWhereFilter();
      final Filter newWhereFilter;

      if (whereFilter != null) {
        newWhereFilter = whereFilter.copy(
            whereFilter.getTraitSet(),
            whereFilter.getInput(),
            RexUtil.flatten(
                getCluster().getRexBuilder(),
                makeAnd(ImmutableList.of(whereFilter.getCondition(), makeOr(conditions)))
            )
        );
      } else {
        newWhereFilter = LogicalFilter.create(
            leftPartialQuery.getScan(),
            makeOr(conditions) // already in flattened form
        );
      }

      PartialDruidQuery newPartialQuery = PartialDruidQuery.create(leftPartialQuery.getScan())
                                                           .withWhereFilter(newWhereFilter)
                                                           .withSelectProject(leftPartialQuery.getSelectProject());

      if (leftPartialQuery.getAggregate() != null) {
        newPartialQuery = newPartialQuery.withAggregate(leftPartialQuery.getAggregate());
      }

      if (leftPartialQuery.getHavingFilter() != null) {
        newPartialQuery = newPartialQuery.withHavingFilter(leftPartialQuery.getHavingFilter());
      }

      if (leftPartialQuery.getAggregateProject() != null) {
        newPartialQuery = newPartialQuery.withAggregateProject(leftPartialQuery.getAggregateProject());
      }

      if (leftPartialQuery.getSort() != null) {
        newPartialQuery = newPartialQuery.withSort(leftPartialQuery.getSort());
      }

      if (leftPartialQuery.getSortProject() != null) {
        newPartialQuery = newPartialQuery.withSortProject(leftPartialQuery.getSortProject());
      }

      return left.withPartialQuery(newPartialQuery);
    } else {
      return null;
    }
  }

  private RexNode makeAnd(final List<RexNode> conditions)
  {
    if (conditions.size() == 1) {
      return Iterables.getOnlyElement(conditions);
    } else {
      return getCluster().getRexBuilder().makeCall(SqlStdOperatorTable.AND, conditions);
    }
  }

  private RexNode makeOr(final List<RexNode> conditions)
  {
    if (conditions.size() == 1) {
      return Iterables.getOnlyElement(conditions);
    } else {
      return getCluster().getRexBuilder().makeCall(SqlStdOperatorTable.OR, conditions);
    }
  }
}


text:
layout: default
title: Staff - I volontari presenti al PGDay.IT
permalink: /it/staff/
image: staff.jpg
modal: staff
lang: it
ref: staff
redirect_from:
 - /staff/
---

 {% include top-section.html %}

 {% include staff.html %}


text:
#include "PLGTest.h"
//#include "FRect.h"
#include "BSPLevelCell.h"
#include "LevelCell.h"
#include "BSPWallStaticMeshActor.h"
#include "BSPLevelGenerator.h"

ABSPLevelGenerator::ABSPLevelGenerator(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	//Find Wall Mesh
	static ConstructorHelpers::FObjectFinder<UStaticMesh> StaticMeshOb_AW3(TEXT("StaticMesh'/Game/Props/BSPWall.BSPWall'"));
	if (StaticMeshOb_AW3.Object)
	{
		wallMesh = StaticMeshOb_AW3.Object;
	}
	//Set how many times the rooms are divided (5 is good)
	loops = 5;
	//Set the GridSize (80, 80 seems good)
	GridSize = FSize(80, 80);
	//Set the size of one tile (size of the static mes)
	TileSize = FSize(192, 192);
	//Find the ceiling Blueprint
	static ConstructorHelpers::FObjectFinder<UBlueprint> ItemBlueprint(TEXT("Blueprint'/Game/Blueprints/CeilingLight.CeilingLight'"));
	if (ItemBlueprint.Object){
		ceilingLightClass = (UClass*)ItemBlueprint.Object->GeneratedClass;

	}
	//Find the Exit Blueprint
	static ConstructorHelpers::FObjectFinder<UBlueprint> ExitBlueprint(TEXT("Blueprint'/Game/Blueprints/exit.exit'"));
	if (ExitBlueprint.Object){
		exitClass = (UClass*)ExitBlueprint.Object->GeneratedClass;

	}
	//Find the Start Blueprint
	static ConstructorHelpers::FObjectFinder<UBlueprint> StartBlueprint(TEXT("Blueprint'/Game/Blueprints/playerStart.playerStart'"));
	if (StartBlueprint.Object){
		startClass = (UClass*)StartBlueprint.Object->GeneratedClass;

	}
	//Find the Wall light Blueprint
	static ConstructorHelpers::FObjectFinder<UBlueprint> LightBlueprint(TEXT("Blueprint'/Game/Blueprints/BSPWallLight.BSPWallLight'"));
	if (LightBlueprint.Object){
		lightClass = (UClass*)LightBlueprint.Object->GeneratedClass;

	}
	this->RootComponent->SetMobility(EComponentMobility::Static);

}

void ABSPLevelGenerator::ChangeGridViaAlgorithym()
{
	SplitDirection previousSplitDirection = SplitDirectionVertical;
	for (int32 stage = 0; stage < loops; stage++)
	{

		roomArray.Add(BSPRoomArray());
		//If this is the first stage we need to initialize the first room
		if (stage == 0)
		{
			//first stage
			FRect firstRoom = FRect(GridSize.width, GridSize.height, 0, 0);
			TArray<FRect> newRooms = SplitRoomRandomly(firstRoom, previousSplitDirection, stage);
			roomArray[stage].rooms.Add(newRooms[0]);
			roomArray[stage].rooms.Add(newRooms[1]);
		}
		else
		{
			//take the rooms from the previous stage and split them randomly to create this stage
			for (int32 i = 0; i < roomArray[stage - 1].rooms.Num(); i++)
			{
				FRect room = roomArray[stage - 1].rooms[i];
				TArray<FRect> newRooms = SplitRoomRandomly(room, previousSplitDirection, stage);
				roomArray[stage].rooms.Add(newRooms[0]);
				roomArray[stage].rooms.Add(newRooms[1]);
			}
		}
		//Switch split direction
		if (previousSplitDirection == SplitDirectionHorizontal)
		{
			previousSplitDirection = SplitDirectionVertical;
		}
		else
		{
			previousSplitDirection = SplitDirectionHorizontal;
		}

	}
	FString theString = "";
	//Loop through the final stage to get the final rooms, then randomly determine the size of the room
	for (int32 j = 0; j < roomArray[loops-1].rooms.Num(); j++)
	{
		FRect room = roomArray[loops - 1].rooms[j];
		float randomHeight = RandomIntBetweenFloats(3.0f, room.height - 1);
		float randomWidth = RandomIntBetweenFloats(3.0f, room.width - 1);
		if (randomHeight/randomWidth >3.5)
		{
			randomHeight = RandomIntBetweenFloats(3.0f, room.height/1.7f - 1);
		}
		else if (randomWidth / randomHeight >3.5)
		{
			randomWidth = RandomIntBetweenFloats(3.0f, room.width/ 1.7f - 1);
		}

		float maxX = room.x + room.width-1-randomWidth;
		float maxY = room.y + room.height-1
			- randomHeight;
		float randomX = RandomIntBetweenFloats(room.x, maxX);
		float randomY = RandomIntBetweenFloats(room.y, maxY);

		FRect finalRoom = FRect(randomWidth, randomHeight, randomX, randomY);
		//This array is filled with the final hollow rooms.
		finalRoomArray.Add(finalRoom);
		//FRect finalRoom = FRect(room.width - 2, room.height - 2, room.x + 1, room.y + 1);
		FillOutRoom(finalRoom);
		//just some debug stuff
		theString = theString + FString::SanitizeFloat(finalRoom.width) + "," + FString::SanitizeFloat(finalRoom.height) + "," + FString::SanitizeFloat(finalRoom.x) + "," + FString::SanitizeFloat(finalRoom.y) + "::";
		//GEngine->AddOnScreenDebugMessage(-9, 5.f, FColor::Red, theString);
	}

	//Make the connections
	for (int32 k = 0; k < roomArray[loops - 1].rooms.Num(); k++)
	{
		//first one connects to nothing
		if (k==0)
		{

		}
		else
		{
			FRect room = roomArray[loops - 1].rooms[k];
			//get the last room
			FRect lastRoom = roomArray[loops - 1].rooms[k - 1];
			bool isCoordinate1Floor = true;
			bool isCoordinate2Floor = true;
			FVector2D startCoordinate = FVector2D();
			FVector2D destinationCoordinate = FVector2D();

			while (isCoordinate1Floor)
			{
				startCoordinate = RandomPositionInRect(room);
				if (LevelCellForGridCoordinate(startCoordinate)->Type==FLevelCell::LevelCellTypeFloor)
				{
					isCoordinate1Floor = false;
				}
			}

			while (isCoordinate2Floor)
			{
				destinationCoordinate = RandomPositionInRect(lastRoom);
				if (LevelCellForGridCoordinate(destinationCoordinate)->Type == FLevelCell::LevelCellTypeFloor)
				{
					isCoordinate2Floor = false;
				}
			}

			MakePathBetweenCoords(startCoordinate, destinationCoordinate);
		}
	}

	/*Set the walls*/
	for (int32 x = 0; x < GridSize.width; x++)
	{
		for (int32 y = 0; y < GridSize.height; y++)
		{
			if (x == 0 || y == 0 /*|| x == GridSize.width - 1 || GridSize.height - 1*/)
			{
				grid[x].columns[y]->Type = FLevelCell::LevelCellTypeWall;
			}
		}

	}

	//Loop through the final hollow rooms, populate them, if they are big we need some lights
	for (int32 index = 0; index < finalRoomArray.Num(); index++)
	{
		FRect finalRoom = finalRoomArray[index];
		if (finalRoom.height>3 && finalRoom.width>3)
		{
			//WE need some lights

			for (int32 x = 0; x < finalRoom.width-3; x++)
			{
				if (x%3==0)
				{
					for (int32 y = 0; y < finalRoom.height - 3; y++)
					{
						if (y % 3 == 0)
						{
							FVector2D gridCoordinate = FVector2D(finalRoom.x + 1 + x, finalRoom.y + 1 + y);
							FVector spawnVector = VectorForGridCoordinate(gridCoordinate);
							spawnVector.Z = spawnVector.Z + 400.0f;

							FActorSpawnParameters SpawnInfo;

							//SET NO COLLISION FAIL TO TRUE
							SpawnInfo.bNoCollisionFail = true;

							SpawnInfo.Owner = this;
							AActor *ceilingLightActor = SpawnBP<AActor>(GetWorld(), ceilingLightClass, spawnVector, FRotator(0, 0, 0));
							ceilingLightActor->AttachRootComponentToActor(this);
						}

					}
				}
			}
		}
	}

	//Choose Start and exit
	//NEEDS FIXING SPAWN WAY TO CLOSE
	/*FVector2D randomStart;
	FVector2D randomExit;
	bool isRandomStartGood = false;
	bool isRandomExitGood = false;
	while (!isRandomStartGood)
	{
		int32 randomX = RandomIntBetweenFloats(GridSize.width-1, 0.0);
		int32 randomY = RandomIntBetweenFloats(GridSize.height-1, 0.0);
		if (LevelCellForGridCoordinate(FVector2D(randomX,randomY))->Type == FLevelCell::LevelCellTypeFloor)
		{
			randomStart = FVector2D(randomX, randomY);
			isRandomStartGood = true;
		}
	}
	FVector vect = VectorForGridCoordinate(randomStart);
	vect.X = vect.X + 96.0;
	vect.Y = vect.Y + 96.0;

	AActor *playerStart = SpawnBP<AActor>(GetWorld(), startClass, vect, FRotator(0, 0, 0));
	playerStart->AttachRootComponentToActor(this);
	while (!isRandomExitGood)
	{
		int32 randomX = RandomIntBetweenFloats(GridSize.width-1, 0.0);
		int32 randomY = RandomIntBetweenFloats(GridSize.height-1, 0.0);
		if (LevelCellForGridCoordinate(FVector2D(randomX, randomY))->Type == FLevelCell::LevelCellTypeFloor && (randomExit-randomStart).Size()>40)
		{
			randomExit = FVector2D(randomX, randomY);
			isRandomExitGood = true;
		}
	}

	FVector spawnVector = VectorForGridCoordinate(randomExit);

	FActorSpawnParameters SpawnInfo;

	//SET NO COLLISION FAIL TO TRUE
	SpawnInfo.bNoCollisionFail = true;

	SpawnInfo.Owner = this;
	AActor *exitActor = SpawnBP<AActor>(GetWorld(), exitClass, spawnVector, FRotator(0, 0, 0));
	exitActor->AttachRootComponentToActor(this);*/

}

TArray<FRect> ABSPLevelGenerator::SplitRoomRandomly(FRect room, SplitDirection previousSplitDirection, int32 stage)
{
	FRect room1 = FRect();
	FRect room2 = FRect();
	//Check wich way to split
	if (previousSplitDirection == SplitDirectionHorizontal)
	{
		//some numbers for the random generator
		float maxHeight = room.y + room.height;
		float splitPoint = 0.0f;
		bool isSplitPointGood = true;

		//some numbers to determine the perfect middle and then the max and min split points, so we dont get really small rooms TODO DOC
		int32 rootNum = stage / 2;
		rootNum++;
		int32 perfectMiddle = GridSize.height / pow(2.0f, rootNum);
		int32 minSplitPoint = perfectMiddle / 2 + room.y;
		int32 maxSplitPoint = minSplitPoint + perfectMiddle*1.5;
		int32 count = 0;
		while (isSplitPointGood)
		{
			splitPoint = floor((RandomFloatBetween0and1()*(maxHeight - room.y + 1.0f)) + room.y);
			if (splitPoint >= minSplitPoint && splitPoint <= maxSplitPoint && maxHeight-splitPoint>perfectMiddle/2)
			{
				isSplitPointGood = false;
				GEngine->AddOnScreenDebugMessage(-7, 5.f, FColor::Red, "isgood");
			}
			GEngine->AddOnScreenDebugMessage(-8, 5.f, FColor::Red, FString::SanitizeFloat(splitPoint));
			if (count == 100)
			{
				splitPoint = room.x + perfectMiddle / 2.0f;
				isSplitPointGood = false;
			}
			count++;
		}

		GEngine->AddOnScreenDebugMessage(-6, 5.f, FColor::Red, FString::FromInt(perfectMiddle) + "," + FString::FromInt(minSplitPoint) + "," + FString::FromInt(maxSplitPoint) + "," + FString::FromInt(splitPoint) + "," + FString::FromInt(rootNum)+"," + FString::FromInt(floor(pow(64.0f, (1/2)))));
		 room1 = FRect(room.width, splitPoint - room.y, room.x, room.y);
		 room2 = FRect(room.width, maxHeight - splitPoint, room.x, splitPoint);
		GEngine->AddOnScreenDebugMessage(-4, 5.f, FColor::Red, "Room1:" + FString::SanitizeFloat(room1.width) + "," + FString::SanitizeFloat(room1.height) + "," + FString::SanitizeFloat(room1.x) + "," + FString::SanitizeFloat(room1.y));
		GEngine->AddOnScreenDebugMessage(-5, 5.f, FColor::Red, "Room2:" + FString::SanitizeFloat(room1.width) + "," + FString::SanitizeFloat(room1.height) + "," + FString::SanitizeFloat(room1.x) + "," + FString::SanitizeFloat(room1.y));
	}
	else
	{
		float maxHeight = room.x + room.width;
		float splitPoint = 0.0f;
		bool isSplitPointGood2 = true;

		stage++;
		int32 rootNum = stage / 2;
		rootNum++;
		int32 perfectMiddle = GridSize.width / pow(2.0f, rootNum);
		int32 minSplitPoint = perfectMiddle / 2 + room.x;
		int32 maxSplitPoint = minSplitPoint + perfectMiddle*1.5;
		int32 count = 0;

		while (isSplitPointGood2)
		{
			splitPoint = floor((RandomFloatBetween0and1()*(maxHeight - room.x + 1.0f)) + room.x);
			if (splitPoint >= minSplitPoint && splitPoint <= maxSplitPoint && maxHeight - splitPoint>perfectMiddle / 2)
			{
				isSplitPointGood2 = false;
				GEngine->AddOnScreenDebugMessage(-7, 5.f, FColor::Red, "isgood");
			}
			GEngine->AddOnScreenDebugMessage(-8, 5.f, FColor::Red, FString::SanitizeFloat(splitPoint));
			if (count == 100)
			{
				splitPoint = room.x + perfectMiddle / 2.0f;
				isSplitPointGood2 = false;
			}
			count++;
		}
		GEngine->AddOnScreenDebugMessage(-6, 5.f, FColor::Red, FString::FromInt(perfectMiddle) + "," + FString::FromInt(minSplitPoint) + "," + FString::FromInt(maxSplitPoint) + "," + FString::FromInt(splitPoint) + "," + FString::FromInt(rootNum) + "," + FString::FromInt(floor(pow(64.0f, (1 / 2)))));
		room1 = FRect(splitPoint - room.x, room.height, room.x, room.y);
		room2 = FRect(maxHeight - splitPoint, room.height, splitPoint, room.y);
		GEngine->AddOnScreenDebugMessage(-4, 5.f, FColor::Red, "Room1:" + FString::SanitizeFloat(room1.width) + "," + FString::SanitizeFloat(room1.height) + "," + FString::SanitizeFloat(room1.x) + "," + FString::SanitizeFloat(room1.y));
		GEngine->AddOnScreenDebugMessage(-5, 5.f, FColor::Red, "Room2:" + FString::SanitizeFloat(room1.width) + "," + FString::SanitizeFloat(room1.height) + "," + FString::SanitizeFloat(room1.x) + "," + FString::SanitizeFloat(room1.y));
	}
	TArray<FRect> endRooms = TArray<FRect>();
	endRooms.Add(room1);
	endRooms.Add(room2);
	return endRooms;
}

//Make the given set of coordinates floor cells
void ABSPLevelGenerator::FillOutRoom(FRect room)
{
	for (int32 x = room.x; x < room.width+room.x; x++)
	{
		for (int32 y = room.y; y < room.height+room.y; y++)
		{
			grid[x].columns[y]->Type = FLevelCell::LevelCellTypeFloor;
		}
	}
}

int32 ABSPLevelGenerator::RandomIntBetweenFloats(float float1, float float2)
{
	return floor(RandomFloatBetween0and1()*(float2 - float1 + 1.0f) + float1);
}

FVector2D ABSPLevelGenerator::RandomPositionInRect(FRect rect)
{
	float maxX = rect.x + rect.width;
	float maxY = rect.y + rect.height;
	return FVector2D(RandomIntBetweenFloats(rect.x, maxX-1), RandomIntBetweenFloats(rect.y, maxY-1));
}

void ABSPLevelGenerator::MakePathBetweenCoords(FVector2D start, FVector2D end)
{

	if (start.X > end.X)
	{
		for ( float x = start.X;  x >= end.X;  x--)
		{
			LevelCellForGridCoordinate(FVector2D(x, start.Y))->Type = FLevelCell::LevelCellTypeFloor;
		}
	}
	else
	{
		for (float x = start.X; x <= end.X; x++)
		{
			LevelCellForGridCoordinate(FVector2D(x, start.Y))->Type = FLevelCell::LevelCellTypeFloor;
		}
	}
	if (start.Y > end.Y)
	{
		for (float y = start.Y; y >= end.Y; y--)
		{
			LevelCellForGridCoordinate(FVector2D(end.X, y))->Type = FLevelCell::LevelCellTypeFloor;
		}
	}
	else
	{
		for (float y = start.Y; y <= end.Y; y++)
		{
			LevelCellForGridCoordinate(FVector2D(end.X, y))->Type = FLevelCell::LevelCellTypeFloor;
		}
	}
}

//Set everything default to wall
void ABSPLevelGenerator::InitializeArray(UWorld *world)
{
	for (int32 x = 0; x < GridSize.width; x++)
	{

		grid.Add(UBSPGridRow());
		for (int32 y = 0; y < GridSize.height; y++)
		{

			FBSPLevelCell* cell = new FBSPLevelCell();
			//UGameplayStatics::FinishSpawningActor(cell, FTransform());
			//double random = ((double)rand() / (RAND_MAX));
			cell->Type = FBSPLevelCell::LevelCellTypeWall;
			cell->GridCoordinate = FVector2D(x, y);

			grid[x].columns.Add(cell);
		}

	}
}

//finally create the static meshes
void ABSPLevelGenerator::CreateStaticMeshes()
{
	FActorSpawnParameters SpawnInfo;
	SpawnInfo.Owner = this;

	//SET NO COLLISION FAIL TO TRUE
	SpawnInfo.bNoCollisionFail = true;

	//SpawnInfo.Owner = this;

	ABSPWallStaticMeshActor* wallActor =
		GetWorld()->SpawnActor<ABSPWallStaticMeshActor>(
		ABSPWallStaticMeshActor::StaticClass(),
		this->GetActorLocation(),
		FRotator::ZeroRotator,
		SpawnInfo
		);
	if (!wallActor)                    return;
	if (!wallActor->InstancedStaticMeshComponent)   return;
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	//Mesh
	wallActor->InstancedStaticMeshComponent->SetStaticMesh(wallMesh);
	//wallActor->AttachRootComponentToActor(this);
	//Add Core Instance
	/*FTransform newT = NewVertex->GetTransform();
	newT.SetLocation(FVector(0, 0, 0));
	NewVertex->InstancedStaticMeshComponent->AddInstance(newT);*/

	//Scale
	//wallActor->SetActorRelativeScale3D(this->GetActorScale3D());

	for (int32 x = 0; x < GridSize.width; x++)
	{

		for (int32 y = 0; y <GridSize.height; y++)
		{

			if (LevelCellForGridCoordinate(FVector2D(x, y))->Type == FLevelCell::LevelCellTypeWall)
			{

				FTransform newT = wallActor->GetTransform();
				newT.SetLocation(VectorForGridCoordinate(FVector2D(x, y)));
				//if (x == 0 && y < 3)
				wallActor->InstancedStaticMeshComponent->AddInstance(newT);
				//GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "Test2");

				FBSPLevelCell* celli = LevelCellForGridCoordinate(FVector2D(x, y));
				//GEngine->AddOnScreenDebugMessage(-2, 5.f, FColor::Red, "Test3");
				//Array for which tiles are floors in this order: W, E, N, S

				celli->center = this->GetActorLocation();
				//celli->createStaticMeshWithGrid(floors, lightClass);
				//Create wall lights
				CreateWallLight(celli);
			}

		}

	}
}

FBSPLevelCell* ABSPLevelGenerator::LevelCellForGridCoordinate(FVector2D Coordinate)
{
	if (IsValidGridCoordinate(Coordinate))
	{
		FBSPLevelCell* cell = grid[Coordinate.X].columns[Coordinate.Y];
		return cell;
	}
	return NULL;
}

//Turn string into a number
int32 ABSPLevelGenerator::getSeedForString(FString seed)
{

	 char* String[300];
	for (int32 i = 0; i < seed.GetCharArray().Num(); i++)
	{
		String[i] = (char*)seed.GetCharArray()[i];
	}
	int32 seed2 = 0;
	for (int32 j = 0; j < seed.GetCharArray().Num(); j++)
	{
		seed2 += (int32)String[j];
	}

	return seed2;
}
void ABSPLevelGenerator::openMap()
{

	FURL url = FURL();
	url.Map = "E:\\Copy\\Unreal Projects\\PLGTest\\Content\\test.umap";
	//url.Protocol = "unreal";
	FWorldContext context = FWorldContext();
	context.SetCurrentWorld(GetWorld());
	FString error;
	GetWorld()->CleanupWorld();
	GetWorld()->ForceGarbageCollection();
	GetWorld()->RemoveFromRoot();
	UGameplayStatics::OpenLevel(GetWorld(), "test", true);
	//GEngine->LoadMap(context, url, nullptr, error);
}

void ABSPLevelGenerator::GenerateLevelWithSeed(int32 seed)
{
	//GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "Level Generation Started!");

	//UWorld*  World = GetWorld();
	//const float startTime = World->GetTimeSeconds();
	srand(seed);
	InitializeArray(GetWorld());

	ChangeGridViaAlgorithym();

	//const float endTime = World->GetTimeSeconds();
	//float time = endTime - startTime;
	CreateStaticMeshes();
	IsValidGridCoordinate(FVector2D(0, 0));
	//	GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "Level Generation Finished in "+FString::SanitizeFloat(time)+" Secconds!");

	//this->SetActorRotation(FRotator(0,45,0));

}

void ABSPLevelGenerator::CreateWallLight(FBSPLevelCell *cell)
{
	int32 x = cell->GridCoordinate.X;
	int32 y = cell->GridCoordinate.Y;
	UWorld *TheWorld = GetWorld();
	TArray<bool> floors;

	for (int32 i = 0; i < 6; i++)
	{
		floors.Add(false);
	}
	if (x != 0)
	{
		floors[0] = (LevelCellForGridCoordinate(FVector2D(x - 1, y))->Type == FLevelCell::LevelCellTypeFloor);
	}

	if (x != 79)
	{
		floors[1] = (LevelCellForGridCoordinate(FVector2D(x + 1, y))->Type == FLevelCell::LevelCellTypeFloor);
	}

	if (y != 0)
	{
		floors[2] = (LevelCellForGridCoordinate(FVector2D(x, y - 1))->Type == FLevelCell::LevelCellTypeFloor);
	}

	if (y != 79)
	{
		floors[3] = (LevelCellForGridCoordinate(FVector2D(x, y + 1))->Type == FLevelCell::LevelCellTypeFloor);
	}
	float randomZ = floor(((double)rand() / (RAND_MAX)) *(396.0f / 1.8 - 396.0f / 2.1 + 1.0f) + 396.0f / 2.1);
	float randomX = floor(((double)rand() / (RAND_MAX)) *(192.0f / 1.5 - 192.0f / 2.5 + 1.0f) + 192.0f / 2.5);
	bool should = false;

	if (x % 2 == 0 && y % 2 == 0)
	{
		should = true;
	}
	if (x % 2 == 1 && y % 2 == 1)
	{
		should = true;
	}

	if (should)
	{
		if (x != 0)
		{

			if (floors[0])
			{

				FVector Loc = FVector(VectorForGridCoordinate(FVector2D(x, y)));
				Loc.X += randomX;
				Loc.Z += randomZ;
				Loc.Y -= 192.0f;
				FRotator Rot = FRotator(0, -90, 0);

				GEngine->AddOnScreenDebugMessage(-7, 10, FColor::Red, "Hello");
				AActor * lightActor = SpawnBP<AActor>(TheWorld, lightClass, Loc, Rot);

			}
		}

		if (x != 79)
		{

			if (floors[1])
			{

				FVector Loc = FVector(VectorForGridCoordinate(FVector2D(x, y)));
				FRotator Rot = FRotator(0, -270, 0);
				Loc.X += randomX;
				Loc.Z += randomZ;

				AActor * lightActor = SpawnBP<AActor>(TheWorld, lightClass, Loc, Rot);

			}
		}
		if (y != 0)
		{

			if (floors[2])
			{

				FVector Loc = FVector(VectorForGridCoordinate(FVector2D(x, y)));
				FRotator Rot = FRotator(0, 180, 0);
				Loc.Y -= randomX;
				Loc.Z += randomZ;

				AActor * lightActor = SpawnBP<AActor>(TheWorld, lightClass, Loc, Rot);

			}
		}

		if (y != 79)
		{

			if (floors[3])
			{

				FVector Loc = FVector(VectorForGridCoordinate(FVector2D(x, y)));
				FRotator Rot = FRotator(0, 0, 0);
				Loc.Y -= randomX;
				Loc.Z += randomZ;
				Loc.X += 192.0f;

				AActor * lightActor = SpawnBP<AActor>(TheWorld, lightClass, Loc, Rot);

			}
		}
	}
}


text:
//
//  Convolver.hpp
//  laproque - https://github.com/Buerner/laproque
//
//  Copyright © 2017 Martin Bürner. All rights reserved.
//  Licensed under the MIT License. See LICENSE.md file in the project root for full license information.
//

#ifndef Convolver_hpp
#define Convolver_hpp

#include <stdio.h>
#include <fftw3.h>
#include <atomic>

#include "complexmath.hpp"
#include "FFThelper.hpp"

namespace laproque {

// TODO: The _freq_resp_parts array must be thread safe because
// replacing could interfere with the audio porcessing. Maybe write a
// threadsafe array class and overload braces operator.
/**
 * @brief Partitioned fast convolution class.
 *
 * Class which computes the convolution of and input buffer with an impulse response passed on initialization of instance. It uses the partitioned convolution approach to allow the use in blockwise audio processing.
 * On initialization just pass your impulse response, its size and the size of the partitiones.
 */
class Convolver
{
public:
    /**
     * @brief Construtor for convolver instance with desired impulse response.
     * @param imp_resp Pointer to the impulse response you want to use.
     * @param n_samples Length of the impulse response in samples.
     * @param block_size Size of the processing blocks i.e. partitions.
     */
    Convolver(float* imp_resp, unsigned long n_samples, unsigned block_size);

    /**
     * Copy constructor.
     */
    Convolver( Convolver& conv );

    virtual ~Convolver();

    /**
     * @brief Function which computes the convolution result.

     * Note that the size of input and outputs equals the block_size chosen on initialization.
     * @param in_buffer Input data with size of block_size.
     * @param out_buffer Output data with size of block_size.
     */
    virtual void process( float* in_buffer, float* out_buffer );

    /**
     * @brief Replace frequency response.
     *
     * This functions overwrites the currently frequency response which is currently set. It expects correctly patitioned blocks in the frequency domain.
     */
    void set_freq_response( fftwf_complex* new_response );

    /**
     * @brief Set time domain input buffer to 0.
     *
     * As the class processes multiple blocks, the input needs to be stored to comply with the partitiond convolution pricipal. When you want to use a Convolver instance for different input signals call this function between processing.
     */
    void reset_input_buffer();

    /**
     * @brief Returns FFT resolution.
     */
    unsigned get_fft_size();

    /**
     * @brief Returns processing block size.
     */
    unsigned get_block_size();

    /**
     * @brief Returns resolution of one partition (fft_size/2 + 1).
     */
    unsigned get_spectrum_size();

    /**
     * @brief Returns size of all frequency domain partitions combined.
     */
    unsigned get_spectra_size();

    /**
     * @brief Returns number of partitions.
     */
    unsigned get_n_parts();

protected:
    /** Length of discrete fourier transform */
    unsigned _fft_size;
    /** Number of frames in on block during block processing. */
    unsigned _block_size;
    /** Number fo complex values in one partition pectrum */
    unsigned _spectrum_size;
    /** Number of complex values in partitions combined */
    unsigned _spectra_size;
    /** Number of partitions. */
    unsigned _n_parts;

    float* _input;
    float* _result;

    fftwf_complex* _input_spectra;
    fftwf_complex* _freq_resp_parts;
    fftwf_complex* _multiply_buffer;
    fftwf_complex* _output_spectr;

    FFThelper _fft;

    /** Takes care of all memory reservations needed for convolution process. */
    void _make_allocations();

    /**
     * @brief Actual fast convolution process
     .
     * Heart of the convolution.
     * Implemented as seperate function to enable derived classes to do additional processing.
     */
    void _fast_conv();

    /**
     * Prepares the frequency response partitions i.e. computes FFT of blocks of the impulse response.
     */
    void _compute_freq_resp( float* imp_resp );

};

} // namespace laproque

#endif /* Convolver_hpp */


text:
<?php

namespace Xcore\Generator\Tests\Data\AssociationMapping;

use Doctrine\ORM\Mapping as ORM;

/**
 * Product2
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Product2
{
    use Product2Trait;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->generatedConstructor();
    }

}


text:
#pragma once

#include <Core/Animation/Pose.hpp>
#include <Core/Types.hpp>

namespace Ra {
namespace Core {
namespace Animation {

/*
 * Return true if the two poses are compatibile with each other.
 * A pose is compatible with another if the size of the two poses are equal.
 *
 * Possible FUTURE WORKS:
 * Two poses are compatible if their size is equal and if their transforms
 * are within the constraints of each others.
 */
RA_CORE_API bool compatible( const Pose& p0, const Pose& p1 );

/*
 * Given a model pose and a compatible rest pose, return the relative pose.
 */
RA_CORE_API Pose relativePose( const Pose& modelPose, const RestPose& restPose );

/*
 * Return the pose resulting in applying the i-th transform to the i-th pose transform.
 *
 * The operation is equal to:
 *           pose[i] = transform[i] * pose[i];
 */
RA_CORE_API Pose applyTransformation( const Pose& pose,
                                      const AlignedStdVector<Transform>& transform );

/*
 * Return the pose resulting in applying the transform to the pose transforms.
 *
 * The operation is equal to:
 *           pose[i] = transform * pose[i];
 */
RA_CORE_API Pose applyTransformation( const Pose& pose, const Transform& transform );

RA_CORE_API bool areEqual( const Pose& p0, const Pose& p1 );

RA_CORE_API Pose interpolatePoses( const Pose& a, const Pose& b, const Scalar t );

} // namespace Animation
} // namespace Core
} // namespace Ra


text:
import bioformats.bed
import bioformats.gff3
from chromosomer.fragment import Map

class Transfer(object):
    """
    Implements transfering routines for abstract data.
    """

    def __init__(self, fragment_map):
        """
        Create a Transfer object.

        :param fragment_map: a fragment map for feature transfer
        :type fragment_map: Map
        """
        self.__fragment_map = Map()
        self.__fragment_map.read(fragment_map)

    def find_fragment(self, fragment):
        """
        Given a fragment name, return its record from the fragment
        map. If the specified fragment is absent in the map, return
        None.

        :param fragment: a fragment name
        :type fragment: str
        :return: a fragment map record corresponding to the specified
            fragment
        :rtype Map.Record
        """
        for chromosome in self.__fragment_map.chromosomes():
            for record in self.__fragment_map.fragments(chromosome):
                if record.fr_name == fragment:
                    return record

        return None

    def coordinate(self, fragment, pos):
        """
        Given a position on a fragment, return the corresponding
        coordinates on the assembled chromosomes according to the
        fragment map specified when the object was created.

        :param fragment: a fragment name
        :param pos: a position on a fragment (zero-based)
        :type fragment: str
        :type pos: int
        :return: a tuple of the chromosome name and a position on it
        :rtype: tuple
        """
        fr_record = self.find_fragment(fragment)
        if fr_record is None:
            # the fragment is absent in the assembly, skip the feature
            return None

        chrom = fr_record.ref_chr
        if fr_record.fr_strand == '+':
            chrom_pos = fr_record.ref_start + pos
        else:
            chrom_pos = fr_record.ref_end - pos

        return chrom, chrom_pos

class BedTransfer(Transfer):
    """
    Implements transferring routines for files in the BED format.
    """
    def feature(self, bed_record):
        """
        Given a record from a BED file, return the transferred one.

        :param bed_record: a line from a BED file
        :type bed_record: bioformats.bed.BedRecord
        :return: a transferred feature
        :rtype: bioformats.bed.BedRecord
        """
        fr_record = self.find_fragment(bed_record.seq)
        if fr_record is None:
            # the fragment is absent in the assembly, skip it
            return None

        chrom = fr_record.ref_chr
        start = self.coordinate(bed_record.seq, bed_record.start)[1]
        end = self.coordinate(bed_record.seq, bed_record.end)[1]

        # determine the transferred feature strand
        if bed_record.strand is not None:
            feature_strand = -1 if bed_record.strand == '-' else 1
            fragment_strand = -1 if bed_record.strand == '-' else 1
            if feature_strand * fragment_strand == -1:
                strand = '-'
            else:
                strand = '+'
        else:
            strand = None

        transferred_record = list(bed_record)
        transferred_record[0] = chrom
        transferred_record[1] = min(start, end)
        transferred_record[2] = max(start, end)
        transferred_record[5] = strand

        return bioformats.bed.Record(*transferred_record)

class Gff3Transfer(Transfer):
    """
    Implements transferring routines for files in the GFF3 format.
    """
    def feature(self, gff3_record):
        """
        Given a record from a GFF3 file, return the transferred one.

        :param gff3_record: a line from a GFF3 file
        :type gff3_record: bioformats.gff3.Gff3Record
        :return: a transferred feature
        :rtype: bioformats.bed.BedRecord
        """
        fr_record = self.find_fragment(gff3_record.seqid)
        if fr_record is None:
            # the fragment is absent in the assembly, skip it
            return None

        chrom = fr_record.ref_chr
        start = self.coordinate(gff3_record.seqid,
                                gff3_record.start - 1)[1]
        end = self.coordinate(gff3_record.seqid, gff3_record.end)[1]

        # determine the transferred feature strand
        if gff3_record.strand != '.':
            feature_strand = -1 if gff3_record.strand == '-' else 1
            fragment_strand = -1 if gff3_record.strand == '-' else 1
            if feature_strand * fragment_strand == -1:
                strand = '-'
            else:
                strand = '+'
        else:
            strand = '.'

        transferred_record = list(gff3_record)
        transferred_record[0] = chrom
        transferred_record[3] = min(start, end) + 1
        transferred_record[4] = max(start, end)
        transferred_record[6] = strand

        return bioformats.gff3.Record(*transferred_record)

class VcfTransfer(Transfer):
    """
    Implements transferring routines for files in the VCF format.
    """
    def feature(self, vcf_record):
        """
        Given a record from a VCF file, return the transferred one.

        :param vcf_record: a variant record
        :type vcf_record: vcf.model._Record
        :return: a transferred variant
        :rtype: vcf.model._Record
        """
        fr_record = self.find_fragment(vcf_record.CHROM)
        if fr_record is None:
            # the fragment is absent in the assembly, skip it
            return None

        chrom = fr_record.ref_chr
        pos = self.coordinate(vcf_record.CHROM, vcf_record.POS)[1]

        vcf_record.CHROM = chrom
        vcf_record.POS = pos

        return vcf_record


text:
@interface NewsDetail : UIViewController

@property (nonatomic, strong) NSString *newsTitle;
@property (nonatomic, strong) NSURL *url;

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end


text:
package Armadillo.Communication.Impl.Topic;

public enum EnumTopic
{
    TempTopicName,
    PrivateTopic,
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta charset="utf-8" />
<meta name="generator" content="skuro.tk/0.1 | jekyll/2.0.3" />
<meta name="description" content="Personal Blog of Carlo Sciolla (skuro)" />
<meta name="keywords" content="clojure,java,scala,alfresco,lambdalf,performance,programming,developer,backbase" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://skuro.tk/img/post/sproutcore.png">
<meta name="twitter:title" content="SproutCore encoding gotchas">
<meta name="twitter:description" content="Personal Blog of Carlo Sciolla (skuro)">
<meta name="twitter:creator" content="@skuro">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="SproutCore encoding gotchas">
<meta property="og:description" content="Personal Blog of Carlo Sciolla (skuro)">
<meta property="og:url" content="http://skuro.tk/2010/09/30/sproutcore-encoding-gotchas">
<meta property="og:site_name" content="SKURO! -- Shading lights">

<link rel="stylesheet" href="/stylesheets/bootstrap.min.css" type="text/css" />

<link rel="stylesheet" href="/stylesheets/skuro.css" type="text/css" />

<title>SproutCore encoding gotchas @ SKURO! -- Shading lights</title>

                SKURO!

Archive

Categories

About me

                            <button type="button" class="btn btn-default"></button>
                            <button type="button" class="btn btn-default"></button>
                            <button type="button" class="btn btn-default"></button>
                            <button type="button" class="btn btn-default"></button>

      Crampi alla lingua

      Performance boost in Clojure 1.3 (alpha4)

    SproutCore encoding gotchas

    September 30, 2010

    #javascript

These days I'm trying out SproutCore, an MVC framework written in Javascript that aims to help developing rich client web applications. I'm not going to entertain you with any juicy technical spotlight, as they'll hopefully find their way in these pages later on with plenty of details. At the moment I'd like to share a little problem I got stuck with that had a non trivial solution,  at least for the noob I am.

First thing you have to know is that SproutCore ships with both a rich Javascript library and a set of building tools written in ruby, which go under the code name of abbot. New projects kickstart, scaffolding, automatic documentation are among the features that abbot provides you with, along with the ability to run you application on a local web server during development. Sounds cool, isn't it? And I didn't even mention it's integrated unit testing facility!

I immediately tried to give it a shot, and ran through one of the tutorials to write down my first HelloWorld. The first pieces got into place, and after the first quick round I left my hello world project in such a state that I already decided to build a simple but complete application right away. How arrogant.

The second day something Bad™ happened, I cannot really tell what, but everything started to fall apart: no one tool in the abbot suite worked properly, I was no more able to get any further and I started a painful journey of which I only remember installing and changing between zillions of ruby versions, crying and considering to give up with IT and to start my own religion to make a living.

But then I simply resorted to the #sproutcore IRC channel and I got the tip that saved the day (thanks pjmorse!):

export LC_CTYPE=UTF-8

"Boom baby!" I said, everything got back to normality. I can save my holy plans for a rainy day. It seems that encoding is an endless source of issues in the ruby world, so that probably if you have any ruby knowledge whatsoever this all rant might just seem pointless and the solution trivial.

Next episode on SproutCore (if everything goes well): a sample SproutCore + Clojure application. See you there!

Please enable JavaScript to view the comments powered by Disqus.
blog comments powered by Disqus

              SKURO! blog by

                Carlo Sciolla

              All text licensed under CC BY 3.0

              All code licensed under MIT unless otherwise specified


text:
/*
-------------------------------------------------------------------------------
lookup3.c, by Bob Jenkins, May 2006, Public Domain.

These are functions for producing 32-bit hashes for hash table lookup.
hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
are externally useful functions.  Routines to test the hash are included
if SELF_TEST is defined.  You can use this free for any purpose.  It's in
the public domain.  It has no warranty.

You probably want to use hashlittle().  hashlittle() and hashbig()
hash byte arrays.  hashlittle() is is faster than hashbig() on
little-endian machines.  Intel and AMD are little-endian machines.
On second thought, you probably want hashlittle2(), which is identical to
hashlittle() except it returns two 32-bit hashes for the price of one.
You could implement hashbig2() if you wanted but I haven't bothered here.

If you want to find a hash of, say, exactly 7 integers, do
  a = i1;  b = i2;  c = i3;
  mix(a,b,c);
  a += i4; b += i5; c += i6;
  mix(a,b,c);
  a += i7;
  final(a,b,c);
then use c as the hash value.  If you have a variable length array of
4-byte integers to hash, use hashword().  If you have a byte array (like
a character string), use hashlittle().  If you have several byte arrays, or
a mix of things, see the comments above hashlittle().

Why is this so big?  I read 12 bytes at a time into 3 4-byte integers,
then mix those integers.  This is fast (you can do a lot more thorough
mixing with 12*3 instructions on 3 integers than you can with 3 instructions
on 1 byte), but shoehorning those bytes into integers efficiently is messy.
-------------------------------------------------------------------------------
Original code by Bob Jenkins. Modified by the LISPmob project.
*/
#define SELF_TEST 1

#include <stdio.h>      /* defines printf for tests */
#include <time.h>       /* defines time_t for timings in the test */
#include <stdint.h>     /* defines uint32_t etc */
#include <sys/param.h>  /* attempt to define endianness */
#ifdef linux
# include <endian.h>    /* attempt to define endianness */
#endif

/*
 * My best guess at if you are big-endian or little-endian.  This may
 * need adjustment.
 */
#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
     __BYTE_ORDER == __LITTLE_ENDIAN) || \
    (defined(i386) || defined(__i386__) || defined(__i486__) || \
     defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))
# define HASH_LITTLE_ENDIAN 1
# define HASH_BIG_ENDIAN 0
#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \
       __BYTE_ORDER == __BIG_ENDIAN) || \
      (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
# define HASH_LITTLE_ENDIAN 0
# define HASH_BIG_ENDIAN 1
#else
# define HASH_LITTLE_ENDIAN 0
# define HASH_BIG_ENDIAN 0
#endif

#define hashsize(n) ((uint32_t)1<<(n))
#define hashmask(n) (hashsize(n)-1)
#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))

/*
-------------------------------------------------------------------------------
mix -- mix 3 32-bit values reversibly.

This is reversible, so any information in (a,b,c) before mix() is
still in (a,b,c) after mix().

If four pairs of (a,b,c) inputs are run through mix(), or through
mix() in reverse, there are at least 32 bits of the output that
are sometimes the same for one pair and different for another pair.
This was tested for:
* pairs that differed by one bit, by two bits, in any combination
  of top bits of (a,b,c), or in any combination of bottom bits of
  (a,b,c).
* "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
  the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
  is commonly produced by subtraction) look like a single 1-bit
  difference.
* the base values were pseudorandom, all zero but one bit set, or
  all zero plus a counter that starts at zero.

Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
satisfy this are
    4  6  8 16 19  4
    9 15  3 18 27 15
   14  9  3  7 17  3
Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
for "differ" defined as + with a one-bit base and a two-bit delta.  I
used http://burtleburtle.net/bob/hash/avalanche.html to choose
the operations, constants, and arrangements of the variables.

This does not achieve avalanche.  There are input bits of (a,b,c)
that fail to affect some output bits of (a,b,c), especially of a.  The
most thoroughly mixed value is c, but it doesn't really even achieve
avalanche in c.

This allows some parallelism.  Read-after-writes are good at doubling
the number of bits affected, so the goal of mixing pulls in the opposite
direction as the goal of parallelism.  I did what I could.  Rotates
seem to cost as much as shifts on every machine I could lay my hands
on, and rotates are much kinder to the top and bottom bits, so I used
rotates.
-------------------------------------------------------------------------------
*/
#define mix(a,b,c) \
{ \
  a -= c;  a ^= rot(c, 4);  c += b; \
  b -= a;  b ^= rot(a, 6);  a += c; \
  c -= b;  c ^= rot(b, 8);  b += a; \
  a -= c;  a ^= rot(c,16);  c += b; \
  b -= a;  b ^= rot(a,19);  a += c; \
  c -= b;  c ^= rot(b, 4);  b += a; \
}

/*
-------------------------------------------------------------------------------
final -- final mixing of 3 32-bit values (a,b,c) into c

Pairs of (a,b,c) values differing in only a few bits will usually
produce values of c that look totally different.  This was tested for
* pairs that differed by one bit, by two bits, in any combination
  of top bits of (a,b,c), or in any combination of bottom bits of
  (a,b,c).
* "differ" is defined as +, -, ^, or ~^.  For + and -, I transformed
  the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
  is commonly produced by subtraction) look like a single 1-bit
  difference.
* the base values were pseudorandom, all zero but one bit set, or
  all zero plus a counter that starts at zero.

These constants passed:
 14 11 25 16 4 14 24
 12 14 25 16 4 14 24
and these came close:
  4  8 15 26 3 22 24
 10  8 15 26 3 22 24
 11  8 15 26 3 22 24
-------------------------------------------------------------------------------
*/
#define final(a,b,c) \
{ \
  c ^= b; c -= rot(b,14); \
  a ^= c; a -= rot(c,11); \
  b ^= a; b -= rot(a,25); \
  c ^= b; c -= rot(b,16); \
  a ^= c; a -= rot(c,4);  \
  b ^= a; b -= rot(a,14); \
  c ^= b; c -= rot(b,24); \
}

/*
--------------------------------------------------------------------
 This works on all machines.  To be useful, it requires
 -- that the key be an array of uint32_t's, and
 -- that the length be the number of uint32_t's in the key

 The function hashword() is identical to hashlittle() on little-endian
 machines, and identical to hashbig() on big-endian machines,
 except that the length has to be measured in uint32_ts rather than in
 bytes.  hashlittle() is more complicated than hashword() only because
 hashlittle() has to dance around fitting the key bytes into registers.
--------------------------------------------------------------------
*/
uint32_t hashword(
const uint32_t *k,                   /* the key, an array of uint32_t values */
size_t          length,               /* the length of the key, in uint32_ts */
uint32_t        initval)         /* the previous hash, or an arbitrary value */
{
    uint32_t a, b, c;

    /* Set up the internal state */
    a = b = c = 0xdeadbeef + (((uint32_t) length) << 2) + initval;

    /*------------------------------------------------- handle most of the key */
    while (length > 3) {
        a += k[0];
        b += k[1];
        c += k[2];
        mix(a, b, c);
        length -= 3;
        k += 3;
    }

    /*------------------------------------------- handle the last 3 uint32_t's */
    switch (length) { /* all the case statements fall through */
    case 3:
        c += k[2];
    case 2:
        b += k[1];
    case 1:
        a += k[0];
        final(a, b, c);
    case 0: /* case 0: nothing left to add */
        break;
    }
    /*------------------------------------------------------ report the result */
    return c;
}


text:
Brochard
========

Orchard CMS running on ASP.Net VNext (DNX)

Getting Started
---------------

First off, follow the instructions here https://github.com/aspnet/home inorder to install DNVM. Next install Visual Studio 2015, or what ever you flavour of editor is.

Next you want to clone the Repo. 'git clone https://github.com/OrchardCMS/Brochard.git' and checkout the master branch.

Run the bootstrap.cmd file included in the repository to bootstrap dnx.

Load up the solution in Visual studio and do a compile.

Next navigate to 'D:\Brochard\src\OrchardVNext.Web' or where ever your retrospective folder is on the command line in Administrative mode.

run.. 'dnx . web' -> Hey you just kicked up the Orchard host.

Then in your browser, call the url... http://local.orchardvnext.test1.com/setup/index

Note:
You may need to add local.orchardvnext.test1.com to your host file.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using SQMReorderer.Gui.Command;
using SQMReorderer.Gui.Dialogs;
using SQMReorderer.Gui.Dialogs.AddInit;

namespace SQMReorderer.Gui.ViewModels.ArmA2
{
    public class CombinedVehicleViewModel : ViewModelBase, ICombinedVehicleViewModel
    {
        private readonly List<VehicleViewModel> _vehicles;
        private readonly IAddInitDialogFactory _addInitDialogFactory;

        public CombinedVehicleViewModel(List<VehicleViewModel> vehicles, IAddInitDialogFactory addInitDialogFactory)
        {
            _vehicles = vehicles;
            _addInitDialogFactory = addInitDialogFactory;
            AddInitCommand = new DelegateCommand(AddInit);
        }

        public DelegateCommand AddInitCommand { get; private set; }

        public string VehicleName
        {
            get { return GetCombinedValue(x => x.VehicleName); }
            set { Set(value, () => VehicleName, () => SetCombinedValue(x => x.VehicleName = value)); }
        }

        public string Rank
        {
            get { return GetCombinedValue(x => x.Rank); }
            set { SetCombinedValue(x => x.Rank = value); }
        }

        public string Text
        {
            get { return GetCombinedValue(x => x.Text); }
            set { SetCombinedValue(x => x.Text = value); }
        }

        public string Description
        {
            get { return GetCombinedValue(x => x.Description); }
            set { Set(value, () => Description, () => SetCombinedValue(x => x.Description = value)); }
        }

        public string Init
        {
            get { return GetCombinedValue(x => x.Init); }
            set { Set(value, () => Init, () => SetCombinedValue(x => x.Init = value)); }
        }

        private string GetCombinedValue(Func<VehicleViewModel, string> getValueFunc)
        {
            if (_vehicles.Count == 0)
            {
                return null;
            }

            var firstValue = getValueFunc(_vehicles.First());

            if (_vehicles.Any(x => getValueFunc(x) != firstValue))
            {
                return null;
            }

            return firstValue;
        }

        private void SetCombinedValue(Action<VehicleViewModel> setValueFunc)
        {
            _vehicles.ForEach(setValueFunc);
        }

        private void AddInit()
        {
            var addInitDialog = _addInitDialogFactory.Create();
            var addInitResult = addInitDialog.ShowDialog();

            if (addInitResult.DialogResult == DialogResult.Ok)
            {
                SetCombinedValue(x => x.Init += addInitResult.InitToAdd);
                FirePropertyChanged(() => Init);
            }
        }
    }
}


text:
/**
 * MsResultDynamicResidueModDb.java
 * @author Vagisha Sharma
 * Aug 18, 2008
 * @version 1.0
 */
package org.yeastrc.ms.domain.search;

/**
 *
 */
public interface MsResultResidueMod extends MsResidueModificationIn {

    public abstract int getModifiedPosition();

}


text:
package unquietcode.tools.flapi;

import org.junit.Test;

/**
 * @author Ben Fagin
 * @version 04-10-2013
 */
public class TriggeredMethods_T extends AbstractCompiledTest {

	@Test
	public void testBasicTriggeredMethod() {
		Descriptor descriptor = Flapi.builder()
			.setDescriptorName("Something")
			.setPackage("something")

			.addMethod("dynamic()").atMost(1)
			.addMethod("dynamicWithGroup()").atMost(1, 1)
			.addMethod("triggered()").after(1).atLeast(1)
			.addMethod("terminal()").last()
		.build();

		descriptor.writeToFolder(getTemporaryFolder());
		testCompile("TriggeredTest2.avaj");
	}

	@Test
	public void testTriggeredAnyMethod() {
		Descriptor descriptor = Flapi.builder()
			.setDescriptorName("Something")
			.setPackage("something")

			.addMethod("required()").any()
			.addMethod("requiredWithGroup()").any(1)
			.addMethod("triggered()").after(1).atMost(1)
			.addMethod("terminal()").last()
		.build();

		descriptor.writeToFolder(getTemporaryFolder());

		addTestClassMethod("Test", loadResource("TriggeredTest1.avaj"));
		testCompile();
	}

	@Test(expected=DescriptorBuilderException.class)
	public void testTriggeringSameGroup() {
		Descriptor descriptor = Flapi.builder()
			.setDescriptorName("Something")
			.setPackage("something")

			.addMethod("triggered()").after(1).atMost(2, 1)
			.addMethod("terminal()").last()
		.build();

		descriptor.writeToStream(BlackHoleStream.$);
	}
}


text:
class AddMaterializedViewInFooNamespace < ActiveRecord::Migration[5.0]
  def up
    execute <<~SQL
      CREATE MATERIALIZED VIEW foo.mat_view AS
      SELECT
        public.mat_view_1.label AS label
       FROM mat_view_1;
    SQL
  end

  def down
    execute <<~SQL
      DROP MATERIALIZED VIEW foo.mat_view
    SQL
  end
end


text:
Do not use global `$` or `jQuery`.

## Rule Details

In general, we want application code to reference the version of jQuery that's been directly pinned to the version of Ember used. This helps avoid version conflicts, and ensures that code inside modules isn't reliant on global variables.

Examples of **incorrect** code for this rule:

```js
export default Component.extend({
  init() {
    $('.foo').addClass('bar'); //global usage
  }
});
```

Examples of **correct** code for this rule:

```js
import Ember from 'ember';

const { $ } = Ember;
export default Component.extend({
  init() {
    Ember.$('.foo').addClass('bar') //usage from Ember object
    // or even better
    $('.foo').addClass('bar'); // deconstruction from Ember object
  }
});

```


text:
{#
 # News entry template
 # -------------------
 #
 # This template gets loaded whenever a News entry's URL is
 # requested. That's because the News section's Template setting is
 # set to "news/_entry", the path to this template.
 #
 # When this template is loaded, it will already have an 'entry'
 # variable, set to the requested News entry.
 #
 # See this page for more details on how Craft routes requests:
 # http://craftcms.com/docs/routing
 #}

{% extends "_layout" %}

{% block content %}

{{ entry.title }}

Posted on {{ entry.postDate.format('F d, Y') }}

		{{ entry.body }}

{% endblock %}


text:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
cd $DIR

heroku container:login

docker tag savantly/sprout-server:latest registry.heroku.com/sprout-server/web
docker push registry.heroku.com/sprout-server/web

docker tag savantly/sprout-webapp:latest registry.heroku.com/sprout-web/web
docker push registry.heroku.com/sprout-web/web

heroku container:release web -a sprout-server
heroku container:release web -a sprout-web