use struct value in if statement in solidity - if-statement

my code generates a list of how many referrals an address has...It correctly generates the numbers for the total referrals and referrals by level...How can I take the value of total referrals so I can use its value in an if totaltransfers > ? statement?
struct User {
bool referred;
address referred_by;
}
struct Referal_levels {
uint256 level_1;
uint256 level_2;
uint256 level_3;
uint256 level_4;
uint256 _totalreferred;
}
mapping(address => Referal_levels) public refer_info;
mapping(address => User) public user_info;
function lotteryStart() public {
require (lotteryActive == false, "lottery already active");
lotteryActive = true;
lotterystartTime = now;
}
function enter(address ref) public payable {
require(ref != msg.sender, " You cannot refer yourself ");
user_info[msg.sender].referred_by = ref;
user_info[msg.sender].referred = true;
address level1 = user_info[msg.sender].referred_by;
address level2 = user_info[level1].referred_by;
address level3 = user_info[level2].referred_by;
address level4 = user_info[level3].referred_by;
address totalreferred = user_info[level4].referred_by;
if ((level1 != msg.sender) && (level1 != address(0))) {
refer_info[level1].level_1 += 1;
refer_info[level1]._totalreferred += 1;
}
if ((level2 != msg.sender) && (level2 != address(0))) {
refer_info[level2].level_2 += 1;
refer_info[level2]._totalreferred += 1;
}
if ((level3 != msg.sender) && (level3 != address(0))) {
refer_info[level3].level_3 += 1;
refer_info[level3]._totalreferred += 1;
}
if ((level4 != msg.sender) && (level4 != address(0))) {
refer_info[level4].level_4 += 1;
refer_info[level4]._totalreferred += 1;
}

Related

How to initialize an object once and use it for all test cases

I have a test class where I have all my test cases for my java project, I want to initialize the service class once which creates an array and I want to use the same array for all the other test cases, I have tried to do that but when the first test case is ran an customer is registered and stored in the array I want to use the customer stored in the array and use it for the next test case but it seems that the customer is not in the array for the next test case i.e a new array is being created or I think that junit is running each test case individually
MainTests.java
package tests;
import static org.junit.Assert.*;
import org.junit.*;
import services.BankingServiceImpl;
import dao.BankingSystemArrayImpl;
public class MainTests {
static BankingServiceImpl bankingService;
private static boolean setupIsDone = false;
#BeforeClass
public static void setup() {
bankingService = new BankingServiceImpl();
}
#Test // 1
public void createCustomer() {
String custName = "Rohan";
String HomeAddressCity = "Pune";
String HomeAddressState = "Maharashtra";
int HomeAddressPincode = 411043;
String LocalAddressCity = "Pune";
String LocalAddressState = "Pune";
int LocalAddressPincode = 411043;
int day = 19;
int month = 9;
int year = 1998;
int result = bankingService.acceptCustomerDetails(custName, HomeAddressCity, HomeAddressState,
HomeAddressPincode, LocalAddressCity, LocalAddressState, LocalAddressPincode, day, month, year);
System.out.println(bankingService.getLength());
assertTrue(result > 0);
}
#Test // 2
public void openCustomerAccount() {
System.out.print(bankingService.getLength());
int customerid = 100;
int balance = 100000;
String accountType = "savings";
int result = bankingService.openAccount(customerid, balance, accountType);
assertTrue(result > 0);
}
#Test // 3
public void Balance() {
int customerid = 100;
int accountid = 50;
int pin = 1007;
int result = bankingService.getAccountBalance(customerid, accountid, pin);
assertTrue(result > 0);
}
#Test // 4
public void amt_withdraw() {
int customerid = 100;
int accountid = 50;
int amount = 10000;
int pin = 1007;
int result = bankingService.withdraw(customerid, accountid, amount, pin);
assertEquals(result, 90000);
}
#Test // 5
public void transfer() {
int customerid = 100;
int accountid = 50;
int customerid1 = 101;
int accountid1 = 51;
int amount = 10000;
int pin = 1007;
boolean result = bankingService.fundTransfer(customerid, accountid, customerid1, accountid1, amount, pin);
assertEquals(result, true);
}
#Test // 6
public void amt_deposit() {
int customerid = 100;
int accountid = 50;
int amount = 10000;
int result = bankingService.deposit(customerid, accountid, amount);
assertEquals(result, 90000);
}
/*
* #Test //7 public void cust_details() { int customerid = 100;
* BankingServiceImpl bankingService = new BankingServiceImpl();
*
* int result = bankingService.getCustomerDetails(customerid);
* assertEquals(result, 90000); }
*/
#Test // 10
public void pin_change() {
int customerid = 100;
int accountid = 50;
int o_pin = 1007;
int n_pin = 1122;
boolean result = bankingService.changePin(customerid, accountid, o_pin, n_pin);
assertEquals(result, true);
}
#Test // 11
public void check_change() {
int customerid = 100;
int accountid = 50;
int pin = 1007;
boolean result = bankingService.checkPin(customerid, accountid, pin);
assertEquals(result, true);
}
}
Service Class
package services;
import beans.Account;
import beans.Address;
import beans.Customer;
import beans.MyDate;
import beans.Transaction;
import dao.BankingSystemArrayImpl;
public class BankingServiceImpl {
BankingSystemArrayImpl BankingSystemArray;
public BankingServiceImpl() {
System.out.print("called");
BankingSystemArray = new BankingSystemArrayImpl();
}
/*
* public void transfer(int accountId, int tansferAccountId, double amount)
* { double a = BankingSystemArray.getAccount(accountId).getBalance()
* - amount; System.out.println(a);
* BankingSystemArray.getAccount(accountId).setBalance(a); double b =
* BankingSystemArray.getAccount(accountId).getBalance() + amount;
* BankingSystemArray.getAccount(tansferAccountId).setBalance(b);
*
* }
*/
public int acceptCustomerDetails(String custName, String HomeAddressCity,
String HomeAddressState, int HomeAddressPincode,
String LocalAddressCity, String LocalAddressState,
int LocalAddressPincode, int day, int month, int year) {
if ((day > 0 && day <= 31) && (month >= 1 && month <= 12)
&& (year <= 2015)) {
return BankingSystemArray.insertCustomer(new Customer(
custName, new Address(LocalAddressCity, LocalAddressState,
LocalAddressPincode), new Address(HomeAddressCity,
HomeAddressState, HomeAddressPincode), new MyDate(
day, month, year)));
} else
return 0;
}
public int openAccount(int custId, int balance, String accType) {
int accountId = 0;
if (custId < 99) {
System.out
.println("Invalid customer Id,please enter a valid customer Id");
} else if (!(accType.equalsIgnoreCase("savings")
|| accType.equalsIgnoreCase("current") || accType
.equalsIgnoreCase("salary"))) {
System.out
.println("Invalid account type, please enter a valid account type");
} else if (balance < 0) {
System.out.println("Invalid amount, please amount a valid amount");
}
else {
Customer customer = BankingSystemArray.getCustomer(custId);
if (customer == null) {
System.out.println("Sorry you have not registered");
return 0;
} else {
Account account = new Account(accType, balance);
accountId = BankingSystemArray.insertAccount(account,
custId);
}
}
return accountId;
}
public int getAccountBalance(int custId, int accNo, int pin) {
if (checkPin(custId, accNo, pin)) {
return BankingSystemArray.getAccount(custId, accNo)
.getBalance();
} else {
System.out.println("Invalid pin");
return 0;
}
}
public int withdraw(int custId, int accNo, int amt, int pin) {
int balance = 0;
if (amt < 0) {
System.out.println("Invalid amount, please enter a valid amount");
} else {
Customer customer = BankingSystemArray.getCustomer(custId);
if (customer == null) {
return 0;
} else {
Account account = BankingSystemArray.getAccount(custId,
accNo);
if (account == null) {
System.out.println("Sorry your account does not exist");
} else if (account.getPin()!=pin) {
System.out.println("Invalid pin");
return 0;
} else {
if ((account.getBalance() - amt) > 0) {
account.setBalance(account.getBalance() - amt);
balance = account.getBalance();
}
}
}
}
return balance;
}
public boolean fundTransfer(int custIdFrom, int accNoFrom, int custIdTo,
int accNoTo, int amt, int pin) {
if (withdraw(custIdFrom, accNoFrom, amt, pin) > 0) {
deposit(custIdTo, accNoTo, amt);
return true;
}
return false;
}
public int deposit(int custId, int accNo, int amt) {
if (amt < 0) {
System.out.println("Invalid amount, please enter a valid amount");
} else {
BankingSystemArray.getAccount(custId, accNo).setBalance(
BankingSystemArray.getAccount(custId, accNo)
.getBalance() + amt);
return BankingSystemArray.getAccount(custId, accNo)
.getBalance();
}
return 0;
}
public Customer getCustomerDetails(int custId) {
Customer customer = BankingSystemArray.getCustomer(custId);
if (customer != null) {
return customer;
}
return null;
}
public Account getAccountDetails(int custId, int accNo) {
Account account = BankingSystemArray.getAccount(custId, accNo);
if (account != null) {
return account;
}
return null;
}
public Account[] getAllAccountsDetails(int custId) {
Account[] account = BankingSystemArray.getAccountList(custId);
if (account != null) {
return account;
}
return null;
}
public Transaction[] getAllTransactionDetails(int custId, int accNo) {
// TODO Auto-generated method stub
return null;
}
public int generatePin(int custId, int accNo) {
Account account = BankingSystemArray.getAccount(custId, accNo);
int pin = BankingSystemArray.generateRandomNumber();
account.setPin(pin);
return account.getPin();
}
public boolean changePin(int custId, int accNo, int oldPin, int newPin) {
Account account = BankingSystemArray.getAccount(custId, accNo);
if (account != null) {
if (account.getPin() == oldPin) {
account.setPin(newPin);
return true;
}
}
return false;
}
public boolean checkPin(int custId, int accNo, int pin) {
Account account = BankingSystemArray.getAccount(custId, accNo);
if (account != null) {
if (account.getPin() == pin) {
return true;
}
}
return false;
}
public Customer getLength() {
return BankingSystemArray.getLength();
}
}
To solve your problem, you need first to understand the JUnit behavior.
Methods marked with #BeforeClass and #AfterClass are run only
once, and are the upper and lower bound of all your test methods.
Methods marked with #Before and #After are run immediately
before and after any test method.
Only static members are shared between test cases. So all instance
members are being reset before any test method.
Also note that as a RULE in Unit Testing, all tests (all test methods) MUST be isolated from each other, but it's OK in integration testing.

How do you find the shortest path after the BFS algorithm?

while( !q.is_empty() )
{
loc = q.remove_from_front();
//cout << loc.row << " " << loc.col << endl;
if( (loc.row-1) >= 0) //north
{
loc2.row = loc.row-1;
loc2.col = loc.col;
if(maze[loc2.row][loc2.col] != '#' && visited[loc2.row][loc2.col] == false)
{
visited[loc2.row][loc2.col] = true;
q.add_to_back(loc2);
//loc = predecessor[loc.row][loc.col];
predecessor[loc2.row][loc2.col] = loc;
if(maze[loc2.row][loc2.col] == 'F')
{
result = 1;
maze[loc2.row][loc2.col] = '*';
break;
}
}
}
if(loc.col-1 >= 0) //West
{
loc2.row = loc.row;
loc2.col = loc.col-1;
if(maze[loc2.row][loc2.col] != '#' && visited[loc2.row][loc2.col] == false)
{
visited[loc2.row][loc2.col] = true;
q.add_to_back(loc2);
//loc = predecessor[loc.row][loc.col];
predecessor[loc2.row][loc2.col] = loc;
if(maze[loc2.row][loc2.col] == 'F')
{
result = 1;
maze[loc2.row][loc2.col] = '*';
break;
}
}
}
if(loc.row+1 < rows) //South
{
loc2.row = loc.row+1;
loc2.col = loc.col;
if(maze[loc2.row][loc2.col] != '#' && visited[loc2.row][loc2.col] == false)
{
visited[loc2.row][loc2.col] = true;
q.add_to_back(loc2);
// loc = predecessor[loc.row][loc.col];
predecessor[loc2.row][loc2.col] = loc;
if(maze[loc2.row][loc2.col] == 'F')
{
result = 1;
maze[loc2.row][loc2.col] = '*';
break;
}
}
}
if(loc.col+1 < cols) //East
{
loc2.row = loc.row;
loc2.col = loc.col+1;
if(maze[loc2.row][loc2.col] != '#' && visited[loc2.row][loc2.col] == false)
{
visited[loc2.row][loc2.col] = true;
q.add_to_back(loc2);
//loc = predecessor[loc.row][loc.col];
predecessor[loc2.row][loc2.col] = loc;
if(maze[loc2.row][loc2.col] == 'F')
{
result = 1;
maze[loc.row][loc.col] = '*';
break;
}
}
}
}
if(result == 1)
{
while()
{
//not sure...
}
}
This is my BFS algorithm and the main reason I asked this question is because the other questions similar to my own question tends to be done with vectors. I haven't learn vectors yet. What I am trying to do is to print the shortest path using '' characters to display it on valid elements. It should be in bounds, no walls visited (walls are '#' characters), and no element should be visited twice. I know that if I set my predecessor 2D array correctly, the shortest path should be displayed correctly. However, I am not sure if I did set it up correctly and how to actually fill in that path with '' characters...

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());
}
}
}
}

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);
}
}
}
}