Example #1
0
FGeometry::FGeometry(const FVector2D& InLocalSize, const FSlateLayoutTransform& InLocalLayoutTransform, const FSlateLayoutTransform& ParentAccumulatedLayoutTransform, const FSlateRenderTransform& ParentAccumulatedRenderTransform) 
	: Size(InLocalSize)
	, Scale(1.0f)
	, AbsolutePosition(0.0f, 0.0f)
	, AccumulatedRenderTransform(Concatenate(InLocalLayoutTransform, ParentAccumulatedRenderTransform))
{
	FSlateLayoutTransform AccumulatedLayoutTransform = Concatenate(InLocalLayoutTransform, ParentAccumulatedLayoutTransform);
	// HACK to allow us to make FGeometry public members immutable to catch misuse.
	const_cast<FVector2D&>(AbsolutePosition) = AccumulatedLayoutTransform.GetTranslation();
	const_cast<float&>(Scale) = AccumulatedLayoutTransform.GetScale();
	const_cast<FVector2D&>(Position) = InLocalLayoutTransform.GetTranslation();
}
Example #2
0
TEST_F(TextToBinaryTest, CRLF) {
  const std::string input =
      "%i32 = OpTypeInt 32 1\r\n%c = OpConstant %i32 123\r\n";
  EXPECT_THAT(CompiledInstructions(input),
              Eq(Concatenate({MakeInstruction(SpvOpTypeInt, {1, 32, 1}),
                              MakeInstruction(SpvOpConstant, {1, 2, 123})})));
}
Example #3
0
/**
 * This widget was created before render transforms existed for each widget, and it chose to apply the render transform AFTER the layout transform.
 * This means leveraging the render transform of FGeometry would be expensive, as we would need to use Concat(LayoutTransform, RenderTransform, Inverse(LayoutTransform).
 * Instead, we maintain the old way of doing it by modifying the AllottedGeometry only during rendering to append the widget's implied RenderTransform to the existing LayoutTransform.
 */
int32 SFxWidget::OnPaint( const FPaintArgs& Args, const FGeometry& AllottedGeometry, const FSlateRect& MyClippingRect, FSlateWindowElementList& OutDrawElements, int32 LayerId, const FWidgetStyle& InWidgetStyle, bool bParentEnabled ) const
{
	// Convert the 0..1 origin into local space extents.
	const FVector2D ScaleOrigin = RenderScaleOrigin.Get() * AllottedGeometry.Size;
	const FVector2D Offset = VisualOffset.Get() * AllottedGeometry.Size;
	// create the render transform as a scale around ScaleOrigin and offset it by Offset.
	const auto RenderTransform = Concatenate(Inverse(ScaleOrigin), RenderScale.Get(), ScaleOrigin, Offset);
	// This will append the render transform to the layout transform, and we only use it for rendering.
	FGeometry ModifiedGeometry = AllottedGeometry.MakeChild(AllottedGeometry.Size, RenderTransform);
	
	FArrangedChildren ArrangedChildren(EVisibility::Visible);
	this->ArrangeChildren(ModifiedGeometry, ArrangedChildren);

	// There may be zero elements in this array if our child collapsed/hidden
	if( ArrangedChildren.Num() > 0 )
	{
		// We can only have one direct descendant.
		check( ArrangedChildren.Num() == 1 );
		const FArrangedWidget& TheChild = ArrangedChildren[0];

		// SFxWidgets are able to ignore parent clipping.
		const FSlateRect ChildClippingRect = (bIgnoreClipping.Get())
			? ModifiedGeometry.GetClippingRect()
			: MyClippingRect.IntersectionWith(ModifiedGeometry.GetClippingRect());

		FWidgetStyle CompoundedWidgetStyle = FWidgetStyle(InWidgetStyle)
			.BlendColorAndOpacityTint(ColorAndOpacity.Get())
			.SetForegroundColor( ForegroundColor );

		return TheChild.Widget->Paint( Args.WithNewParent(this), TheChild.Geometry, ChildClippingRect, OutDrawElements, LayerId + 1, CompoundedWidgetStyle, ShouldBeEnabled( bParentEnabled ) );
	}
	return LayerId;

}
Example #4
0
// This Identifier is stored in binary form.
// But what if you want a pretty string version of it?
// Just call this function.
void Identifier::GetString(String& id) const
{
    auto data = Data::Factory();
    data->Assign(&type_, sizeof(type_));

    OT_ASSERT(1 == data->size());

    if (0 == size()) { return; }

    data->Concatenate(this->data(), size());

    auto output = String::Factory("ot");
    output->Concatenate(String::Factory(
        OT::App().Crypto().Encode().IdentifierEncode(data).c_str()));
    id.swap(output);
}
Example #5
0
OTData& OTData::operator+=(const OTData& rhs)
{
    if (rhs.GetSize() > 0) {
        Concatenate(rhs.data_, rhs.GetSize());
    }
    return *this;
}
Example #6
0
static void rec(int* list, int place, uint32_t* primelist, int index)
{
    if (place == 6) {
        int total = 0;
        int i;
        for (i = 1; i < 6; i++)
            total += list[i];
        if (total < min) {
            min = total;
            int n;
            for (n = 1; n < 6; n++) {
                minlist[n] = list[n];
            }
        }
        return;
    }
    int i;
    for (i = index; primelist[i]; i++) {
        list[place] = primelist[i];
        int works = true;
        int n;
        for (n = 1; n < place; n++) {
            if (!Concatenate(list[n], list[place])) {
                works = false;
                break;
            }
        }
        if (works)
            rec(list, place + 1, primelist, i + 1);
    }
    return;
}
Example #7
0
TEST_P(TextToBinaryHalfValueTest, Samples) {
  const std::string input =
      "%1 = OpTypeFloat 16\n%2 = OpConstant %1 " + GetParam().first;
  EXPECT_THAT(CompiledInstructions(input),
              Eq(Concatenate({MakeInstruction(SpvOpTypeFloat, {1, 16}),
                              MakeInstruction(SpvOpConstant,
                                              {1, 2, GetParam().second})})));
}
Example #8
0
void Nfa::ConcatenateAllPreviousTillOperation(stack<RegularDefinition *> &solver) {
    vector<Nfa *> nfas_to_be_concatenated;
    while(solver.top()->type != RegularDefinition::kOperation) {
        nfas_to_be_concatenated.push_back(solver.top()->GetNfa());
        solver.pop();
    }
    reverse(nfas_to_be_concatenated.begin(), nfas_to_be_concatenated.end());
    solver.push(new RegularDefinition(RegularDefinition::kNfa, Concatenate(nfas_to_be_concatenated)));
}
Example #9
0
///
/// \brief MetaDataset::MetaDataset
/// \param name Name of this dataset as displayed to user
/// \param main_window Main window of the program
/// \param log_file The log file
/// \param directory The current global working directory
/// \param method_description The description of the method used
/// \param endmember_selection The string used by the user to select endmembers
/// \param method An enum specifying the method
/// \param parent_datasets The datasets from which this dataset is extracted
///
MetaDataset::MetaDataset(QString name,
                         MainWindow *main_window,
                         QString *directory,
                         QString method_description,
                         MetaMethod::Method method,
                         QList<QSharedPointer<VespucciDataset> > parent_datasets)
    : VespucciDataset(name, main_window, directory)
{
    parent_datasets_ = parent_datasets;

    if(!ParentsValid()){
        throw std::runtime_error("Improper input to MetaDataset constructor");
        cerr << "Improper input to MetaDataset constructor\n";

    }
    method_ = method;
    method_description_ = method_description;
    mat spectra;
    vec wavelength = parent_datasets_[0]->wavelength();
    vec x;
    vec y;
    switch(method_) {
    case MetaMethod::AverageSpectra :
        try{
            spectra = ProcessAverage(x, y);
        }
        catch(std::exception e){
            throw std::runtime_error("MetaDataset::ProcessAverage");
        }

        break;
    case MetaMethod::ConcatenateDatasets :
        try{
            spectra = Concatenate(x, y);
        }
        catch(std::exception e){
            throw std::runtime_error("MetaDataset::Concatenate");
        }
        break;
    default:
        throw std::runtime_error("Improper input to MetaDataset");
    }

    try{
        SetData(spectra, wavelength, x, y);
        SetParentDatasetIndices(parent_coordinates_);
    }
    catch(std::exception e){
        throw std::runtime_error("Failure to set data in MetaDataset constructor");
    }
    vec indices_temp(spectra.n_cols);
    for (uword i = 0; i < indices_temp.n_elem; ++i){
        indices_temp(i) = i;
    }
    SetIndices(indices_temp);
}
Example #10
0
int32 FHittestGrid::InsertWidget( const int32 ParentHittestIndex, const EVisibility& Visibility, const FArrangedWidget& Widget, const FVector2D InWindowOffset, const FSlateRect& InClippingRect )
{
	check( ParentHittestIndex < WidgetsCachedThisFrame->Num() );

	// Update the FGeometry to transform into desktop space.
	FArrangedWidget WindowAdjustedWidget(Widget);
	WindowAdjustedWidget.Geometry.AppendTransform(FSlateLayoutTransform(InWindowOffset));
	const FSlateRect WindowAdjustedRect = InClippingRect.OffsetBy(InWindowOffset);

	// Remember this widget, its geometry, and its place in the logical hierarchy.
	const int32 WidgetIndex = WidgetsCachedThisFrame->Add( FCachedWidget( ParentHittestIndex, WindowAdjustedWidget, WindowAdjustedRect ) );
	check( WidgetIndex < WidgetsCachedThisFrame->Num() ); 
	if (ParentHittestIndex != INDEX_NONE)
	{
		(*WidgetsCachedThisFrame)[ParentHittestIndex].AddChild( WidgetIndex );
	}
	
	if (Visibility.IsHitTestVisible())
	{
		// Mark any cell that is overlapped by this widget.

		// Compute the render space clipping rect, and compute it's aligned bounds so we can insert conservatively into the hit test grid.
		FSlateRect GridRelativeBoundingClipRect = 
			TransformRect(
				Concatenate(
					Inverse(WindowAdjustedWidget.Geometry.GetAccumulatedLayoutTransform()),
					WindowAdjustedWidget.Geometry.GetAccumulatedRenderTransform()
				),
				FSlateRotatedRect(WindowAdjustedWidget.Geometry.GetClippingRect().IntersectionWith(WindowAdjustedRect))
			)
			.ToBoundingRect()
			.OffsetBy(-GridOrigin);

		// Starting and ending cells covered by this widget.	
		const FIntPoint UpperLeftCell = FIntPoint(
			FMath::Max(0, FMath::FloorToInt(GridRelativeBoundingClipRect.Left / CellSize.X)),
			FMath::Max(0, FMath::FloorToInt(GridRelativeBoundingClipRect.Top / CellSize.Y)));

		const FIntPoint LowerRightCell = FIntPoint(
			FMath::Min( NumCells.X-1, FMath::FloorToInt(GridRelativeBoundingClipRect.Right / CellSize.X)),
			FMath::Min( NumCells.Y-1, FMath::FloorToInt(GridRelativeBoundingClipRect.Bottom / CellSize.Y)));

		for (int32 XIndex=UpperLeftCell.X; XIndex <= LowerRightCell.X; ++ XIndex )
		{
			for(int32 YIndex=UpperLeftCell.Y; YIndex <= LowerRightCell.Y; ++YIndex)
			{
				CellAt(XIndex, YIndex).CachedWidgetIndexes.Add( WidgetIndex );
			}
		}
	}
	
	return WidgetIndex;

}
//						=======================
ExprResult				AddExpression::Evaluate
//						======================= 
(
	Context&			context
) const
{
	// Create a result, and initialise its type as error.
	ExprResult result( m_strPrecision );
	result.SetStatus( ExprResult::UNDEF_STATUS );

	// Evaluate the two operands of the addition expression.
	ExprResult left	 = m_pOperand1->Evaluate( context );
	ExprResult right = m_pOperand2->Evaluate( context );

	// Convert any possible variable to its contents.
	left.ConvertFromVar( context );
	right.ConvertFromVar( context );

	// Check if both the operands were evaluated as OK.
	if ( left.IsOK() && right.IsOK() )
	{
		// Check if both operands have either an arithmetic type or type
		// UNSPECIFIED which can be interpreted as an arithmetic type.
		if ( ( left.IsNumber() || ( left.IsUnspecified() && left.InterpretAsNumber() ) )
			&& ( right.IsNumber() || ( right.IsUnspecified() && right.InterpretAsNumber() ) ) )
		{
			// The (numerical) values of both operands can be added.
			result = Add( left, right );
		}
		else
		{
			// The values of both operands can be concatenated.
			result = Concatenate( left, right );
		}
	}
	else
	{
		// Check if an error was found in the left operand.
		if ( !left.IsOK() )
		{
			// Set as status and value of the result, those of the left operand.
			result.SetStatus( left.GetStatus() );
			result.SetValue( left.GetValue() );
		}
		else
		{
			// Set as status and value of the result, those of the right operand.
			result.SetStatus( right.GetStatus() );
			result.SetValue( right.GetValue() );
		}
	}
	
	return result;
}
Example #12
0
FGeometry::FGeometry(const FVector2D& InLocalSize, const FSlateLayoutTransform& InLocalLayoutTransform, const FSlateRenderTransform& InLocalRenderTransform, const FVector2D& InLocalRenderTransformPivot, const FSlateLayoutTransform& ParentAccumulatedLayoutTransform, const FSlateRenderTransform& ParentAccumulatedRenderTransform) 
	: Size(InLocalSize)
	, Scale(1.0f)
	, AbsolutePosition(0.0f, 0.0f)
	, AccumulatedRenderTransform(
		Concatenate(
			// convert the pivot to local space and make it the origin
			Inverse(TransformPoint(FScale2D(InLocalSize), InLocalRenderTransformPivot)), 
			// apply the render transform in local space centered around the pivot
			InLocalRenderTransform, 
			// translate the pivot point back.
			TransformPoint(FScale2D(InLocalSize), InLocalRenderTransformPivot), 
			// apply the layout transform next.
			InLocalLayoutTransform, 
			// finally apply the parent accumulated transform, which takes us to the root.
			ParentAccumulatedRenderTransform))
{
	FSlateLayoutTransform AccumulatedLayoutTransform = Concatenate(InLocalLayoutTransform, ParentAccumulatedLayoutTransform);
	// HACK to allow us to make FGeometry public members immutable to catch misuse.
	const_cast<FVector2D&>(AbsolutePosition) = AccumulatedLayoutTransform.GetTranslation();
	const_cast<float&>(Scale) = AccumulatedLayoutTransform.GetScale();
	const_cast<FVector2D&>(Position) = InLocalLayoutTransform.GetTranslation();
}
Example #13
0
// Exec_DataSetCmd::Execute()
Exec::RetType Exec_DataSetCmd::Execute(CpptrajState& State, ArgList& argIn) {
  RetType err = CpptrajState::OK;
  if (argIn.Contains("legend")) {         // Set legend for one data set
    std::string legend = argIn.GetStringKey("legend");
    DataSet* ds = State.DSL().GetDataSet( argIn.GetStringNext() );
    if (ds == 0) return CpptrajState::ERR;
    mprintf("\tChanging legend '%s' to '%s'\n", ds->legend(), legend.c_str());
    ds->SetLegend( legend );
  // ---------------------------------------------
  } else if (argIn.hasKey("outformat")) { // Change double precision set output format
    err = ChangeOutputFormat(State, argIn);
  // ---------------------------------------------
  } else if (argIn.hasKey("remove")) {    // Remove data sets by various criteria
    err = Remove(State, argIn);
  // ---------------------------------------------
  } else if (argIn.hasKey("makexy")) {    // Combine values from two sets into 1
    err = MakeXY(State, argIn);
  // ---------------------------------------------
  } else if (argIn.hasKey("make2d")) {    // Create 2D matrix from 1D set
    err = Make2D(State, argIn);
  // ---------------------------------------------
  } else if (argIn.hasKey("vectorcoord")) { // Extract vector X/Y/Z coord as new set
    err = VectorCoord(State, argIn);
  // ---------------------------------------------
  } else if (argIn.hasKey("filter")) {    // Filter points in data set to make new data set
    err = Filter(State, argIn);
  // ---------------------------------------------
  } else if (argIn.hasKey("cat")) {       // Concatenate two or more data sets
    err = Concatenate(State, argIn);
  // ---------------------------------------------
  } else if (argIn.hasKey("droppoints")) { // Drop points from set
    err = ModifyPoints(State, argIn, true);
  // ---------------------------------------------
  } else if (argIn.hasKey("keeppoints")) { // Keep points in set
    err = ModifyPoints(State, argIn, false);
  // ---------------------------------------------
  } else if (argIn.hasKey("dim")) {        // Modify dimension of set(s)
    err = ChangeDim(State, argIn);
  // ---------------------------------------------
  } else if (argIn.hasKey("invert")) {     // Invert set(s) X/Y, create new sets
    err = InvertSets(State, argIn);
  // ---------------------------------------------
  } else {                                // Default: change mode/type for one or more sets.
    err = ChangeModeType(State, argIn);
  }
  return err;
}
Example #14
0
// append a string at the end of the current buffer.
void String::Concatenate(const char* fmt, ...)
{
    va_list vl;
    va_start(vl, fmt);

    std::string str_output;

    const bool bSuccess = String::vformat(fmt, &vl, str_output);

    va_end(vl);

    if (bSuccess) {
        const String strConcat(str_output);

        Concatenate(strConcat);
    }
}
Example #15
0
/*
 * vislib::sys::Path::Resolve
 */
vislib::StringW vislib::sys::Path::Resolve(StringW path, StringW basepath) {
    // TODO: Windows shell API resolve does not work in the expected
    // way, so we use the same manual approach for Windows and Linux.

#ifdef _WIN32
    /* Replace unchefmäßige path separators. */
    basepath.Replace(L'/', SEPARATOR_W);
    path.Replace(L'/', SEPARATOR_W);
#endif /* _WIN32 */

    if (Path::IsRelative(basepath)) {
        basepath = Resolve(basepath);
    }

    if (path.IsEmpty()) {
        /* Path is empty, i. e. return current working directory. */
        return Path::Canonicalise(basepath);

    } else if (Path::IsAbsolute(path)) {
        /* Path is absolute, just return it. */
        return Path::Canonicalise(path);

    } else if ((path[0] == MYDOCUMENTS_MARKER_W) 
            && ((path.Length() == 1) || path[1] == SEPARATOR_W)) {
        /*
         * replace leading ~ with users home directory
         */
        path.Replace(MYDOCUMENTS_MARKER_W, Path::GetUserHomeDirectoryW());
        return Path::Canonicalise(path);

    } else if ((path[0] == SEPARATOR_W) && (path[1] != SEPARATOR_W)) {
        /*
         * Concatenate current drive and relative path, and canonicalise
         * the result.
         */
        return Path::Concatenate(basepath.Substring(0, 2), path, true);

    } else {
        /*
         * Concatenate current directory and relative path, and canonicalise
         * the result.
         */
        return Concatenate(basepath, path, true);
    }
}
Example #16
0
FGeometry::FGeometry(const FVector2D& OffsetFromParent, const FVector2D& ParentAbsolutePosition, const FVector2D& InLocalSize, float InScale) 
	: Size(InLocalSize)
	, Scale(1.0f)
	, AbsolutePosition(0.0f, 0.0f)
{
	// Since OffsetFromParent is given as a LocalSpaceOffset, we MUST convert this offset into the space of the parent to construct a valid layout transform.
	// The extra TransformPoint below does this by converting the local offset to an offset in parent space.
	FVector2D LayoutOffset = TransformPoint(InScale, OffsetFromParent);

	FSlateLayoutTransform ParentAccumulatedLayoutTransform(InScale, ParentAbsolutePosition);
	FSlateLayoutTransform LocalLayoutTransform(LayoutOffset);
	FSlateLayoutTransform AccumulatedLayoutTransform = Concatenate(LocalLayoutTransform, ParentAccumulatedLayoutTransform);
	AccumulatedRenderTransform = TransformCast<FSlateRenderTransform>(AccumulatedLayoutTransform);
	// HACK to allow us to make FGeometry public members immutable to catch misuse.
	const_cast<FVector2D&>(AbsolutePosition) = AccumulatedLayoutTransform.GetTranslation();
	const_cast<float&>(Scale) = AccumulatedLayoutTransform.GetScale();
	const_cast<FVector2D&>(Position) = LocalLayoutTransform.GetTranslation();
}
Example #17
0
int main()
{
	int i,j;
	char lockName[10];
	int money;
	TestMe(33,0);
	TestMe(55,1);
	TestMe(66,2);
	TestMe(44,0);
	TestMe(77,0);

	TestMe(88,1);
	TestMe(99,1);
	TestMe(11,1);
	TestMe(22,1);
	TestMe(33,1);
	TestMe(40,1);

	i = CreateLock("TestLock",8);
	WriteNum(i);Write("\n",1,1);
    
	for(i=0;i<29;i++)
	  {
	    Concatenate("TestLock",sizeof("testlock"),i,lockName);
	    j = CreateLock(lockName, sizeof(lockName));
		WriteNum(j);Write("\n",1,1);
	  }	
/*
		AcquireLock(i-1);
		ReleaseLock(i-1);

	money = CreateSharedInt("money",5,10);
	SetSharedInt(money,5,1);
	SetSharedInt(money,3,1);
	SetSharedInt(money,8,10);
	i = ArraySearch(money,3,1);
	WriteNum(i);Write("\n",1,1);
	i = ArraySearch(money,99,10);
	WriteNum(i);Write("\n",1,1);
	*/
}
Example #18
0
struct IntInstr* GenIntCode (struct TreeNode* tree) {
    struct TreeNode *root = tree;
    IntInstr *b1,*b2,*cond,*jump2else,*thenpart,*jump2end,*elsepart,*endif;

    switch (root->type) {
    case STMT_LIST:
	b1 = GenIntCode(root->child[0]);	
	b2 = GenIntCode(root->child[1]);	
        Concatenate(b1,b2);
        return b1;
    case EMPTY_STMT:
        return newIntInstr(OP_NOP,NULL,NULL);
    case EXPR_STMT : 
        b1 = GenIntCode(root->child[0]);
        b2 = newIntInstr(OP_DISCARD,NULL,NULL);
        return Concatenate(b1,b2);
    case PRINT_STMT :
        b1 = GenIntCode(root->child[0]);
        b2 = newIntInstr(OP_PRINT,NULL,NULL);
        return Concatenate(b1,b2);
    case INPUT_STMT :
        return newIntInstr(OP_INPUT,root->symbol,NULL);
    case IFTHEN_STMT :
        cond = GenIntCode(root->child[0]);
        jump2end = newIntInstr(OP_JMPF,NULL,NULL); 
        thenpart = GenIntCode(root->child[1]);
        endif = newIntInstr(JUMPTARGET,NULL,jump2end);
	jump2end->target = endif;	

        Concatenate (cond, jump2end);
	Concatenate (jump2end, thenpart);
	Concatenate (thenpart, endif);
	return cond; 
   case IFTHENELSE_STMT :
	cond = GenIntCode(root->child[0]);
        jump2else = newIntInstr(OP_JMPF,NULL,NULL);     
    	thenpart = GenIntCode(root->child[1]);
        elsepart = PrefixJT(GenIntCode(root->child[2]),jump2else);
 	
	jump2else->target =  elsepart;
        jump2end = newIntInstr(OP_JMP,NULL,NULL);
	endif = newIntInstr(JUMPTARGET,NULL,jump2end);	
	jump2end->target = endif;

	Concatenate (cond, jump2else);
	Concatenate (jump2else, thenpart);
	Concatenate (thenpart, jump2end);
	Concatenate (jump2end, elsepart);
	Concatenate (elsepart, endif);
	return cond; 
   case ERROR_STMT:
	return newIntInstr (OP_NOP,NULL,NULL);
   case EQUAL_EXPR:
	b1 = GenIntCode (root->child[0]);
	b2 = GenIntCode (root->child[1]);
	Concatenate (b1, b2);
	if (root->child[0]->rettype == T_STRING)
		return Concatenate (b1, newIntInstr (OP_STR_EQUAL,NULL,NULL));
	else
		return Concatenate (b1, newIntInstr (OP_BOOL_EQUAL,NULL,NULL));
   case ASSIGN_EXPR:
	b1 = GenIntCode (root->child[0]);
	b2 = newIntInstr (OP_GETTOP, root->symbol,NULL);
	return Concatenate (b1, b2);
   case CONCAT_EXPR:
	b1 = GenIntCode (root->child[0]);
	b2 = GenIntCode (root->child[1]);
	Concatenate (b1, b2);
	return Concatenate (b1, newIntInstr (OP_CONCAT,NULL,NULL));
   case IDENT_EXPR:
   case STR_EXPR:
	return newIntInstr (OP_PUSH, root->symbol,NULL);
   case COERCE_TO_STR:
	b1 = GenIntCode (root->child[0]);
	b2 = newIntInstr (OP_BOOL2STR,NULL,NULL);
	return Concatenate (b1, b2);
    }
    return newIntInstr (OP_NOP,NULL,NULL); // shouldn't happen 
}
Example #19
0
void Visitor() /* code block to perform visitor operation */
{
  int condnToWait,who,i,j, num;
  int talkingTime;
  int checkCorrectOperatorV;
  int phoneToUse,gotPhone;
  int thisActivate;
  int operatorToUse;
  int callPresident;

/* Some common parameters */


  char lockName[30];
  char condName1[30];
  char condName2[30];
  int presidentStatus;
  int phoneStatus;
  char printing[50];
  int lockID1, lockID2, lockID3, lockID4, lockID5, lockID6, condID1, condID2, condID3, condID4;
  int indOpLock[20], waitForOperVerCV[20], waitForCallerCV[20];
  int activate, authMechanism, freeOperators, operatorStatus;
  int repositoryMoney;
 

  presidentStatus = CreateSharedInt("presidentStatus",15,1);
  phoneStatus = CreateSharedInt("phoneStatus",11,NOOFPHONES);
  freeOperators = CreateSharedInt("freeOperators",13,1);
  operatorStatus = CreateSharedInt("operatorStatus",14,Nop);
  activate = CreateSharedInt("activate",sizeof("activate"),Nop);
  authMechanism = CreateSharedInt("authMechanism",sizeof("authMechanism"),Nop);
  repositoryMoney = CreateSharedInt("repositoryMoney",sizeof("repositoryMoney"),Nop);
 
  

  lockID1 = CreateLock("phoneLock",10);                  /* obtain a master lock for all phones */
  lockID2 = CreateLock("GlobalOpLock",12);     /* obtain a master lock for all the operators */
  lockID3 = CreateLock("visitorCountLock",17);     /* obtain a lock to keep track of the number of visitors permitted to make a call */
  lockID4 = CreateLock("NumSenators",12);
  lockID5 = CreateLock("NumVisitors",12);
  lockID6 = CreateLock("NumOperators",13);
  /*  displayLock = CreateLock("DispLock",7); */
  /* Lock **individualOperatorLock; */                            /* obtain an individual lock for every operator */
  condID1 = CreateCondition("presiNeedsPhone",16); /* condition variable for the condition that president needs phone */
  condID2 = CreateCondition("senatorNeedsPhone",18);     /* condition variable for the condition that senator needs phone */
  condID3 = CreateCondition("visitorNeedsPhone",18);     /* condition variable for the condition that visitor  needs phone */
  condID4 = CreateCondition("processCustomer",16);         /* condition variable to allow president/senator/visitor to make a call */
  for (i=0;i<Nop;i++)
    {
      Concatenate("OperatorLock",sizeof("OperatorLock"),i,lockName);
      Concatenate("waitForOpVer",sizeof("waitForOpVer"),i,condName1);
      Concatenate("waitForCaller",sizeof("waitForCaller"),i,condName2); 
      indOpLock[i] = CreateLock(lockName,sizeof(lockName));
      waitForOperVerCV[i] = CreateCondition(condName1,sizeof(condName1));
      waitForCallerCV[i] = CreateCondition(condName2,sizeof(condName2));
    } 
  
  
  
  /* End of common parameters */

  AcquireLock(lockID5);
  who = NumVisitor;
  NumVisitor++;
  ReleaseLock(lockID5);
  AcquireLock(lockID1);
  /* loop to check if the president or senator is waiting. If any one is waiting, then visitor has to wait before he/she can make a call. Otherwise visitor can go ahead */
  do
    {
      condnToWait = TRUE;      
      if(GetSharedInt(presidentStatus,0) == 1)
		condnToWait = TRUE;
      /* Check if some senator is already waiting! */
      else if(CheckCondWaitQueue(condID2)==1)
		{
		  /* Bad luck, there seems to be a senator.  */
		  condnToWait = TRUE;
		}
      else
		{
		  /*
	  for(i=0;i<NOOFPHONES;i++)
	    {
	      if(GetSharedInt(phoneStatus,i)==FREE)
		   {
			  phoneToUse = i;
			  SetSharedInt(phoneStatus,i,BUSY);
			  condnToWait = FALSE;
			  break;
		   }
	    }	*/
		phoneToUse = GetOneIndex(phoneStatus);
		if(phoneToUse!=NOOFPHONES)
			condnToWait = FALSE;
	}
      if(condnToWait)
	WaitCV(condID3,lockID1); /* visitor waits if there is a president or a senator already waitng to make a call. */
    }while(condnToWait);
  ReleaseLock(lockID1);
  /* Visitor has got a phone */
  /* Need to get an operator now */
  AcquireLock(lockID2);
  while(GetSharedInt(freeOperators,0)==0)
    WaitCV(condID4,lockID2);
  /* visitor has to wait if there are no free operators available */
  /* Some operator is available. Though I don't know who it is. Let us find out.   */ 
  /*
  for(j=0;j<Nop;j++)
    {
      if(GetSharedInt(operatorStatus,j)==FREE)
	{
	  operatorToUse = j;
	  break;
	}
    } */
	operatorToUse = GetOneIndex(operatorStatus);
  /* operator obtained */
  checkCorrectOperatorV = operatorToUse; /* check if the operator to whom the visitor pays money is the same as the one the permits/denies the visitor to make a call */
  AcquireLock(indOpLock[operatorToUse]);
  SetSharedInt(activate, operatorToUse, 2);
  SetSharedInt(operatorStatus, operatorToUse, BUSY);
  SetSharedInt(freeOperators, 0, GetSharedInt(freeOperators, 0) - 1);
  ReleaseLock(lockID2);
  SetSharedInt(authMechanism, operatorToUse, 3);  /* 1 for President | 2 for Senators | 3 for Visitors */
  SetSharedInt(repositoryMoney, operatorToUse, ((RandomFunction(100)-1)>80)?0:1); /* randomly generate whether the visitor pays $1 or not */
  /* If operator is sleeping, wake up */

  SignalCV(waitForCallerCV[operatorToUse],indOpLock[operatorToUse]);
  SignalCV(waitForCallerCV[operatorToUse],indOpLock[operatorToUse]);
  while(GetSharedInt(activate,operatorToUse)==2)
	  WaitCV(waitForOperVerCV[operatorToUse],indOpLock[operatorToUse]);
  thisActivate=0;
  thisActivate=GetSharedInt(activate, operatorToUse);  
  ReleaseLock(indOpLock[operatorToUse]);
  if (thisActivate==0) 
    {
	  /* visitor is denied access to phone beacause he/she didn't pay $1. */
      j=0;
      talkingTime=0;
      /* printf("Visitor%d \t  UNAVAILABLE \t %d/%d units \t %d \t   NOTAPPLICABLE    DENIED \t   Money paid is $0 - verified by operator 
	  %d \n",who+1,j,talkingTime,operatorToUse+1,checkCorrectOperatorV+1); */
	  /*	   AcquireLock(displayLock); */
	  Write("Visitor ",8,1);
	   num = who+1;
		itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
		Write(" \t UNAVAILABLE \t",100,1);	   
		num = j;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write("/",1,1);
	    num=talkingTime;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" units \t ",10,1);
	    num=operatorToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \t",6,1);	
	    Write(" NOTAPPLICABLE    DENIED \t   Money paid is $0 - verified by operator ",100,1);
	    num=checkCorrectOperatorV+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \n",3,1);
		/*ReleaseLock(displayLock);*/
	Yield();

      /* printf("Access to Phone for visitor %d Denied by Operator %d!\n",who+1,operatorToUse+1); */
    }
  else if (thisActivate==1) /* visitor has paid $1. Operator verifies and visitor is allowed to make a call */
    {
      /* Now Talk */
      talkingTime = RandomFunction(5); /* randomly generate the amount of time the visitor will talk on the phone */
      /* loop for the visitor to talk on the phone for the randomly generated time period */
      for (i=1;i<=talkingTime;i++){
	/* printf("Visitor%d \t  %d \t\t %d/%d units \t %d \t   NOTAPPLICABLE    ACCEPTED \t   
	Money paid is $1 - verified by operator %d \n",who+1,phoneToUse+1,i,talkingTime,operatorToUse+1,checkCorrectOperatorV+1); */
	/*AcquireLock(displayLock);*/
	Write("Visitor ",8,1);
	   num = who+1;
		itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
		Write(" \t",2,1);
	    num = phoneToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write("\t\t ",5,1);
		num = i;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write("/",1,1);
	    num=talkingTime;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" units \t ",10,1);
	    num=operatorToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \t",6,1);	
	    Write(" NOTAPPLICABLE    ACCEPTED \t   Money paid is $1 - verified by operator ",100,1);
	    num=checkCorrectOperatorV+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \n",3,1);
		/*ReleaseLock(displayLock);*/
	/*Yield();*/
      }
      /* visitor is done talking */
      /* Set the phone status to be free */
    }
  AcquireLock(lockID1);
  SetSharedInt(phoneStatus,phoneToUse,FREE);
  if(GetSharedInt(presidentStatus,0)==0) /* president is not waking to talk */
    {
      if(CheckCondWaitQueue(condID2))
		SignalCV(condID2,lockID1); /* wake up the next senator waiting to talk */
      else
		SignalCV(condID3,lockID1); /* if no senator is waiting, then wake up the next visitor waiting to talk */
    }
  else /* president is waiting to talk, so senators and visitors will have to wait */
    {
      callPresident = TRUE;
	  /*
      for(i=0;i<NOOFPHONES;i++)
		if((i!=phoneToUse)&&(GetSharedInt(phoneStatus,i)==BUSY)) // check if even a single phone is busy other than the phone just used by the visitor which he/she sets to free 
	  {
	    callPresident = FALSE;
	    break;
	  }*/
		i = ArraySearch(phoneStatus, phoneToUse, BUSY);
		if(i!=NOOFPHONES)
			callPresident = FALSE;
      if(callPresident==TRUE)
	SignalCV(condID1,lockID1); /* if all phones are free, then no one is talking currently and so, signal the president */
    }
  /* visitor goes away and does not return. Remember visitors can make a maximum of just one call       */
  ReleaseLock(lockID1);	
  WriteMe("Visitor ");WriteNum(who + 1);WriteMe("Leaving\n");
  Exit(0);
}
Example #20
0
/// <summary>
/// Concatenates a translation matrix to this matrix.
/// </summary>
/// <param name="transX">Distance to translate in the X direction.</param>
/// <param name="transY">Distance to translate in the Y direction.</param>
/// <param name="transZ">Distance to translate in the Z direction.</param>
void Matrix3D::Translate(double transX, double transY, double transZ)
{
    Matrix3D matrix = Matrix3D::wkMat3Da;
    matrix.SetToTranslation(transX, transY, transZ);
    Concatenate(matrix);
}
void CMatrix3D::Rotate(const CQuaternion& quat)
{
	CMatrix3D rotationMatrix=quat.ToMatrix();
	Concatenate(rotationMatrix);
Example #22
0
/// <summary>
/// Concatenates a rotation matrix to this matrix.
/// </summary>
/// <param name="angle">The angle of rotation in degrees.</param>
/// <param name="axis">The orientation of the axis to rotate around.</param>
/// <param name="point">A point on the axis of rotation.</param>
void Matrix3D::Rotate(double angle, Vector3D& axis, Point3D& point)
{
    Matrix3D matrix = Matrix3D::wkMat3Da;
    matrix.SetToRotation(angle, axis, point);
    Concatenate(matrix);
}
Example #23
0
FPaintGeometry FGeometry::ToPaintGeometry(const FVector2D& LocalSize, const FSlateLayoutTransform& LayoutTransform) const
{
	FSlateLayoutTransform NewAccumulatedLayoutTransform = Concatenate(LayoutTransform, GetAccumulatedLayoutTransform());
	return FPaintGeometry(NewAccumulatedLayoutTransform, Concatenate(LayoutTransform, GetAccumulatedRenderTransform()), LocalSize);
}
// This code reads up the file, discards the bookends, and saves only the gibberish itself.
// the bEscaped option allows you to load a normal ASCII-Armored file if off, and allows
// you to load an escaped ASCII-armored file (such as inside the contracts when the public keys
// are escaped with a "- " before the rest of the ------- starts.)
bool OTASCIIArmor::LoadFromString(OTString & theStr, bool bEscaped/*=false*/)
{
	char buffer1[2100];
	
	memset(buffer1, 0, 2100);
	
	bool bContentMode = false;				// "currently in content mode"
	bool bHaveEnteredContentMode = false;	// "have yet to enter content mode"
	
	// Clear out whatever string might have been in there before.
	Release();
	
	// Load up the string from theStr, 
	// (bookended by "-----BEGIN ... -----" and END messages)
	bool bIsEOF = false;
	theStr.reset(); // So we can call theStr.sgets(). Making sure position is at start of string.
	
	do
	{
		bIsEOF = !(theStr.sgets(buffer1, 2048));
		//		bIsEOF = fin.getline(buffer1, 2048).eof();
		
		std::string line		= buffer1;	
		const char * pConstBuf	= line.c_str();
		char * pBuf				= (char *)pConstBuf;
		
		// It's not a blank line.
		if (line.length() < 2)
		{
			continue;
		}
		
		// if we're on a dashed line...
		else if (line.at(0) == '-' && line.at(2) == '-' && line.at(3) == '-'
				 && (bEscaped ? (line.at(1) == ' ') : (line.at(1) == '-') ) )
		{			
			// If I just hit a dash, that means there are only two options:
			
			// a. I have not yet entered content mode, and potentially just now entering it for the first time.
			if (!bHaveEnteredContentMode)
			{
				if (line.find("BEGIN")!=std::string::npos && line.at(0) == '-' && line.at(2) == '-' && 
					line.at(3) == '-' && (bEscaped ? (line.at(1) == ' ') : (line.at(1) == '-')))
				{
//					OTLog::Error("Reading ascii-armored contents...");
					bHaveEnteredContentMode = true;
					bContentMode = true;
					continue;
				}
				else
				{
					continue;
				}				
				
			}
			
			// b. I am now LEAVING content mode!
			else if (bContentMode && line.find("END")!=std::string::npos)
			{
//				OTLog::Error("Finished reading ascii-armored contents.\n");
//				OTLog::vError("Finished reading ascii-armored contents:\n%s(END DATA)\n", Get());
				bContentMode   = false;
				continue;
			}
		}
		
		
		// Else we're on a normal line, not a dashed line.
		else
		{
			if (bHaveEnteredContentMode && bContentMode)
			{
				if (line.compare(0,8,"Version:") == 0)
				{
//					OTLog::Error("Skipping version line...\n");
					continue;
				}
			}
			
		}
		
		// Here we save the line to member variables, if appropriate
		if (bContentMode)
		{
			Concatenate("%s\n", pBuf);
		}
	}
	while(!bIsEOF && (bContentMode || !bHaveEnteredContentMode));
	
	
	// reset the string position back to 0
	theStr.reset();
	
	if (!bHaveEnteredContentMode)
	{
		OTLog::Error("Error in OTASCIIArmor::LoadFromString: EOF before ascii-armored content found.\n");
		return false;
	}
	else if (bContentMode)
	{
		OTLog::Error("Error in OTASCIIArmor::LoadFromString: EOF while still reading content.\n");
		return false;
	}
	else
		return true;
}
Example #25
0
/// <summary>
/// Concatenates a scaling matrix to this matrix.
/// </summary>
/// <param name="scaleX">Factor to scale by in the X direction.</param>
/// <param name="scaleY">Factor to scale by in the Y direction.</param>
/// <param name="scaleZ">Factor to scale by in the Z direction.</param>
void Matrix3D::Scale(double scaleX, double scaleY, double scaleZ)
{
    Matrix3D matrix = Matrix3D::wkMat3Da;
    matrix.SetToScaling(scaleX, scaleY, scaleZ);
    Concatenate(matrix);
}
Example #26
0
void President()
{
  int presidentNumberOfCalls=0; /* keep count of total number of calls made by the president */
  int checkCorrectOperatorP;
  int waitingTime;
  int condnToWait;
  int phoneToUse, gotPhone,i,j;
  int operatorToUse;
  int talkingTime;
  int phoneStatus_i;
  int num;
  char lockName[30];
  char condName1[30];
  char condName2[30];
  int presidentStatus;
  int phoneStatus;
  char printing[50];
  int lockID1, lockID2, lockID3, lockID4, lockID5, lockID6, condID1, condID2, condID3, condID4;
  int indOpLock[20], waitForOperVerCV[20], waitForCallerCV[20];
  int activate, authMechanism, freeOperators, operatorStatus;



  /* Create or get access to some shared variables, locks, conditions */
  presidentStatus = CreateSharedInt("presidentStatus",15,1);
  phoneStatus = CreateSharedInt("phoneStatus",11,NOOFPHONES);
  lockID1 = CreateLock("phoneLock",10);                  /* obtain a master lock for all phones */
  freeOperators = CreateSharedInt("freeOperators",13,1);
  operatorStatus = CreateSharedInt("operatorStatus",14,Nop);
  activate = CreateSharedInt("activate",sizeof("activate"),Nop);
  authMechanism = CreateSharedInt("authMechanism",sizeof("authMechanism"),Nop);


  lockID2 = CreateLock("GlobalOpLock",sizeof("globaloplock"));     /* obtain a master lock for all the operators */
  lockID3 = CreateLock("visitorCountLock",17);     /* obtain a lock to keep track of the number of visitors permitted to make a call */
  lockID4 = CreateLock("NumSenators",12);
  lockID5 = CreateLock("NumVisitors",12);
  lockID6 = CreateLock("NumOperators",13);
 /*  displayLock = CreateLock("DispLock",7); */
  /* Lock **individualOperatorLock; */                            /* obtain an individual lock for every operator */
  condID1 = CreateCondition("presiNeedsPhone",16); /* condition variable for the condition that president needs phone */
  condID2 = CreateCondition("senatorNeedsPhone",18);     /* condition variable for the condition that senator needs phone */
  condID3 = CreateCondition("visitorNeedsPhone",18);     /* condition variable for the condition that visitor  needs phone */
  condID4 = CreateCondition("processCustomer",16);         /* condition variable to allow president/senator/visitor to make a call */
  for (i=0;i<Nop;i++)
    {
     Concatenate("OperatorLock",sizeof("OperatorLock"),i,lockName);
     Concatenate("waitForOpVer",sizeof("waitForOpVer"),i,condName1);
     Concatenate("waitForCaller",sizeof("waitForCaller"),i,condName2); 
     indOpLock[i] = CreateLock(lockName,sizeof(lockName));
     waitForOperVerCV[i] = CreateCondition(condName1,sizeof(condName1));
     waitForCallerCV[i] = CreateCondition(condName2,sizeof(condName2));
    } 

	 while(presidentNumberOfCalls<3)
    {
		 WriteMe("President Going to speak for the ");WriteNum(presidentNumberOfCalls);WriteMe("th time\n");
      condnToWait = FALSE;
      phoneToUse = 0;

      AcquireLock(lockID1);

      SetSharedInt(presidentStatus, 0, 1); /* presidentStatus = 1; */

      /* loop for the president to keep waiting even if a single phone is busy */
      do
	  {	 
		  /*
		  for(i=0;i<NOOFPHONES;i++)
		    {
			 phoneStatus_i = GetSharedInt(phoneStatus,i);
		     if(phoneStatus_i == BUSY)
				{
				 condnToWait = TRUE;
				 break;
				}
		    } */
			i = GetZeroIndex(phoneStatus);

		if(i==NOOFPHONES)
		   condnToWait=FALSE;
		else
			condnToWait = TRUE;
	
		if(condnToWait==TRUE)
		  WaitCV(condID1,lockID1);
	
	  }while(condnToWait==TRUE);
	  	
      /* all phones are free now */
      SetSharedInt(phoneStatus, phoneToUse, BUSY); /* phoneStatus[phoneToUse] = BUSY;*/
      /* president has obtained a phone now */
      ReleaseLock(lockID1);      
      /* Need to get an operator */
      AcquireLock(lockID2);
      /* loop to wait till an operator is available */
	  	
      while(GetSharedInt(freeOperators,0)==0)
	    WaitCV(condID4,lockID2);
	  	
	  /* president has to wait if there are no free operators available */
      /* Some operator is available. Though I don't know who it is yet, let us find out    */    
      /*
	  for(j=0;j<Nop;j++)
	  {
	  if(GetSharedInt(operatorStatus,j)==FREE)
	    {
	      operatorToUse = j;
	      break;
	    }
	 }
	 */
	 operatorToUse = GetOneIndex(operatorStatus);
      /* operator obtained */
      /* check if the operator to whom president goes for authentication is same as the one who permits him/her to make a call. */
      checkCorrectOperatorP = operatorToUse;
      AcquireLock(indOpLock[operatorToUse]);
      SetSharedInt(activate, operatorToUse, 2);
      SetSharedInt(operatorStatus, operatorToUse, BUSY);
      SetSharedInt(freeOperators, 0, GetSharedInt(freeOperators, 0) - 1);
	  ReleaseLock(lockID2);
      SetSharedInt(authMechanism, operatorToUse, 1); /* 1 for President | 2 for Senators | 3 for Visitors */
	 
      /* If operator is sleeping, wake up */
	  SignalCV(waitForCallerCV[operatorToUse],indOpLock[operatorToUse]);
	  while(GetSharedInt(activate,operatorToUse)==2)
	      WaitCV(waitForOperVerCV[operatorToUse],indOpLock[operatorToUse]); 
      ReleaseLock(indOpLock[operatorToUse]);  
      if(GetSharedInt(activate,operatorToUse)==0) /* President is denied access to phone.But this will never happen as there is only one president and we assume that his/her ID is never faked */
	  {
	  /*  printf("President is denied access to Phone failing authentication!\n"); */
		Write("President is denied access to Phone failing authentication!\n",sizeof("President is denied access to Phone failing authentication!\n"),1);
	  }
      else if(GetSharedInt(activate, operatorToUse)==1) /* operator succesfully authenticates the identity of the president */
	 {
	  /* Now Talk */
	  talkingTime = RandomFunction(20); /* randomly generate the amount of time the president is talking */
          /* loop for the president to talk on the phone for the randomly generated time period */
	  for (j=1;j<=talkingTime;j++){
	    /*printf("President \t  %d \t\t %d/%d units \t %d \t\t %d \t    ACCEPTED       NOTAPPLICABLE - verified by operator %d \n",phoneToUse+1,j,talkingTime,operatorToUse+1,presidentNumberOfCalls+1,checkCorrectOperatorP+1);*/
		/*AcquireLock(displayLock); */
		Write("President \t ",13,1);
	    num = phoneToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write("\t\t ",5,1);	    
	    itoa(printing,10,j);
	    Write(printing,sizeof(printing),1);
	    Write("/",1,1);
	    num=talkingTime;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" units \t ",10,1);
	    num=operatorToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \t\t ",6,1);
	    num=presidentNumberOfCalls+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \t   ACCEPTED      NOTAPPLICABLE - verified by operator ",56,1);
	    num=checkCorrectOperatorP+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \n",3,1);
		/*ReleaseLock(displayLock);*/
	   /* Yield();*/
	  }
	  /* president is done talking */	  
	  /* Set the status to be free */
	  AcquireLock(lockID1);
	  SetSharedInt(phoneStatus, phoneToUse, FREE);
	  SetSharedInt(presidentStatus,0,0);
	  BroadcastCV(condID2,lockID1); /* wake up all the senators waiting to talk */
	  BroadcastCV(condID3,lockID1); /* wake up all the visitors waiting to talk */
	  ReleaseLock(lockID1);
	}
      /* president goes away  */
      /* president waits for a random amount of time before coming back to make the next call. Remember maximum number of calls allowed is 5 */
      waitingTime = RandomFunction(4);
      for(j=0;j<waitingTime;j++)
	{
	  Yield();
	}
      presidentNumberOfCalls++; /* increment the number of calls made by the president */
    }
  Exit(0);
}
Example #27
0
TArray<FArrangedWidget> FHittestGrid::GetBubblePath( FVector2D DesktopSpaceCoordinate, bool bIgnoreEnabledStatus )
{
	if (WidgetsCachedThisFrame->Num() > 0 && Cells.Num() > 0)
	{
		const FVector2D CursorPositionInGrid = DesktopSpaceCoordinate - GridOrigin;
		const FIntPoint CellCoordinate = FIntPoint(
			FMath::Min( FMath::Max(FMath::FloorToInt(CursorPositionInGrid.X / CellSize.X), 0), NumCells.X-1),
			FMath::Min( FMath::Max(FMath::FloorToInt(CursorPositionInGrid.Y / CellSize.Y), 0), NumCells.Y-1 ) );
		
		static FVector2D LastCoordinate = FVector2D::ZeroVector;
		if ( LastCoordinate != CursorPositionInGrid )
		{
			LastCoordinate = CursorPositionInGrid;
		}

		checkf( (CellCoordinate.Y*NumCells.X + CellCoordinate.X) < Cells.Num(), TEXT("Index out of range, CellCoordinate is: %d %d CursorPosition is: %f %f"), CellCoordinate.X, CellCoordinate.Y, CursorPositionInGrid.X, CursorPositionInGrid.Y );

		const TArray<int32>& IndexesInCell = CellAt( CellCoordinate.X, CellCoordinate.Y ).CachedWidgetIndexes;
		int32 HitWidgetIndex = INDEX_NONE;
	
		// Consider front-most widgets first for hittesting.
		for ( int32 i = IndexesInCell.Num()-1; i>=0 && HitWidgetIndex==INDEX_NONE; --i )
		{
			check( IndexesInCell[i] < WidgetsCachedThisFrame->Num() ); 

			const FCachedWidget& TestCandidate = (*WidgetsCachedThisFrame)[IndexesInCell[i]];

			// Compute the render space clipping rect (FGeometry exposes a layout space clipping rect).
			FSlateRotatedRect DesktopOrientedClipRect = 
				TransformRect(
					Concatenate(
						Inverse(TestCandidate.CachedGeometry.GetAccumulatedLayoutTransform()), 
						TestCandidate.CachedGeometry.GetAccumulatedRenderTransform()
					), 
					FSlateRotatedRect(TestCandidate.CachedGeometry.GetClippingRect().IntersectionWith(TestCandidate.ClippingRect))
				);

			if (DesktopOrientedClipRect.IsUnderLocation(DesktopSpaceCoordinate) && TestCandidate.WidgetPtr.IsValid())
			{
				HitWidgetIndex = IndexesInCell[i];
			}
		}

		if (HitWidgetIndex != INDEX_NONE)
		{
			TArray<FArrangedWidget> BubblePath;
			int32 CurWidgetIndex=HitWidgetIndex;
			bool bPathUninterrupted = false;
			do
			{
				check( CurWidgetIndex < WidgetsCachedThisFrame->Num() );
				const FCachedWidget& CurCachedWidget = (*WidgetsCachedThisFrame)[CurWidgetIndex];
				const TSharedPtr<SWidget> CachedWidgetPtr = CurCachedWidget.WidgetPtr.Pin();
				
				bPathUninterrupted = CachedWidgetPtr.IsValid();
				if (bPathUninterrupted)
				{
					BubblePath.Insert(FArrangedWidget(CachedWidgetPtr.ToSharedRef(), CurCachedWidget.CachedGeometry), 0);
					CurWidgetIndex = CurCachedWidget.ParentIndex;
				}
			}
			while (CurWidgetIndex != INDEX_NONE && bPathUninterrupted);
			
			if (!bPathUninterrupted)
			{
				// A widget in the path to the root has been removed, so anything
				// we thought we had hittest is no longer actually there.
				// Pretend we didn't hit anything.
				BubblePath = TArray<FArrangedWidget>();
			}

			// Disabling a widget disables all of its logical children
			// This effect is achieved by truncating the path to the
			// root-most enabled widget.
			if ( !bIgnoreEnabledStatus )
			{
				const int32 DisabledWidgetIndex = BubblePath.IndexOfByPredicate( []( const FArrangedWidget& SomeWidget ){ return !SomeWidget.Widget->IsEnabled( ); } );
				if (DisabledWidgetIndex != INDEX_NONE)
				{
					BubblePath.RemoveAt( DisabledWidgetIndex, BubblePath.Num() - DisabledWidgetIndex );
				}
			}
			
			return BubblePath;
		}
		else
		{
			return TArray<FArrangedWidget>();
		}
	}
	else
	{
		return TArray<FArrangedWidget>();
	}
}
Example #28
0
// This code reads up the string, discards the bookends, and saves only the gibberish itself.
// the bEscaped option allows you to load a normal ASCII-Armored file if off, and allows
// you to load an escaped ASCII-armored file (such as inside the contracts when the public keys
// are escaped with a "- " before the rest of the ------- starts.)
//
bool OTASCIIArmor::LoadFromString(OTString & theStr, // input
                                  bool bEscaped/*=false*/, 
                                  const // This szOverride sub-string determines where the content starts, when loading.
                                  std::string str_override/*="-----BEGIN"*/) // Default is "-----BEGIN"
{
    // Should never be 0 size, as default is "-----BEGIN"
    // But if you want to load a private key, try "-----BEGIN ENCRYPTED PRIVATE" instead.
    // *smile*
    const std::string str_end_line = "-----END"; // Someday maybe allow parameterized option for this.
    // ------------------------------------------
    const int nBufSize  = 2100; // todo: hardcoding
    const int nBufSize2 = 2048; // todo: hardcoding
    // -----------------------------
	char buffer1[2100];         // todo: hardcoding
    
    std::fill(&buffer1[0], &buffer1[(nBufSize-1)], 0); // Initializing to 0.
	
	bool bContentMode            = false;  // "Currently IN content mode."
	bool bHaveEnteredContentMode = false;  // "Have NOT YET entered content mode."
	
	// Clear out whatever string might have been in there before.
	Release();
	
	// Load up the string from theStr, 
	// (bookended by "-----BEGIN ... -----" and "END-----" messages)
	bool bIsEOF = false;
	theStr.reset(); // So we can call theStr.sgets(). Making sure position is at start of string.
	
	do
	{
		bIsEOF = !(theStr.sgets(buffer1, nBufSize2)); // 2048
		
		std::string line		= buffer1;	
		const char * pConstBuf	= line.c_str();
		char * pBuf				= (char *)pConstBuf;
		
		// It's not a blank line.
		if (line.length() < 2)
		{
			continue;
		}
		
		// if we're on a dashed line...
		else if (line.at(0) == '-' && 
                 line.at(2) == '-' && 
                 line.at(3) == '-' &&
				 (bEscaped ? (line.at(1) == ' ') : (line.at(1) == '-') )
                )
		{			
			// If I just hit a dash, that means there are only two options:
			
			// a. I have not yet entered content mode, and potentially just now entering it for the first time.
			if (!bHaveEnteredContentMode)
			{
                // str_override defaults to:  "-----BEGIN" (If you want to load a private key instead,
                // Try passing "-----BEGIN ENCRYPTED PRIVATE" instead of going with the default.)
                //
				if (line.find(str_override) != std::string::npos && 
                    line.at(0) == '-' && 
                    line.at(2) == '-' && 
					line.at(3) == '-' && 
                    (bEscaped ? (line.at(1) == ' ') : (line.at(1) == '-'))
                   )
				{
//					OTLog::Error("Reading ascii-armored contents...");
					bHaveEnteredContentMode = true;
					bContentMode = true;
					continue;
				}
				else
				{
					continue;
				}				
			}
			
			// b. I am now LEAVING content mode!
			else if (bContentMode &&
                     // str_end_line is "-----END"
                     (line.find(str_end_line) != std::string::npos))
			{
//				OTLog::Error("Finished reading ascii-armored contents.\n");
//				OTLog::vError("Finished reading ascii-armored contents:\n%s(END DATA)\n", Get());
				bContentMode   = false;
				continue;
			}
		}
		
		// Else we're on a normal line, not a dashed line.
		else
		{
			if (bHaveEnteredContentMode && bContentMode)
			{
				if (line.compare(0,8,"Version:") == 0)
				{
//					OTLog::Error("Skipping version line...\n");
					continue;
				}
				if (line.compare(0,8,"Comment:") == 0)
				{
//					OTLog::Error("Skipping comment line...\n");
					continue;
				}
			}
			
		}
		
		// Here we save the line to member variables, if appropriate
		if (bContentMode)
		{
			Concatenate("%s\n", pBuf);
		}
	}
	while(!bIsEOF && (bContentMode || !bHaveEnteredContentMode));
	
	
	// reset the string position back to 0
	theStr.reset();
	
	if (!bHaveEnteredContentMode)
	{
		OTLog::vError("Error in OTASCIIArmor::LoadFromString: EOF before ascii-armored "
                      "content found, in:\n\n%s\n\n", theStr.Get());
		return false;
	}
	else if (bContentMode)
	{
		OTLog::vError("Error in OTASCIIArmor::LoadFromString: EOF while still reading "
                      "content, in:\n\n%s\n\n", theStr.Get());
		return false;
	}
	else
		return true;
}
Example #29
0
	inline void Concatenate(const String& str)
	{
		Concatenate(str.c_str());
	}
Example #30
0
int32 SSlider::OnPaint( const FPaintArgs& Args, const FGeometry& AllottedGeometry, const FSlateRect& MyClippingRect, FSlateWindowElementList& OutDrawElements, int32 LayerId, const FWidgetStyle& InWidgetStyle, bool bParentEnabled ) const
{
	// we draw the slider like a horizontal slider regardless of the orientation, and apply a render transform to make it display correctly.
	// However, the AllottedGeometry is computed as it will be rendered, so we have to use the "horizontal orientation" when doing drawing computations.
	const float AllottedWidth = Orientation == Orient_Horizontal ? AllottedGeometry.GetLocalSize().X : AllottedGeometry.GetLocalSize().Y;
	const float AllottedHeight = Orientation == Orient_Horizontal ? AllottedGeometry.GetLocalSize().Y : AllottedGeometry.GetLocalSize().X;

	float HandleRotation;
	FVector2D HandleTopLeftPoint;
	FVector2D SliderStartPoint;
	FVector2D SliderEndPoint;

	// calculate slider geometry as if it's a horizontal slider (we'll rotate it later if it's vertical)
	const FVector2D HandleSize = Style->NormalThumbImage.ImageSize;
	const FVector2D HalfHandleSize = 0.5f * HandleSize;
	const float Indentation = IndentHandle.Get() ? HandleSize.X : 0.0f;

	const float SliderLength = AllottedWidth - Indentation;
	const float SliderPercent = ValueAttribute.Get();
	const float SliderHandleOffset = SliderPercent * SliderLength;
	const float SliderY = 0.5f * AllottedHeight;

	HandleRotation = 0.0f;
	HandleTopLeftPoint = FVector2D(SliderHandleOffset - ( HandleSize.X * SliderPercent ) + 0.5f * Indentation, SliderY - HalfHandleSize.Y);

	SliderStartPoint = FVector2D(HalfHandleSize.X, SliderY);
	SliderEndPoint = FVector2D(AllottedWidth - HalfHandleSize.X, SliderY);

	FSlateRect RotatedClippingRect = MyClippingRect;
	FGeometry SliderGeometry = AllottedGeometry;
	
	// rotate the slider 90deg if it's vertical. The 0 side goes on the bottom, the 1 side on the top.
	if (Orientation == Orient_Vertical)
	{
		// Do this by translating along -X by the width of the geometry, then rotating 90 degreess CCW (left-hand coords)
		FSlateRenderTransform SlateRenderTransform = TransformCast<FSlateRenderTransform>(Concatenate(Inverse(FVector2D(AllottedWidth, 0)), FQuat2D(FMath::DegreesToRadians(-90.0f))));
		// create a child geometry matching this one, but with the render transform.
		SliderGeometry = AllottedGeometry.MakeChild(
			FVector2D(AllottedWidth, AllottedHeight), 
			FSlateLayoutTransform(), 
			SlateRenderTransform, FVector2D::ZeroVector);
		// The clipping rect is already given properly in window space. But we do not support layout rotations, so our local space rendering cannot
		// get the clipping rect into local space properly for the local space clipping we do in the shader.
		// Thus, we transform the clip coords into local space manually, UNDO the render transform so it will clip properly,
		// and then bring the clip coords back into window space where DrawElements expect them.
		RotatedClippingRect = TransformRect(
			Concatenate(
				Inverse(SliderGeometry.GetAccumulatedLayoutTransform()), 
				Inverse(SlateRenderTransform),
				SliderGeometry.GetAccumulatedLayoutTransform()), 
			MyClippingRect);
	}

	const bool bEnabled = ShouldBeEnabled(bParentEnabled);
	const ESlateDrawEffect::Type DrawEffects = bEnabled ? ESlateDrawEffect::None : ESlateDrawEffect::DisabledEffect;

	// draw slider bar
	auto BarTopLeft = FVector2D(SliderStartPoint.X, SliderStartPoint.Y - Style->BarThickness * 0.5f);
	auto BarSize = FVector2D(SliderEndPoint.X - SliderStartPoint.X, Style->BarThickness);
	FSlateDrawElement::MakeBox(
		OutDrawElements,
		LayerId,
		SliderGeometry.ToPaintGeometry(BarTopLeft, BarSize),
		LockedAttribute.Get() ? &Style->DisabledBarImage : &Style->NormalBarImage,
		RotatedClippingRect,
		DrawEffects,
		SliderBarColor.Get().GetColor(InWidgetStyle) * InWidgetStyle.GetColorAndOpacityTint()
		);

	++LayerId;

	// draw slider thumb
	FSlateDrawElement::MakeBox( 
		OutDrawElements,
		LayerId,
		SliderGeometry.ToPaintGeometry(HandleTopLeftPoint, Style->NormalThumbImage.ImageSize),
		LockedAttribute.Get() ? &Style->DisabledThumbImage : &Style->NormalThumbImage,
		RotatedClippingRect,
		DrawEffects,
		SliderHandleColor.Get().GetColor(InWidgetStyle) * InWidgetStyle.GetColorAndOpacityTint()
	);

	return LayerId;
}