DHTMLX Gantt chart group same task in a row expand collapse issue - grouping

I am using gantt chart in which the data will be in following format
A
A1 1/4/2016
A1 2/4/2016
A2 4/4/2016
B
B1 4/4/2016
B2 5/4/2016
I want to group the same tasks to display in single row
I have achieved this but when I expand multiple categories the chart data does not show properly
As you can see Audi05 should display one row below.
Here is my customized code:
/* Custom Code */
gantt.getGlobalTaskIndex = function (id) {
dhtmlx.assert(id, "Invalid argument");
if (index_list.length!=0 && _.where(index_list,{id:id}).length > 0){
return _.where(index_list,{id:id})[0].pos;
}
var ord = this._order;
for(var i= 0, count = ord.length; i < count; i++)
if(ord[i] == id)
return i;
return -1;
};
/* End */
gantt._render_grid_item = function (item) {
if (!gantt._is_grid_visible())
return null;
/* Issue in the Custom Code */
var index = index_list.length;
if(item.vehicle_id)
{
var isExist=task_list.some(function (el) {
var res=(el.id===item.vehicle_id);
return res;
});
if(!isExist){
task_list.push({'id':item.vehicle_id});
}
else{
return null;
}
}
/* End */
var columns = this.getGridColumns();
var cells = [];
var width = 0;
for (var i = 0; i < columns.length; i++) {
var last = i == columns.length - 1;
var col = columns[i];
var cell;
var value;
if (col.name == "add") {
value = "<div class='gantt_add'></div>";
} else {
if (col.template)
value = col.template(item);
else
value = item[col.name];
if (value instanceof Date)
value = this.templates.date_grid(value, item);
value = "<div class='gantt_tree_content'>" + value + "</div>";
}
var css = "gantt_cell" + (last ? " gantt_last_cell" : "");
var tree = "";
if (col.tree) {
for (var j = 0; j < item.$level; j++)
tree += this.templates.grid_indent(item);
var has_child = this._has_children(item.id);
if (has_child) {
tree += this.templates.grid_open(item);
tree += this.templates.grid_folder(item);
} else {
tree += this.templates.grid_blank(item);
tree += this.templates.grid_file(item);
}
}
var style = "width:" + (col.width - (last ? 1 : 0)) + "px;";
if (dhtmlx.defined(col.align))
style += "text-align:" + col.align + ";";
cell = "<div class='" + css + "' style='" + style + "'>" + tree + value + "</div>";
cells.push(cell);
}
var css = item.$index % 2 === 0 ? "" : " odd";
css += (item.$transparent) ? " gantt_transparent" : "";
css += (item.$dataprocessor_class ? " " + item.$dataprocessor_class : "");
if (this.templates.grid_row_class) {
var css_template = this.templates.grid_row_class.call(this, item.start_date, item.end_date, item);
if (css_template)
css += " " + css_template;
}
if (this.getState().selected_task == item.id) {
css += " gantt_selected";
}
var el = document.createElement("div");
el.className = "gantt_row" + css;
el.style.height = this.config.row_height + "px";
el.style.lineHeight = (gantt.config.row_height) + "px";
el.setAttribute(this.config.task_attribute, item.id);
el.innerHTML = cells.join("");
return el;
};
gantt.open = function (id) {
task_list=[];
gantt._set_item_state(id, true);
this.callEvent("onTaskOpened", [id]);
};
gantt.close = function (id) {
task_list=[];
gantt._set_item_state(id, false);
this.callEvent("onTaskClosed", [id]);
};
gantt._get_task_coord = function(task, to_start, x_correction){
to_start = to_start !== false;
x_correction = x_correction || 0;
var isMilestone = (this._get_safe_type(task.type) == this.config.types.milestone);
var date = null;
if(to_start || isMilestone){
date = (task.start_date || this._default_task_date(task));
}else{
date = (task.end_date || this.calculateEndDate(this._default_task_date(task)));
}
var x = this.posFromDate(date),
//y = this.getTaskTop(task.id);
/* Custom code */
y = this.getTaskTop(task);
if(task.vehicle_id)
{
var isExist=vehicle_list.some(function (el) {
var res=(el.id===task.vehicle_id);
return res;
});
if(!isExist){
vehicle_list.push({'id':task.vehicle_id,'y':y});
}
else{
y = _.where(vehicle_list, {id:task.vehicle_id})[0].y;
}
}
/* End */
if(isMilestone){
if(to_start){
x -= x_correction;
}else{
x += x_correction;
}
}
return {x:x, y:y};
};
gantt.getTaskPosition = function(task, start_date, end_date){
var x = this.posFromDate(start_date || task.start_date);
var x2 = this.posFromDate(end_date || task.end_date);
x2 = Math.max(x, x2);
//var y = this.getTaskTop(task.id);
var y = this.getTaskTop(task); // Custom code
var height = this.config.task_height;
return {
left:x,
top:y,
height : height,
width: Math.max((x2 - x), 0)
};
};

Please, check the sample with a similar way of displaying tasks and subtasks:
http://docs.dhtmlx.com/gantt/samples/04_customization/18_subtasks_displaying.html

Related

Designing a general data structure for data that is used by OGR API

I'm trying to create a general data structure that process and creates a feature
I'm trying to make a more generic serialization/deserialization format for pushing data via that BinaryMessageBuffer and for getting the data via BinaryMessageBuffer too.
here is the code that creates the data.
void S3W::IWFSAreaData::ProcessBuffer(S3W::BinaryMessageBuffer &buffer)
{
std::string areaName = "";
unsigned int numGeometries;
double minH;
double maxH;
areaName = buffer.consumeString();
minH = buffer.consumeDouble();
maxH = buffer.consumeDouble();
numGeometries = buffer.consumeUint();
OGRMultiPoint mp;
for (size_t k = 0; k < numGeometries; k++)
{
double x, y;
x = buffer.consumeDouble();
y = buffer.consumeDouble();
OGRPoint point;
point.setX(x);
point.setY(y);
mp.addGeometry(&point);
}
OGRFeature *poFeature = OGRFeature::CreateFeature(m_Layer->GetLayerDefn());
if (poFeature)
{
poFeature->SetField("gfname", areaName.c_str());
poFeature->SetField("minHeight", minH);
poFeature->SetField("maxHeight", maxH);
poFeature->SetGeometry(&mp);
if (m_Layer->CreateFeature(poFeature) != OGRERR_NONE)
{
std::cout << "error inserting an area" << std::endl;
}
else
{
std::cout << "Created a feature" << std::endl;
}
}
OGRFeature::DestroyFeature(poFeature);
}
here is the code for receiving the data:
void S3W::IWFSAreaData::SrvReceive(S3W::BinaryMessageBuffer & data)
{
// Reset Reading (Although not necessary now because it hasnt been read yet, this is good practice before reading WFS data)
m_Layer->ResetReading();
OGRFeature *Feature;
while ((Feature = m_Layer->GetNextFeature()) != NULL)
{
// Variable initialised to contain the definitions of all of the fileds in the WFS Layer
OGRFeatureDefn *FeatureDefinition = m_Layer->GetLayerDefn();
for (int i = 0; i < FeatureDefinition->GetFieldCount(); i++)
{
// Variable initialised to contain field data at the current index of i
OGRFieldDefn *FieldDefinition = FeatureDefinition->GetFieldDefn(i);
std::string fieldName = FieldDefinition->GetNameRef();
if (FieldDefinition->GetType() == OFTReal && fieldName == "minHeight")
{
double minHeight = Feature->GetFieldAsDouble(i);
data.add(minHeight);
}
else if (FieldDefinition->GetType() == OFTReal && fieldName == "maxHeight")
{
double maxHeight = Feature->GetFieldAsDouble(i);
data.add(maxHeight);
}
else if (FieldDefinition->GetType() == OFTString && fieldName == "gfname")
{
const char *gfName = Feature->GetFieldAsString(i);
data.add(gfName);
}
}
// Variable initialised to contain Geometry point data for the field at the current index of i
OGRGeometry *Geometry = Feature->GetGeometryRef();
if (Geometry != NULL && wkbFlatten(Geometry->getGeometryType()) == wkbMultiPoint)
{
OGRMultiPoint *poMultipoint = (OGRMultiPoint *)Geometry;
if (poMultipoint)
{
unsigned int NumberOfGeometries = poMultipoint->getNumGeometries();
data.add(NumberOfGeometries);
for (unsigned int i = 0; i < NumberOfGeometries; i++)
{
OGRGeometry *geom = poMultipoint->getGeometryRef(i);
if (geom)
{
OGRPoint *Point = (OGRPoint *)geom;
if (Point)
{
double x = Point->getX();
double y = Point->getY();
data.add(x);
data.add(y);
}
}
}
}
}
else
{
// if area has no geometry add empty positions
double x = 0, y = 0;
for (int i = 0; i < 2; i++)
{
data.add(x);
data.add(y);
}
}
OGRFeature::DestroyFeature(Feature);
}
}
What kind of data structure that can be used to design a more general work for creating feature and for receiving a feature, with generic "fields".

Set values in an array within an object

I've got an issue with an Object array in an object:
I have a class with an object array:
class element
{
public:
element() {};
LinePiece* arrayLP;
and I have a class thats in the array:
class LinePiece
{
public:
LinePiece() {};
AnsiString Type;
int ElementNr;
int Status;
int X, Y;
so within the Element object I have a LinePiece array. The odd thing is, when I fill in ElementArray[1].LPArray[0]; it gets overwritten by the next object (ElementArray[2].LPArray[0];
I fill it with the following code:
String FileBuffer;
String Regel;
String Code;
element* GetElementInfo()
{
//alle onderdelen van een Elementobject
String OrderNumber; //ON
String OrderBrand; //MO
String ElementNumber; //SN
String ElementMarking; //RS
String ReinforcementPattern; //OW
String CalculationNumber; //CN
String ElementLength; //LE
String ElementWidth; //WD
String ElementBeginX; //BP
String ConcreteThickness; //TH
String Isulation; //IH
String Weight; //NW
element *ElementArray = new element[100];
LinePiece *LPArray = new LinePiece[100];
bool firstElement = true;
int Index =0;
int LPIndex = 0;
for(int i = 1; i <= FileBuffer.Length(); i++)
{
if(FileBuffer[i] != 0)
{
if(FileBuffer[i] != IntToStr('\r')) //controleren of je op einde regel zit, zoniet vul de string "regel" aan
{
if(FileBuffer[i] != IntToStr('\r') && FileBuffer[i] != IntToStr('\n'))
{
Regel = Regel + FileBuffer[i];
}
}
else //kijken wat er op de regel staat
{
Code = Regel.SubString(0,2);
if(Code == "ON") //Ordernummer
{
OrderNumber = Regel.SubString(4, (Regel.Length() -3));
Regel = "";
}
if(Code =="MO") //Ordermerk
{
OrderBrand = Regel.SubString(4, (Regel.Length() -3));
Regel = "";
}
if(Code =="SN") //Element nummer
{
ElementNumber = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code =="RS") //Element marking
{
ElementMarking = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code =="CN") //Calculatienummer
{
CalculationNumber = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code == "LE") //Element lengte
{
ElementLength = Regel.SubString(4,(Regel.Length()-3));
Regel = "";
}
if(Code == "WD") //element breedte
{
ElementWidth = Regel.SubString(4,(Regel.Length()-3));
Regel = "";
}
if(Code == "BP") //beginpunt X
{
ElementBeginX = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if (Code == "OW") //Wapeningspatroon
{
ReinforcementPattern = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code == "TH") //Beton dikte
{
ConcreteThickness = Regel.SubString(4,(Regel.Length()-3));
Regel = "";
}
if(Code == "IH") //isolatie dikte
{
Isulation = Regel.SubString(4,(Regel.Length()-3));
Regel = "";
}
if(Code == "NW") //Gewicht
{
Weight = Regel.SubString(4, (Regel.Length()-3));
Regel = "";
}
if(Code == "CO") //Contour
{
String geheleRegel = Regel.SubString(4, (Regel.Length() -3));
int EleNr = 0;
int Status = 0;
//geheleRegel doormidden hakken voor x en y waardes.
String X = geheleRegel.SubString(0, (geheleRegel.Length() /2));
String Y = geheleRegel.SubString(geheleRegel.Length()/2 +1, geheleRegel.Length());
LinePiece lpObject(Code, EleNr, Status, StrToInt(X), StrToInt(Y));
LPArray[LPIndex] = lpObject;
LPIndex++;
Regel = "";
}
if(Code == "*" && firstElement == false) //Nieuw element
{
if(OrderNumber == "")
{
OrderNumber =="-";
}
if(OrderBrand == "")
{
OrderBrand = "-";
}
if(ElementNumber == "")
{
ElementNumber = "-";
}
if(ElementMarking == "")
{
ElementMarking = "-";
}
if (ReinforcementPattern == "")
{
ReinforcementPattern = "-";
}
if (CalculationNumber == "")
{
CalculationNumber = "-";
}
if(ElementLength == "")
{
ElementLength = 0;
}
if(ElementWidth == "")
{
ElementWidth = 0;
}
if(ElementBeginX == "")
{
ElementBeginX = 0;
}
if(ConcreteThickness == "")
{
ConcreteThickness = 0;
}
if(Isulation == "")
{
Isulation = 0;
}
if(Weight == "")
{
Weight = 0;
}
element ElementObject(OrderNumber, OrderBrand, ElementNumber, ElementMarking,
ReinforcementPattern, CalculationNumber, StrToInt(ElementLength), StrToInt(ElementWidth),
StrToInt(ElementBeginX), StrToInt(ConcreteThickness),StrToInt(Isulation),
Weight, LPArray);
ElementArray[Index] = ElementObject;
LPIndex = 0; /resetting LPIndex
Index++;
}
else
{
Regel="";
}
if (Code == "*")
{
firstElement = false;
}
}
}
}
return ElementArray;
}
So for some reason, it doesn't make 'X' different LPArrays, but overwrites all the LParrays with the last one. How can I fix this?
Your initialization code should looks like:
element *ElementArray = new element[100];
for ( int n = 0; n < 100; ++n )
ElementArray[n].arrayLP = new LinePiece[100];
so the behaviour you describe might be due to undefined bahaviour
you dont seem to delete your allocated array anywhere - that will cause memory leaks. Also if you want arrays and not vectors then you must obey rule of three (add copy constructor/operator and destructor).

sitecore workbox does not prompt for comment when approving multiple items

I have a sitecore workflow. When I approve an item with the Approve button right next to the item it asks for comment. When I approve multiple items using the Approve (selected) or Approve (all) buttons it does not ask for comment. Why is that? Can I make it ask for comment and associate that comment with all the items that being approved? Thanks
In order to enable comments for Selected or All items you need to:
Copy Website\sitecore\shell\Applications\Workbox\Workbox.xml to Website\sitecore\shell\Override\ directory and change <CodeBeside Type="..." /> to <CodeBeside Type="My.Assembly.Namespace.WorkboxForm,My.Assembly" /> where My.Assembly and My.Assembly.Namespace matches your project.
Create your own class WorkboxForm that will override Sitecore WorkboxForm and match Type from point 1. and use the edited code of WorkBox form:
using Sitecore;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Exceptions;
using Sitecore.Globalization;
using Sitecore.Resources;
using Sitecore.Shell.Framework.CommandBuilders;
using Sitecore.Text;
using Sitecore.Web;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.Sheer;
using Sitecore.Web.UI.XmlControls;
using Sitecore.Workflows;
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
namespace My.Assembly.Namespace
{
public class WorkboxForm : Sitecore.Shell.Applications.Workbox.WorkboxForm
{
private NameValueCollection stateNames;
public void CommentMultiple(ClientPipelineArgs args)
{
Assert.ArgumentNotNull(args, "args");
if (!args.IsPostBack)
{
Context.ClientPage.ClientResponse.Input("Enter a comment:", string.Empty);
args.WaitForPostBack();
}
else if (args.Result.Length > 2000)
{
Context.ClientPage.ClientResponse.ShowError(new Exception(string.Format("The comment is too long.\n\nYou have entered {0} characters.\nA comment cannot contain more than 2000 characters.", args.Result.Length)));
Context.ClientPage.ClientResponse.Input("Enter a comment:", string.Empty);
args.WaitForPostBack();
}
else
{
if (args.Result == null || args.Result == "null" || args.Result == "undefined")
return;
IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;
if (workflowProvider == null)
return;
IWorkflow workflow = workflowProvider.GetWorkflow(Context.ClientPage.ServerProperties["workflowid"] as string);
if (workflow == null)
return;
string stateId = (string)Context.ClientPage.ServerProperties["ws"];
string command = (string)Context.ClientPage.ServerProperties["command"];
string[] itemRefs = ((string)Context.ClientPage.ServerProperties["ids"] ?? string.Empty).Split(new[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
bool flag = false;
int num = 0;
foreach (string itemRef in itemRefs)
{
string[] strArray = itemRef.Split(new[] { ',' });
Item items = Context.ContentDatabase.Items[strArray[0], Language.Parse(strArray[1]), Sitecore.Data.Version.Parse(strArray[2])];
if (items != null)
{
WorkflowState state = workflow.GetState(items);
if (state.StateID == stateId)
{
try
{
workflow.Execute(command, items, args.Result, true, new object[0]);
}
catch (WorkflowStateMissingException)
{
flag = true;
}
++num;
}
}
}
if (flag)
SheerResponse.Alert("One or more items could not be processed because their workflow state does not specify the next step.", new string[0]);
if (num == 0)
{
Context.ClientPage.ClientResponse.Alert("There are no selected items.");
}
else
{
UrlString urlString = new UrlString(WebUtil.GetRawUrl());
urlString["reload"] = "1";
Context.ClientPage.ClientResponse.SetLocation(urlString.ToString());
}
}
}
public override void HandleMessage(Message message)
{
Assert.ArgumentNotNull(message, "message");
switch (message.Name)
{
case "workflow:sendselectednew":
SendSelectedNew(message);
return;
case "workflow:sendallnew":
SendAllNew(message);
return;
}
base.HandleMessage(message);
}
protected override void DisplayState(IWorkflow workflow, WorkflowState state, DataUri[] items, System.Web.UI.Control control, int offset, int pageSize)
{
Assert.ArgumentNotNull(workflow, "workflow");
Assert.ArgumentNotNull(state, "state");
Assert.ArgumentNotNull(items, "items");
Assert.ArgumentNotNull(control, "control");
if (items.Length <= 0)
return;
int num = offset + pageSize;
if (num > items.Length)
num = items.Length;
for (int index = offset; index < num; ++index)
{
Item obj = Context.ContentDatabase.Items[items[index]];
if (obj != null)
CreateItem(workflow, obj, control);
}
Border border1 = new Border();
border1.Background = "#e9e9e9";
Border border2 = border1;
control.Controls.Add(border2);
border2.Margin = "0px 4px 0px 16px";
border2.Padding = "2px 8px 2px 8px";
border2.Border = "1px solid #999999";
foreach (WorkflowCommand workflowCommand in WorkflowFilterer.FilterVisibleCommands(workflow.GetCommands(state.StateID)))
{
XmlControl xmlControl1 = (XmlControl) Resource.GetWebControl("WorkboxCommand");
Assert.IsNotNull(xmlControl1, "workboxCommand is null");
xmlControl1["Header"] = (workflowCommand.DisplayName + " " + Translate.Text("(selected)"));
xmlControl1["Icon"] = workflowCommand.Icon;
xmlControl1["Command"] = ("workflow:sendselectednew(command=" + workflowCommand.CommandID + ",ws=" + state.StateID + ",wf=" + workflow.WorkflowID + ")");
border2.Controls.Add(xmlControl1);
XmlControl xmlControl2 = (XmlControl) Resource.GetWebControl("WorkboxCommand");
Assert.IsNotNull(xmlControl2, "workboxCommand is null");
xmlControl2["Header"] = (workflowCommand.DisplayName + " " + Translate.Text("(all)"));
xmlControl2["Icon"] = workflowCommand.Icon;
xmlControl2["Command"] = ("workflow:sendallnew(command=" + workflowCommand.CommandID + ",ws=" + state.StateID + ",wf=" + workflow.WorkflowID + ")");
border2.Controls.Add(xmlControl2);
}
}
private static void CreateCommand(IWorkflow workflow, WorkflowCommand command, Item item, XmlControl workboxItem)
{
Assert.ArgumentNotNull(workflow, "workflow");
Assert.ArgumentNotNull(command, "command");
Assert.ArgumentNotNull(item, "item");
Assert.ArgumentNotNull(workboxItem, "workboxItem");
XmlControl xmlControl = (XmlControl) Resource.GetWebControl("WorkboxCommand");
Assert.IsNotNull(xmlControl, "workboxCommand is null");
xmlControl["Header"] = command.DisplayName;
xmlControl["Icon"] = command.Icon;
CommandBuilder commandBuilder = new CommandBuilder("workflow:send");
commandBuilder.Add("id", item.ID.ToString());
commandBuilder.Add("la", item.Language.Name);
commandBuilder.Add("vs", item.Version.ToString());
commandBuilder.Add("command", command.CommandID);
commandBuilder.Add("wf", workflow.WorkflowID);
commandBuilder.Add("ui", command.HasUI);
commandBuilder.Add("suppresscomment", command.SuppressComment);
xmlControl["Command"] = commandBuilder.ToString();
workboxItem.AddControl(xmlControl);
}
private void CreateItem(IWorkflow workflow, Item item, System.Web.UI.Control control)
{
Assert.ArgumentNotNull(workflow, "workflow");
Assert.ArgumentNotNull(item, "item");
Assert.ArgumentNotNull(control, "control");
XmlControl workboxItem = (XmlControl) Resource.GetWebControl("WorkboxItem");
Assert.IsNotNull(workboxItem, "workboxItem is null");
control.Controls.Add(workboxItem);
StringBuilder stringBuilder = new StringBuilder(" - (");
Language language = item.Language;
stringBuilder.Append(language.CultureInfo.DisplayName);
stringBuilder.Append(", ");
stringBuilder.Append(Translate.Text("version"));
stringBuilder.Append(' ');
stringBuilder.Append(item.Version);
stringBuilder.Append(")");
Assert.IsNotNull(workboxItem, "workboxItem");
workboxItem["Header"] = item.DisplayName;
workboxItem["Details"] = (stringBuilder).ToString();
workboxItem["Icon"] = item.Appearance.Icon;
workboxItem["ShortDescription"] = item.Help.ToolTip;
workboxItem["History"] = GetHistory(workflow, item);
workboxItem["HistoryMoreID"] = Control.GetUniqueID("ctl");
workboxItem["HistoryClick"] = ("workflow:showhistory(id=" + item.ID + ",la=" + item.Language.Name + ",vs=" + item.Version + ",wf=" + workflow.WorkflowID + ")");
workboxItem["PreviewClick"] = ("Preview(\"" + item.ID + "\", \"" + item.Language + "\", \"" + item.Version + "\")");
workboxItem["Click"] = ("Open(\"" + item.ID + "\", \"" + item.Language + "\", \"" + item.Version + "\")");
workboxItem["DiffClick"] = ("Diff(\"" + item.ID + "\", \"" + item.Language + "\", \"" + item.Version + "\")");
workboxItem["Display"] = "none";
string uniqueId = Control.GetUniqueID(string.Empty);
workboxItem["CheckID"] = ("check_" + uniqueId);
workboxItem["HiddenID"] = ("hidden_" + uniqueId);
workboxItem["CheckValue"] = (item.ID + "," + item.Language + "," + item.Version);
foreach (WorkflowCommand command in WorkflowFilterer.FilterVisibleCommands(workflow.GetCommands(item)))
CreateCommand(workflow, command, item, workboxItem);
}
private string GetHistory(IWorkflow workflow, Item item)
{
Assert.ArgumentNotNull(workflow, "workflow");
Assert.ArgumentNotNull(item, "item");
WorkflowEvent[] history = workflow.GetHistory(item);
string str;
if (history.Length > 0)
{
WorkflowEvent workflowEvent = history[history.Length - 1];
string text = workflowEvent.User;
string name = Context.Domain.Name;
if (text.StartsWith(name + "\\", StringComparison.OrdinalIgnoreCase))
text = StringUtil.Mid(text, name.Length + 1);
str = string.Format(Translate.Text("{0} changed from <b>{1}</b> to <b>{2}</b> on {3}."),
StringUtil.GetString(new[]
{
text,
Translate.Text("Unknown")
}), GetStateName(workflow, workflowEvent.OldState),
GetStateName(workflow, workflowEvent.NewState),
DateUtil.FormatDateTime(workflowEvent.Date, "D", Context.User.Profile.Culture));
}
else
str = Translate.Text("No changes have been made.");
return str;
}
private static DataUri[] GetItems(WorkflowState state, IWorkflow workflow)
{
Assert.ArgumentNotNull(state, "state");
Assert.ArgumentNotNull(workflow, "workflow");
ArrayList arrayList = new ArrayList();
DataUri[] items = workflow.GetItems(state.StateID);
if (items != null)
{
foreach (DataUri index in items)
{
Item obj = Context.ContentDatabase.Items[index];
if (obj != null && obj.Access.CanRead() && (obj.Access.CanReadLanguage() && obj.Access.CanWriteLanguage()) && (Context.IsAdministrator || obj.Locking.CanLock() || obj.Locking.HasLock()))
arrayList.Add(index);
}
}
return arrayList.ToArray(typeof(DataUri)) as DataUri[];
}
private string GetStateName(IWorkflow workflow, string stateID)
{
Assert.ArgumentNotNull(workflow, "workflow");
Assert.ArgumentNotNull(stateID, "stateID");
if (stateNames == null)
{
stateNames = new NameValueCollection();
foreach (WorkflowState workflowState in workflow.GetStates())
stateNames.Add(workflowState.StateID, workflowState.DisplayName);
}
return StringUtil.GetString(new[] {stateNames[stateID], "?"});
}
private void SendAll(Message message)
{
Assert.ArgumentNotNull(message, "message");
IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;
if (workflowProvider == null)
return;
string workflowID = message["wf"];
string stateID = message["ws"];
IWorkflow workflow = workflowProvider.GetWorkflow(workflowID);
if (workflow == null)
return;
WorkflowState state = workflow.GetState(stateID);
DataUri[] items = GetItems(state, workflow);
Assert.IsNotNull(items, "uris is null");
string comments = state != null ? state.DisplayName : string.Empty;
bool flag = false;
foreach (DataUri index in items)
{
Item obj = Context.ContentDatabase.Items[index];
if (obj != null)
{
try
{
workflow.Execute(message["command"], obj, comments, true, new object[0]);
}
catch (WorkflowStateMissingException)
{
flag = true;
}
}
}
if (flag)
SheerResponse.Alert("One or more items could not be processed because their workflow state does not specify the next step.", new string[0]);
UrlString urlString = new UrlString(WebUtil.GetRawUrl());
urlString["reload"] = "1";
Context.ClientPage.ClientResponse.SetLocation(urlString.ToString());
}
private void SendAllNew(Message message)
{
Assert.ArgumentNotNull(message, "message");
IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;
if (workflowProvider == null)
return;
string workflowID = message["wf"];
string stateID = message["ws"];
IWorkflow workflow = workflowProvider.GetWorkflow(workflowID);
if (workflow == null)
return;
if (message["ui"] != "1")
{
if (message["suppresscomment"] != "1")
{
string ids = String.Empty;
WorkflowState state = workflow.GetState(stateID);
DataUri[] items = GetItems(state, workflow);
foreach (DataUri dataUri in items)
{
ids += dataUri.ItemID + "," + dataUri.Language + "," + dataUri.Version.Number + "," + "::";
}
if (String.IsNullOrEmpty(ids))
{
Context.ClientPage.ClientResponse.Alert("There are no selected items.");
return;
}
Context.ClientPage.ServerProperties["ids"] = ids;
Context.ClientPage.ServerProperties["language"] = message["la"];
Context.ClientPage.ServerProperties["version"] = message["vs"];
Context.ClientPage.ServerProperties["command"] = message["command"];
Context.ClientPage.ServerProperties["ws"] = message["ws"];
Context.ClientPage.ServerProperties["workflowid"] = workflowID;
Context.ClientPage.Start(this, "CommentMultiple");
return;
}
}
// no comment - use the old SendAll
SendAll(message);
}
private void SendSelectedNew(Message message)
{
Assert.ArgumentNotNull(message, "message");
IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;
if (workflowProvider == null)
return;
string workflowID = message["wf"];
IWorkflow workflow = workflowProvider.GetWorkflow(workflowID);
if (workflow == null)
return;
if (message["ui"] != "1")
{
if (message["suppresscomment"] != "1")
{
string ids = String.Empty;
foreach (string str2 in Context.ClientPage.ClientRequest.Form.Keys)
{
if (str2 != null && str2.StartsWith("check_", StringComparison.InvariantCulture))
{
ids += Context.ClientPage.ClientRequest.Form["hidden_" + str2.Substring(6)] + "::";
}
}
if (String.IsNullOrEmpty(ids))
{
Context.ClientPage.ClientResponse.Alert("There are no selected items.");
return;
}
Context.ClientPage.ServerProperties["ids"] = ids;
Context.ClientPage.ServerProperties["language"] = message["la"];
Context.ClientPage.ServerProperties["version"] = message["vs"];
Context.ClientPage.ServerProperties["command"] = message["command"];
Context.ClientPage.ServerProperties["ws"] = message["ws"];
Context.ClientPage.ServerProperties["workflowid"] = workflowID;
Context.ClientPage.Start(this, "CommentMultiple");
return;
}
}
// no comment - use the old SendSelected
SendSelected(message);
}
private void SendSelected(Message message, string comment = null)
{
Assert.ArgumentNotNull(message, "message");
IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;
if (workflowProvider == null)
return;
string workflowID = message["wf"];
string str1 = message["ws"];
IWorkflow workflow = workflowProvider.GetWorkflow(workflowID);
if (workflow == null)
return;
int num = 0;
bool flag = false;
foreach (string str2 in Context.ClientPage.ClientRequest.Form.Keys)
{
if (str2 != null && str2.StartsWith("check_", StringComparison.InvariantCulture))
{
string[] strArray = Context.ClientPage.ClientRequest.Form["hidden_" + str2.Substring(6)].Split(new [] { ',' });
Item obj = Context.ContentDatabase.Items[strArray[0], Language.Parse(strArray[1]), Sitecore.Data.Version.Parse(strArray[2])];
if (obj != null)
{
WorkflowState state = workflow.GetState(obj);
if (state.StateID == str1)
{
try
{
workflow.Execute(message["command"], obj, comment ?? state.DisplayName, true, new object[0]);
}
catch (WorkflowStateMissingException)
{
flag = true;
}
++num;
}
}
}
}
if (flag)
SheerResponse.Alert("One or more items could not be processed because their workflow state does not specify the next step.", new string[0]);
if (num == 0)
{
Context.ClientPage.ClientResponse.Alert("There are no selected items.");
}
else
{
UrlString urlString = new UrlString(WebUtil.GetRawUrl());
urlString["reload"] = "1";
Context.ClientPage.ClientResponse.SetLocation(urlString.ToString());
}
}
}
}

Trouble figuring out what's wrong with this code on Linux

I'm having trouble figuring out why my code is not working on linux. I'm getting errors with the shared_ptrs like: (Partial List)
roject.cpp:21: error: ISO C++ forbids declaration of 'shared_ptr' with no type
project.cpp:21: error: expected ';' before '<' token
project.cpp:22: error: ISO C++ forbids declaration of 'shared_ptr' with no type
project.cpp:22: error: expected ';' before '<' token
project.cpp:23: error: ISO C++ forbids declaration of 'shared_ptr' with no type
project.cpp:23: error: expected ';' before '<' token
project.cpp:30: error: ISO C++ forbids declaration of 'shared_ptr' with no type
project.cpp:30: error: expected ';' before '<' token
project.cpp:37: error: ISO C++ forbids declaration of 'shared_ptr' with no type
project.cpp:37: error: expected ';' before '<' token
project.cpp:82: error: 'shared_ptr' has not been declared
project.cpp:82: error: expected ',' or '...' before '<' token
project.cpp:153: error: 'shared_ptr' has not been declared
project.cpp:153: error: expected ',' or '...' before '<' token
project.cpp: In member function 'void device_table::addCore(int)':
project.cpp:86: error: 'process' was not declared in this scope
project.cpp:88: error: 'struct device_item' has no member named 'process'
project.cpp:89: error: 'currentTime' was not declared in this scope
project.cpp:92: error: 'struct device_item' has no member named 'process'
project.cpp:98: error: 'struct device_item' has no member named 'process'
project.cpp:104: error: 'struct device_item' has no member named 'process'
project.cpp:110: error: 'struct device_item' has no member named 'process'
project.cpp:124: error: 'process_state' is not a class or namespace
project.cpp:130: error: 'process_state' is not a class or namespace
project.cpp:137: error: 'struct device_item' has no member named 'process'
project.cpp:137: error: 'process' was not declared in this scope
project.cpp:138: error: 'currentTime' was not declared in this scope
project.cpp:140: error: 'process_state' is not a class or namespace
project.cpp: In member function 'void device_table::addDisk(int)':
project.cpp:156: error: 'struct device_item' has no member named 'process'
project.cpp:156: error: 'disk' was not declared in this scope
project.cpp:157: error: 'currentTime' was not declared in this scope
project.cpp:167: error: 'process_state' is not a class or namespace
project.cpp: In member function 'void device_table::checkCoreAndDisk(int)':
Here's my code. I realized I shouldn't have used vectors. There's always a next time.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <memory>
#include <algorithm>
#include <queue>
using namespace std;
enum process_state { P_NONE, READY, RUNNING, WAITING };
enum event_component { E_NONE, START, CORE, TTY, DISK };
struct data_entry {
string text;
int time;
};
struct process_entry {
int process;
shared_ptr<data_entry> * dataStart;
shared_ptr<data_entry> * dataEnd;
shared_ptr<data_entry> * dataCurrent;
process_state state;
int Deadline;
int totalTime;
};
struct event_entry {
shared_ptr<process_entry> * process;
int time;
event_component component;
};
struct device_item {
shared_ptr<process_entry> * process;
int finishTime;
int startTime;
int endTime;
};
class device_table {
device_item * core1;
device_item * core2;
device_item * core3;
device_item * core4;
device_item * disk1;
std::queue<device_item*> IQ;
std::queue<device_item*> RQ;
std::queue<device_item*> DiskQ;
int completedReal;
int completedInter;
int completedDisk;
double DurationDisk;
int CoreUtilization[4];
int DiskUtilization;
public:
device_table()
{
core1 = NULL;
core2 = NULL;
core3 = NULL;
core4 = NULL;
disk1 = NULL;
completedReal = 0;
completedInter = 0;
completedDisk = 0;
DurationDisk = 0;
DiskUtilization = 0;
CoreUtilization[0] = 0;
CoreUtilization[1] = 0;
CoreUtilization[2] = 0;
CoreUtilization[3] = 0;
}
void addCore(shared_ptr<process_entry> * process, int currentTime)
{
if((core1 != NULL && core2 != NULL && core3 != NULL && core4 != NULL))
{
string processType = process->get()->dataStart->get()->text;
device_item * newEntry = new device_item();
newEntry->process = process;
newEntry->finishTime = currentTime + process->get()->dataCurrent->get()->time;
newEntry->startTime = currentTime;
if(core1->process->get()->dataStart->get()->text == "INTERACTIVE" && processType == "REAL-TIME")
{
core1->finishTime = core1->finishTime - currentTime;
IQ.push(core1);
core1 = newEntry;
}
else if(core2->process->get()->dataStart->get()->text == "INTERACTIVE" && processType == "REAL-TIME")
{
core2->finishTime = core2->finishTime - currentTime;
IQ.push(core2);
core2 = newEntry;
}
else if(core3->process->get()->dataStart->get()->text == "INTERACTIVE" && processType == "REAL-TIME")
{
core3->finishTime = core3->finishTime - currentTime;
IQ.push(core3);
core3 = newEntry;
}
else if(core4->process->get()->dataStart->get()->text == "INTERACTIVE" && processType == "REAL-TIME")
{
core4->finishTime = core4->finishTime - currentTime;
IQ.push(core4);
core4 = newEntry;
}
else
{
newEntry->finishTime = 0;
newEntry->startTime = 0;
if(process->get()->dataCurrent->get()->text == "INTERACTIVE")
{
IQ.push(newEntry);
process->get()->state = process_state::WAITING;
}
else
{
newEntry->finishTime = process->get()->dataCurrent->get()->time;
RQ.push(newEntry);
process->get()->state = process_state::WAITING;
}
}
}
else
{
device_item * newEntry = new device_item();
newEntry->process = process;
newEntry->startTime = currentTime;
newEntry->finishTime = currentTime + process->get()->dataCurrent->get()->time;
process->get()->state = process_state::RUNNING;
if(core1 == NULL)
core1 = newEntry;
else if(core2 == NULL)
core2 = newEntry;
else if(core3 == NULL)
core3 = newEntry;
else if(core4 == NULL)
core4 = newEntry;
}
}
void addDisk(shared_ptr<process_entry> * disk, int currentTime)
{
device_item * newDisk = new device_item();
newDisk->process = disk;
newDisk->finishTime = currentTime + disk->get()->dataCurrent->get()->time;
newDisk->startTime = currentTime;
if(disk1 == NULL)
disk1 = newDisk;
else
{
newDisk->finishTime = 0;
newDisk->startTime = 0;
DiskQ.push(newDisk);
disk->get()->state = process_state::WAITING;
}
}
void checkCoreAndDisk(int currentTime)
{
// Stick queue if becomes empty. Subtract time.
if(disk1 != NULL)
{
if(disk1->finishTime <= currentTime) {
DiskUtilization += disk1->finishTime - disk1->startTime;
disk1->process->get()->state = process_state::READY;
DurationDisk += disk1->finishTime - disk1->startTime;
disk1 = NULL;
completedDisk += 1;
if(DiskQ.size() > 0) {
disk1 = DiskQ.front();
disk1->startTime = currentTime;
disk1->finishTime = currentTime + disk1->process->get()->dataCurrent->get()->time;
DiskQ.pop();
disk1->process->get()->state = process_state::RUNNING;
}
}
}
if(core1 != NULL)
{
if(core1->finishTime <= currentTime) {
CoreUtilization[0] += core1->finishTime - core1->startTime;
core1->process->get()->state = process_state::READY;
if(core1->process->get()->dataStart->get()->text == "INTERACTIVE") { completedInter += 1; } else { completedReal += 1; };
core1 = NULL;
if(RQ.size() > 0) {
core1 = RQ.front();
core1->startTime = currentTime;
core1->finishTime = currentTime + core1->finishTime;
RQ.pop();
core1->process->get()->state = process_state::RUNNING;
}
else if(IQ.size() > 0) {
core1 = IQ.front();
core1->startTime = currentTime;
core1->finishTime = currentTime + core1->finishTime;
IQ.pop();
core1->process->get()->state = process_state::RUNNING;
}
}
}
if(core2 != NULL)
{
if(core2->finishTime <= currentTime) {
CoreUtilization[1] += core2->finishTime - core2->startTime;
core2->process->get()->state = process_state::READY;
if(core2->process->get()->dataStart->get()->text == "INTERACTIVE") { completedInter += 1; } else { completedReal += 1; };
core2 = NULL;
if(RQ.size() > 0) {
core2 = RQ.front();
core2->startTime = currentTime;
core2->finishTime = currentTime + core2->finishTime;
RQ.pop();
core2->process->get()->state = process_state::RUNNING;
}
else if(IQ.size() > 0) {
core2 = IQ.front();
core2->startTime = currentTime;
core2->finishTime = currentTime + core2->finishTime;
IQ.pop();
core2->process->get()->state = process_state::RUNNING;
}
}
}
if(core3 != NULL)
{
if(core3->finishTime <= currentTime) {
CoreUtilization[2] += core3->finishTime - core3->startTime;
core3->process->get()->state = process_state::READY;
if(core3->process->get()->dataStart->get()->text == "INTERACTIVE") { completedInter += 1; } else { completedReal += 1; };
core3 = NULL;
if(RQ.size() > 0) {
core3 = RQ.front();
core3->startTime = currentTime;
core3->finishTime = currentTime + core3->finishTime;
RQ.pop();
core3->process->get()->state = process_state::RUNNING;
}
else if(IQ.size() > 0) {
core3 = IQ.front();
core3->startTime = currentTime;
core3->finishTime = currentTime + core3->finishTime;
IQ.pop();
core3->process->get()->state = process_state::RUNNING;
}
}
}
if(core4 != NULL)
{
if(core4->finishTime <= currentTime) {
CoreUtilization[3] += core4->finishTime - core4->startTime;
core4->process->get()->state = process_state::READY;
if(core4->process->get()->dataStart->get()->text == "INTERACTIVE") { completedInter += 1; } else { completedReal += 1; };
core4 = NULL;
if(RQ.size() > 0) {
core4 = RQ.front();
core4->startTime = currentTime;
core4->finishTime = currentTime + core4->finishTime;
RQ.pop();
core4->process->get()->state = process_state::RUNNING;
}
else if(IQ.size() > 0) {
core4 = IQ.front();
core4->startTime = currentTime;
core4->finishTime = currentTime + core4->finishTime;
IQ.pop();
core4->process->get()->state = process_state::RUNNING;
}
}
}
}
bool checkDeadlines()
{
}
bool checkCoreFull()
{
return (core1 != NULL && core2 != NULL && core3 != NULL && core4 != NULL);
}
int printCompletedInt()
{
return completedInter;
}
int printCompletedReal()
{
return completedReal;
}
int printCompletedDisk()
{
return completedDisk;
}
double printAvgDiskDuration()
{
return (DurationDisk / completedDisk);
}
int printCoreUtilization(int core)
{
return CoreUtilization[core - 1];
}
int printDiskUtilization()
{
return DiskUtilization;
}
};
void createDataTable(string file, vector<shared_ptr<data_entry>> &dataTable)
{
string line;
ifstream myfile (file);
if (myfile.is_open())
{
int processAmount = 0;
while ( getline (myfile,line) )
{
if(line.find("INTERACTIVE") != string::npos)
{
shared_ptr<data_entry> newEntry = make_shared<data_entry>();
newEntry->text = "INTERACTIVE";
newEntry->time = atoi(line.substr(12, 12).c_str());
dataTable.push_back(newEntry);
//shared_ptr<process_entry> newProcessEntry = shared_ptr<process_entry>(new process_entry);
//newProcessEntry->dataStart = &dataTable.at(dataTable.size() - 1);
//newProcessEntry->dataCurrent = &dataTable.at(dataTable.size() - 1);
//newProcessEntry->process = processAmount;
//processTable.push_back(newProcessEntry);
processAmount += 1;
}
else if (line.find("REAL-TIME") != string::npos)
{
shared_ptr<data_entry> newEntry = make_shared<data_entry>();
newEntry->text = "REAL-TIME";
newEntry->time = atoi(line.substr(10, 10).c_str());
dataTable.push_back(newEntry);
processAmount += 1;
}
else if(line.find("END") != string::npos)
{
shared_ptr<data_entry> newEntry = make_shared<data_entry>();
newEntry->text = "END";
newEntry->time = -1;
dataTable.push_back(newEntry);
//processTable.at(processTable.size())->dataEnd = &dataTable.at(dataTable.size());
}
else if(line.find("RUN") != string::npos)
{
shared_ptr<data_entry> newEntry = make_shared<data_entry>();
newEntry->text = "RUN";
newEntry->time = atoi(line.substr(4, 4).c_str());
dataTable.push_back(newEntry);
}
else if(line.find("TTY") != string::npos)
{
shared_ptr<data_entry> newEntry = make_shared<data_entry>();
newEntry->text = "TTY";
newEntry->time = atoi(line.substr(4, 4).c_str());
dataTable.push_back(newEntry);
}
else if(line.find("DISK") != string::npos)
{
shared_ptr<data_entry> newEntry = make_shared<data_entry>();
newEntry->text = "DISK";
newEntry->time = atoi(line.substr(5, 5).c_str());
dataTable.push_back(newEntry);
}
else if(line.find("DEADLINE") != string::npos)
{
shared_ptr<data_entry> newEntry = make_shared<data_entry>();
newEntry->text = "DEADLINE";
newEntry->time = atoi(line.substr(9, 9).c_str());
dataTable.push_back(newEntry);
}
}
}
myfile.close();
}
void createProcessTable(vector<shared_ptr<data_entry>> &dataTable, vector<shared_ptr<process_entry>> &processTable)
{
int processAmount = 0;
for(size_t i = 0; i < dataTable.size(); i++)
{
if(dataTable.at(i)->text == "INTERACTIVE" || dataTable.at(i)->text == "REAL-TIME")
{
shared_ptr<process_entry> newProcessEntry = make_shared<process_entry>();
newProcessEntry->dataStart = &dataTable.at(i);
newProcessEntry->dataCurrent = &dataTable.at(i);
newProcessEntry->process = processAmount;
newProcessEntry->state = process_state::P_NONE;
newProcessEntry->totalTime = 0;
if(dataTable.at(i + 1)->text == "DEADLINE")
newProcessEntry->Deadline = dataTable.at(i + 1)->time;
else
newProcessEntry->Deadline = -1;
processTable.push_back(newProcessEntry);
processAmount += 1;
}
else if(dataTable.at(i)->text == "END")
{
processTable.back()->dataEnd = &dataTable.at(i);
}
if(processTable.size() > 0 && dataTable.at(i)->text != "DEADLINE" && dataTable.at(i)->time != -1)
{
processTable.back()->totalTime += dataTable.at(i)->time;
}
}
}
void createEventTable(vector<shared_ptr<process_entry>> &processTable, vector<shared_ptr<event_entry>> &eventTable)
{
for(size_t i = 0; i < processTable.size(); i++)
{
shared_ptr<event_entry> newEventEntry = make_shared<event_entry>();
newEventEntry->process = &processTable.at(i);
newEventEntry->time = newEventEntry->process->get()->dataStart->get()->time;
newEventEntry->component = event_component::E_NONE;
eventTable.push_back(newEventEntry);
}
}
bool sortEventTable(shared_ptr<event_entry> i, shared_ptr<event_entry> j)
{
return (i->time < j->time);
}
int main(int argc, const char *argv[])
{
int currentTime = 0;
int deadlineAmount = 0;
vector<shared_ptr<data_entry>> dataTable;
vector<shared_ptr<process_entry>> processTable;
vector<shared_ptr<event_entry>> eventTable;
device_table newDevice;
createDataTable(argv[1], dataTable);
createProcessTable(dataTable, processTable);
createEventTable(processTable, eventTable);
std::sort (eventTable.begin(), eventTable.end(), sortEventTable);
while(eventTable.size() > 0)
{
std::sort (eventTable.begin(), eventTable.end(), sortEventTable);
newDevice.checkCoreAndDisk(currentTime);
//newDevice.printAll();
string currentText = eventTable.at(0).get()->process->get()->dataCurrent->get()->text;
if(currentText == "RUN")
{
eventTable.at(0).get()->component = event_component::CORE;
newDevice.addCore(eventTable.at(0).get()->process, currentTime);
}
else if(currentText == "REAL-TIME" || currentText == "INTERACTIVE")
{
eventTable.at(0).get()->component = event_component::START;
}
else if(currentText == "DISK")
{
eventTable.at(0).get()->component = event_component::DISK;
newDevice.addDisk(eventTable.at(0).get()->process, currentTime);
}
else if(currentText == "TTY")
{
eventTable.at(0).get()->component = event_component::TTY;
}
if(eventTable.at(0).get()->process->get()->dataCurrent->get()->text == "END")
{
//cout << eventTable.at(0).get()->time << "\n";
if(eventTable.at(0).get()->process->get()->Deadline == 1)
{
}
eventTable.erase(eventTable.begin());
}
else
{
//cout << eventTable.at(0).get()->time << "\n";
eventTable.at(0).get()->process->get()->dataCurrent += 1;
if(currentText != "DEADLINE")
currentTime = eventTable.at(0).get()->time;
if(eventTable.at(0).get()->process->get()->dataCurrent->get()->time != -1 && currentText != "DEADLINE")
eventTable.at(0).get()->time = currentTime + eventTable.at(0).get()->process->get()->dataCurrent->get()->time;
}
//cout << newDevice.checkCoreFull() << "\n";
}
for(size_t i = 0; i < processTable.size(); i++)
{
if(processTable.at(i)->Deadline != -1)
{
if (processTable.at(i)->totalTime > processTable.at(i)->Deadline)
deadlineAmount += 1;
}
}
cout << "Completed Interactive : " << newDevice.printCompletedInt() << "\n";
cout << "Completed Real-Time : " << newDevice.printCompletedReal() << "\n";
cout << "Completed Disk : " << newDevice.printCompletedDisk() << "\n";
cout << "Core1 Utilization : " << newDevice.printCoreUtilization(1) << "\n";
cout << "Core2 Utilization : " << newDevice.printCoreUtilization(2) << "\n";
cout << "Core3 Utilization : " << newDevice.printCoreUtilization(3) << "\n";
cout << "Core4 Utilization : " << newDevice.printCoreUtilization(4) << "\n";
cout << "Disk Utilization : " << newDevice.printDiskUtilization() << "\n";
cout << "Average Disk Duration : " << newDevice.printAvgDiskDuration() << "\n";
cout << "% Missed Deadline : " << ((float)deadlineAmount / processTable.size()) * 100 << "%\n";
cout << "Total Elapsed Time : " << currentTime << "\n";
int input;
cin >> input;
return 0;
}
You may want to compile your code with C++11 support:
g++ -std=c++11

llvm "replaceinstwithvalue" does not work

I am a llvm newbie.
I am trying to write a llvm pass to optimize for algebraic identities in a function (like, if my function has an instruction a = b * 0, my pass should replace all following uses of "a" with 0).
So, my pass looks like follows:-
...
for (Function::iterator f_it = F.begin(), f_ite = F.end(); f_it != f_ite; ++f_it) {
for(BasicBlock::iterator b_it = f_it->begin(), b_ite = f_it->end(); b_it != b_ite; ++b_it) {
if(op->getOpcode() == Instruction::Mul) {
if(ConstantInt *CI_F = dyn_cast<ConstantInt>(&*b_it->getOperand(0))) {
if(CI_F->isZero()) {
firstop_zero = 1;
}
}
if(ConstantInt *CI_S = dyn_cast<ConstantInt>(&*b_it->getOperand(1))) {
if(CI_S->isZero()) {
secop_zero = 1;
}
}
if(first_zero || second_zero) {
errs()<<"found zero operand\n";
ReplaceInstWithValue(b_it->getParent()->getInstList(),b_it,(first_zero?(&*b_it->getOperand(1)):(&*b_it->getOperand(0))));
}
}
}
}
I can see that my comment "found zero operand gets printed out on std-err, but I can't see the replacement in the resulting .bc's disassembly.
What am I missing here? Any help is sincerely appreciated.
Thanks a lot!
Praveena
Try
for (Function::iterator f_it = F.begin(), f_ite = F.end(); f_it != f_ite; ++f_it) {
for(BasicBlock::iterator b_it = f_it->begin(), b_ite = f_it->end(); b_it != b_ite; ++b_it) {
Instruction *I = *b_it;
Value *Zeroval;
if(op->getOpcode() == Instruction::Mul) {
if(ConstantInt *CI_F = dyn_cast<ConstantInt>(&*b_it->getOperand(0))) {
if(CI_F->isZero()) {
firstop_zero = 1;
Zeroval = CI_F;
}
}
if(ConstantInt *CI_S = dyn_cast<ConstantInt>(&*b_it->getOperand(1))) {
if(CI_S->isZero()) {
secop_zero = 1;
ZeroVal = CI_S;
}
}
if(first_zero || second_zero) {
errs()<<"found zero operand\n";
I->ReplaceAlluseswith(ZeroVal);
}
}
}
}