text
stringlengths 20
1.01M
| url
stringlengths 14
1.25k
| dump
stringlengths 9
15
β | lang
stringclasses 4
values | source
stringclasses 4
values |
---|---|---|---|---|
Day 1 Keynote - Bjarne Stroustrup: C++11 Style
- Date: February 2, 2012 from 9:30AM to 11:00AM
- Day 1
- Speakers: Bjarne Stroustrup
- 205,916 Views
- 72 Comments
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
Right click βSave asβ¦βSlides.
Follow the Discussion
Good!!
Always eager to learn from the best. I'm definitely looking forward to watching Bjarne's interesting talk and the other GoingNative 2012 sessions!
Looking forward to this exciting session, Rocks!!
Looking forward to all the sessions. I am based in Manchester UK, must have checked the time in Redmond USA at least 20 times today :) cant wait.
We are gonna party like it is C++98 :P
Where are the live feed links?
Awesome talk!
Where can I access the recorded keynote?
You'll be able to access the recorded keynote and indeed all the sessions right here. Charles said it would take about +1 day to do the encoding and then the downloadable video files will be available.
Where can I download yesterday videos?
It was a great lecture!
But I haven't had the time to watch other speakers. I'll download the 1080p version of talks, since 1080p makes reading the code much a nicer experience.
EDIT: Charles, would it be possible to also publish the PowerPoint or PDF slides?
@undefined:Yes, where are the recorded sessions?
Had to work during almost all talks, so I'm looking forward to here all these presentations - saw a bit of the first day live but will enjoy the recordings of all presentations soon
. BTW: great selection of speakers: Bjarne, Sutter, Alexandrescu,β¦
@STL: great to here that range-base-for-loops will be in VC11.. though I'm a std::for_each-guy so that's not that big of a deal for me.
PS: looking forward to std::thread-support in VCβ¦
The range-based for-loop is significantly less verbose than std::for_each() (my least favorite STL algorithm).
But using more specific STL algorithms is always a good idea.
The first qsort Example seems to be broken. I guess it goes to show how bad the API really is.
void f(char *arr, int m, ...) {
qsort(arr, m, sizeof(char*), cmpstringp);
}
He probably wanted a char *arr[].
Great talk so far.
btw. this website should support Unicode in names!
Thanks. Fixed for future uses.
A great talk!
I believe the 38 slide should read
shared_ptr<Gadget> p( new Gadget{n} );
instead of
shared_ptr<Gadget> p = new Gadget{n};
The same thing with the 39 slide.
I thought the talk on C++11 was great.
helpful
Can someone enlighten me about the syntax on page 62 (and 63) of slides:
double* f(const vector<double>& v); // read from v return result
double* g(const vector<double>& v); // read from v return result
void user(const vector<double>& some_vec) // note: const
{
double res1, res2;
thread t1 {[&]{ res1 = f(some_vec); }};
thread t2 {[&]{ res2 = g(some_vec); }};
// ...
t1.join();
t2.join();
cout << res1 << ' ' << res2 << '\n';
}
Isn't there a type mismatch between f() return and res1?
I took some sentence from the description of Bjarne description, because I am trying to find ressources, materials tutorials that show how to acheive this. For the previous standart or c++11. Anybody know good reference where i can find this now?
thanks
@undefined: Slides will be released with each session video! Like this one
C
Oh heck I give up.
Cool. Now we can see the invisible graph.
Yes, having to explain an invisible graph was a bit of a challenge :-)
Thanks for the comments; corrections will be applied to future versions of the talk.
It is interesting to ask if the software which supposed to show the graphs and the graph itself (i.e. invisible one) was written in C++. I noticed also some problems with fonts on one or two slides.
According to my experience these are typical problems in all kind of scientific presentations.
It is hard to believe that it is so difficult to avoid those problems with current technology. The same presentation on one computer looks very different on a different computer only because some other fonts are installed on that computer. In theory it is possible to embed the fonts with the presentation unfortunately this method do not work well in many cases (my own experience).
The only real solution is to transform the presentation into pdf or use some other software (or use your own computer but in many cases is not possible).
I saw these problems hundreds times in all kind of conferences and it looks like nobody in the MS Office Team cares about that (since the existence of MS Office).
The question about an easier way to declare getters and setters, anyone else think than Bjarne was just short of saying "I don't want that crap in my language"? =)
Nice. C++ may get bashed a lot, but its creator can certainly deliver a coherent presentation.() );
Shouldn't there at least be a performance difference between
sum=0; for(vector<int>::sizetype i=0;i<v.size();++i){ sum+=v[i]};
sum=0; for_each(v.begin(),v.end(),[&sum](int x){sum +=x;});
Since the first is calling size() during each loop, while the second (I believe) wouldn't constantly be rechecking the size, similarly to defining a vector<int>::sizetype end=v.size; and checking i<end?
I am also curious why there aren't at least some run times or something to back up the claim that there is no discernible difference between "several systems and several compilers"?
On my question about getters and setters in the video, I guess that these should be avoided; public data and object members should simply be declared public, despite what I've seen to be a common practice on many projects, and which seems to be promoted in many object oriented languages.
Ideally, there would be some way to overload the setting of an object or data "property" if the logic needs to be changed or limits imposed. I have created a Property template class in the past as Bjarne suggested, however, there is no elegant way for the parent class to overload the setter in the aggregated Property<T> member, and the syntax of accessing members of the property too often become property.get().member(), rather than property.member(), which is what you want to write.
From a language viewpoint, perhaps something like an overloaded "member access operator" would allow library writers to implement a setter or getter later if needed without changing user code. But without this, we suggest that if we need to change logic around setting or getting a member value, make the property private and recompile - we can easily find and update all the usages of the data member to use the new getter or setter.
So awesome to have Bjarne posting on C9!
Thank you, sir.
C
@undefined:Darren, here are my thoughts on your question. If you created a wrapper class for each public data member you could overload the assignment operator to perform bounds checking (as well as assignment) and perhaps throw an exception if necessary. That would solve the problem of assigning to a property without a setter. Of course, you would also have to overload all other meaningful operators for that property such as the boolean operators. You would have to repeat all this for each property, which in the end may be more trouble than it's worth. I can't really think of another way to do it, but I also haven't touched C++ in awhile so I could be wrong. Anyway, good luck.
I would really love to hear a talk, or read a paper, from Bjarne that discusses when to use OOP, and when to choose Functional or Type programming. For me, finding a balance has always been the most difficult part in software development. There just isn't one right way, but I'd love to hear his thoughts.
If anyone has any links to anything related that would be wonderful.
Nice
For those who are also members of the C++ Software Developers group on LinkedIn, I have started a discussion about what I believe are the most important features of C++ 11, and would love to see feedback and examples of good style that people would like to contribute. See
I watched the video few times.
I feel like we need some "fresh-minds" in defining what programming should look like, replacing Bjarne.
They had their era, time to move on.
My biggest problem with C++ (in big project) are the #includes that square the amount of source to compile (headers are compiled separately for each compilation unit).
Look how long it takes to compile firefox or KDE :-(
I think this is were we pay the cost for [over]using templates and/or inline functions.
Maybe there is something that could be fixed here? Maybe if we break backward compatibility (drop the preprocessor)? It's a pity that those problems were not mentioned here.
@pafinde: That's one of the things that modules seek to solve.
You can see the "invisible" graph in my posted slides.
I wrote a paper for IEEE Computer Magazine with very similar examples. See the January 2012 issue of Computer or my publications page:.
From C++ application development point of view, is there any place for compiler generated iterators in C++ (c# IEnumerable)? Seems like they may be implemented with zero overhead, like lambdas do.
I dont see any difference between the example
and the 'better' example
Both are understandable only if you use declarative parameter names as it is done with
which is equally understandable for me if you write
?
@bog: Thanks for this detailed answer to my comment.
I dont want to start nit-picking here. For sure 99.9999% of all programmers (me included) would use both corner points to define a rectangle. But you could also define it by its center point and any other point.
Or using the second constructor with Point top_left and Box_hw. Even if i would be 99% sure that i know what's meant, if i would readI would take a look at the implementation or read the docs to be sure.
So for me, using declarative parameter names highly improves the readability of interfaces.
After a night thinking about this issue I have to correct my first comment.
Within the meaning of this excellent talk, the examples using Point are the better ones. I was just misled by the different notations for good examples written with parameters and bad examples written without.
The Point example is better, because it implicates the possibility to use units like it is done by the Speed example.
The general point (sic) about the Point example is that sequences of arguments of the same type is prone to transposition of argument values. I consider it a well established fact that this is a significant source of errors. The implication is that we need to look for remedies. Using a more expressive and specific set of types is one approach.
A very good source of infomation..
Bjarne sir, I truly enjoyed, appreciated, and was influenced by your presentation. One thing that comes to mind is the ability for C++ to write performant, yet secure code.
I'm confused at one thing.
I can understand where he says, shared_ptr and unique_ptr,
but where he says why use a pointer, and then shows this code:
I'm pretty sure C++ wouldn't except that?
I've just run a test, and you can scope a variable like in Java now ^_^
it would be like this
Its amazing to see how C++ is catching up with .NET.
I've always been a C++ guy.
Thanks again.
Now? That last f() has worked for about two decades! It's pure C++98.
The "Gadget g {n};" in the original example, simply used the C++11 uniform initializer syntax, but is otherwise identical.
Wow, i must be honoured to get a reply from the man himself.
Thanks for the heads up Bjarne, C++ is really moving up.
So I can just pass a object by value by using rvalue references.
That is soo cool.
Tom
So, why canβt I read an unsigned char from an input stream?
When I try to read from "0", I get 060 and not 0 as expected.
And when I push (unsigned char) 0, I get "\0", not "0" in the output.
(1) Huh? unsigned char c; while(cin>>c) cout<<c<<'\n'; gives exactly what I expect
(2) The value of (unsigned char)0 *is* 0; not the value of the character '0'
Great presentation Bjarne. Honestly I have checked it a few times already
on the expense of not having watched the other videocasts yet...
Too bad the Vector vs Linked-List comparison kind of fell short. In spite of the graph-mishap I got inspired and tested it on a few different machines. For small amounts it was virtually the same but as the sets got larger there was a huge difference.It was fun to see - especially since I remember discussing this a couple of years ago (then I failed to see the larger picture).
Thanks again for the presentation!
To the guy asking about getters and setters using different get and set functions per class and while still keeping function inlining, this should work.
template<class OutType, class StoreType, class Controller>
class Property
{
private:
StoreType data;
public:
operator OutType()
{
return Controller::get(data);
}
OutType operator=(OutType a)
{
Controller::set(data, a);
return Controller::get(data);
}
};
class HPController
{
public:
static int get(int &a)
{
return a;
}
static void set(int &a, int &b)
{
a = b;
}
};
class Man
{
public:
Property<int, int, HPController> HP;
};
void PropertyTest()
{
Man man;
man.HP = 7;
cout << man.HP << "\n";
}
Thanks Bjarne!!!
I knew I wasn't stupid for wanting readable interfaces!! Hehe
@Ray: The problem with that approach becomes when your 'controller' needs to do something a bit more complex and needs the target object's state to decide what to do or needs to notify the target object to do something else upon a change.
In my experience I've found those cases the primary cases where I actually needed getters and setters.
So then in that case the Property class template needs to change to be able to contain a controller object which then holds a reference to the target object ( 'Man', in this case ), and the Controller then can not use static methods.
But then here is the bloat added.
So I like Darren's new proposal best - if they are logically publically available properties just leave them as public member variables.
In the future, when you realize that you need something more complex, either make them private and add getters and setters and modify the client code, or make a decorator that allows the assignment operator to work with them which calls the real getters and setter behind the scenes.
The truth is IOStream treats signed/unsigned chars as characters and not as numbers. Whether this is something to be expected I don't know.
Didn't know I could watch this on the internet.
I will definitely watch this as soon as I get off.
My suggestion is that when you write a char (short for "character") to an character I/O stream, you should expect to see that character on the output device. It takes quite some alternative learning to expect otherwise.
PS The "c" in cout, stands for "character"
PPS "If everything else fails read the manual"
I was trying to use his units code that was on the slide around 24:00, but the syntax he uses for the following doesn't seem to work with gcc 4.6.2 and -std=c++0x
using Speed = Value<Unit<1,0,-1>>;
I've never seen this use of the using directive before. Anybody know what is up with this?
@Luke: gcc 4.7 introduces support for template aliases. I have only 4.6.1 installed... I'll need to upgrade I guess
With gcc 4.7, the following works:
Speed sp1 = Value<Unit<1,0,-1>>(100); // 100 meters / second
But this does not (operator/ is not defined):
Speed sp1 = Value<Unit<1,0,0>>(100) / Value<Unit<0,0,1>>(1);
I guess he left out the part which would define all the arithmetic operators.
Yes, about two pages of things like this
template<class U1, class U2>
Value<typename Unit_plus<U1,U2>::type>
operator*(Value<U1> x, Value<U2> y)
{
return Value<typename Unit_plus<U1,U2>::type>(x.val*y.val);
}
and this
template<class U1, class U2>
struct Unit_plus {
typedef Unit<U1::m+U2::m,
U1::kg+U2::kg,
U1::s+U2::s
> type;
};
You can make that prettier in C++11, but I was using an old compiler (then), so I used old-fashioned, but effective, metaprogramming.
I like this one.
!bind comes from boost.
"Using !bind(pred, _1) in the first call to stable_partition() in the definition of the gather() function template (around minute 56 of the video) won't compile, will it? (Unless the wrapper object returned from bind() overloads operator!, which I don't think it does.)"
- from decades, code was been easy to learn first, because you were just need a few terms for programming. And you were done all things with that.
- Now, you need , you must use Interfaces , typedef specifics, classes globally existing in a namespace (like .NET) and you must know how you name it.
Yes, a box it's ok . This is a simple box. But, Box_hw ? how do you spell it ? You need now what you want to do but name it !
Is it more difficult for programmers ? No . Is it more difficult to remember the names ? No
It it always difficult to remember for beginners. But, if you are a beginner, engineer, you just need to remember all classes. For example, even google couldn't help you if you want a bicycle and you don't know how you spell a bicycle.
Now, differences between engineers : a few people know all classes ? well, but it's not very realistic.
Second, i love when i can be a C++ programmer since i know how to program in Java. That is in a good spirit.
Third, i love when he said "who does the delete ?" . Many bugs come from the bad documentation or a left program.
And else about Copy ? Not copy ? well, you can choice. You need to choice and need to say in the documentation that you can copy or not (thread safe ?).
After, it explains you should have use a Vector and not a List to insert incrementally your data because true OO type is a chained list. That is the difference and a time consuming with .NET List insertion. But, it's implementation dependent. You should know the implementation now.
Low level is should be not use : use standard templates instead. That's very C++ !
Remove this comment
Remove this threadclose | http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style?format=smooth | CC-MAIN-2013-20 | en | refinedweb |
iPcTest Struct Reference
This is a test property class. More...
#include <propclass/test.h>
Inheritance diagram for iPcTest:
Detailed Description
This is a test property class.
This property class can send out the following messages to the behaviour (add prefix 'cel.parameter.' to get the ID for parameters):
- cel.misc.test.print: a message has been printed (message)
This property class supports the following actions (add prefix 'cel.action.' to get the ID of the action and add prefix 'cel.parameter.' to get the ID of the parameter):
- Print: parameters 'message' (string).
This property class supports the following properties (add prefix 'cel.property.' to get the ID of the property:
- counter (long, read/write): how many times something has been printed.
- max (long, read/write): maximum length of what was printed.
Definition at line 43 of file test.h.
Member Function Documentation
Print a message.
The documentation for this struct was generated from the following file:
Generated for CEL: Crystal Entity Layer 1.4.1 by doxygen 1.7.1 | http://crystalspace3d.org/cel/docs/online/api-1.4.1/structiPcTest.html | CC-MAIN-2013-20 | en | refinedweb |
XSNamespaceItem
The constructor to be used when a grammar pool contains all needed info.
The constructor to be used when the XSModel must represent all components in the union of an existing XSModel and a newly-created Grammar(s) from the GrammarResolver.
[annotations]: a set of annotations.
Convenience method.
Returns a top-level attribute declaration.
null
Returns a top-level attribute group definition.
[schema components]: a list of top-level components, i.e.
element declarations, attribute declarations, etc.
ELEMENT_DECLARATION
TYPE_DEFINITION
objectType
Returns a list of top-level component declarations that are defined within the specified namespace, i.e. element declarations, attribute declarations, etc.
namespace
Returns a top-level element declaration.
Returns a top-level model group definition.
A set of namespace schema information information items ( of type XSNamespaceItem), one for each namespace name which appears as the target namespace of any schema component in the schema used for that assessment, and one for absent if any schema component in the schema had no target namespace.
For more information see schema information.
Returns a list of all namespaces that belong to this schema. The value null is not a valid namespace name, but if there are components that don't have a target namespace, null is included in this list.
Returns a top-level notation declaration.
Returns a top-level simple or complex type definition.
XSTypeDefinition
Get the XSObject (i.e.
XSElementDeclaration) that corresponds to to a schema grammar component (i.e. SchemaElementDecl)
Optional.
Return a component given a component type and a unique Id. May not be supported for all component types.
[friend]
[protected] | http://docs.oracle.com/cd/E18050_01/tuxedo/docs11gr1/xmlparser/html/apiDocs/classXSModel.html | CC-MAIN-2013-20 | en | refinedweb |
as it violates type aliasing. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.
#include <iostream> union S { std::int32_t n; // occupies 4 bytes std::uint16_t s[2]; // occupies 4 bytes std::uint8_t c; // occupies 1 byte }; // the whole union occupies 4 bytes int main() { S s = {0x12345678}; // initalizes the first member, s.n is now the active member // at this point, reading from s.s or s.c is UB std::cout << std::hex << "s.n = " << s.n << '\n'; s.s[0] = 0x0011; // s.s is now the active member // at this point, reading from n or c is UB but most compilers define this std::cout << "s.c is now " << +s.c << '\n' // 11 or 00, depending on platform << "s.n is now " << s.n << '\n'; // 12340011 or 00115678 }
Each member is allocated as if it is the only member of the class, which is why
s.c in the example above aliases the first byte of
s.s[0].
If members of a union are classes with user-defined constructors and destructors, to switch the active member, explicit destructor and placement new are generally needed:
#include <iostream> #include <string> #include <vector> union S { std::string str; std::vector<int> vec; ~S() {} // needs to know which member is active, only possible in union-like class }; // the whole union occupies max(sizeof(string), sizeof(vector<int>) int main() { S s = {"Hello, world"}; // at this point, reading from s.vec is UB std::cout << "s.str = " << s.str << '\n'; s.str.~basic_string<char>(); new (&s.vec) std::vector<int>; // now, s.vec is the active member of the union s.vec.push_back(10); std::cout << s.vec.size() << '\n'; s.vec.~vector<int>(); }
If two union members are standard-layout types, it's well-defined to examine their common subsequence on any compiler.
[edit] Anonymous unions
An unnamed union definition that does not define any objects is an anonymous union definition.
Anonymous unions have further restrictions: they cannot have member functions, cannot have static data members, and all their non-static data members must be public.
Members of an anonymous union are injected in the enclosing scope (and must not conflict with other names declared there).
int main() { union { int a; const char* p; }; a = 1; p = "Jennifer"; }
Namespace-scope anonymous unions must be static.
[edit] Union-like classes
A union-like class is any class with at least one anonymous union as a member. The members of that anonymous union are called variant members. Union-like classes can be used to implement tagged unions.
#include <iostream> // S has one non-static data member (tag), three enumerator members, // and three variant members (c, n, d) struct S { enum {CHAR, INT, DOUBLE} tag; union { char c; int n; double d; }; }; void print_s(const S& s) { switch(s.tag) { case S::CHAR: std::cout << s.c << '\n'; break; case S::INT: std::cout << s.n << '\n'; break; case S::DOUBLE: std::cout << s.d << '\n'; break; } } int main() { S s = {S::CHAR, 'a'}; print_s(s); s.tag = S::INT; s.n = 123; print_s(s); } | http://en.cppreference.com/w/cpp/language/union | CC-MAIN-2013-20 | en | refinedweb |
Deploying and running Django apps on Heroku is really a no-brainer, except for one thing β serving static files via
collectstatic.
I run
collectstatic as usual, using
heroku run command just like how I did it for
syncdb. It worked but Iβm getting 404 error when serving static files.
It turns out that running
collectstatic via
heroku run spins up a new dyno and
collectstatic is running in an isolated environment. So, all the collected static files are deployed to that location and only for this new dyno and the dyno attached to our Django app canβt access that. β Heroku support staff
Solution
The dead simple solution would be to run
collectstatic as part of the Procfile before starting the app. We need to βchainβ together our Procfile commands for the web process, like so:
OK there you go, no more 404 error when serving static files from your Django app on Heroku. Plus, every time you deploy your app, newly added static files will be collected automatically.
Update
There are a lot of questions about the configurations. Cross check with my settings.py here
Important thing here is your STATICFILES_DIRS. Make sure to include your project_name/app_name/static here. In my case, I have project_name/staticfiles for the STATIC_ROOT. Change STATIC_URL = β/static/β if you want to serve from Heroku, same goes to ADMIN_MEDIA_PREFIX = β/static/admin/β
Finally add this to your urls.py in order to serve from Heroku.
urlpatterns += patterns(β,
(rβ^static/(?P.*)$β, βdjango.views.static.serveβ, {βdocument_rootβ: settings.STATIC_ROOT}),
)
Files could be access as such:
/app/project_name/staticfiles/style.css >.
Pingback: Django Static Files on Heroku β elweb
Pingback: Managing Django Static Files on Heroku | ΠΡΠΎΠ³ΡΠ°ΠΌΠΈΡΠ°Π½Π΅
Iβve just been looking into Heroku for hosting myselfβ¦ I had read that the Cedar filesystem was ephemeral, i.e. wiped whenever the dyno is restarted. I thought that would preclude serving Djangoβs static files.
But do your commands above automatically run collectstatic when the new dyno is spun up, to reinstate them?
So it would just be user-uploaded files Iβd need to run from S3 instead?
Sorry for the late, late reply.
It will run every time you do git push heroku master.
FYI, Iβm using django storages & django compressor to serve static files via Amazon S3. In order for compressor to work, youβll need a temp file system cache on Heroku, thus the solution above.
Hi there, am running into the same problem.
I wonder how youβve setup your STATIC_URL, STATIC_ROOT and STATICFILES_DIR as Iβm almost hitting my head on the wall now
Post has been updated. Check the settings.py
I have a question. I tried your snippet to get static but for me it doesnβt work.
What do you have in settings file? What is STATIC_URL and STATIC_ROOT?
With regards
Kamil
Iβve included a sample of my settings.py. Cross check with yours
Thanks
Itβs working now. Founded solution.
So I have:
In Debug:
STATIC_ROOT = βstatic/β
STATIC_URL = β/static/β
and in urls.py
urlpatterns = patterns(β,
β¦####
#### urls urls urlsβ¦
)
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
And itβs working great
Bingo!
Even with Kamilβs writeup, Iβm not sure what youβre proposing here. Sure, running collectstatic gets all the files in one place.
But have you configured gunicorn to serve that directory separate from the Django staticfiles app?
(If youβre willing to run the staticfiles app with DEBUG on, thereβs not even a need to collectstatic; it seems to serve things fine from wherever they are. But thatβs βprobably insecureβ, says the Django docs. So Iβm trying to figure out if what you Kamil is describing somehow gets heroku-nginx or gunicorn to serve the collectedstatic directoryβ¦)
With more research Iβm guessing youβve each settled on some variant like this in urls.py:
if not settings.DEBUG:
# screw the vague FUD and django doctrine against non-DEBUG static-serving
urlpatterns += patterns(β,
(rβ^static/(?P.*)$β, βdjango.views.static.serveβ, {βdocument_rootβ :settings.STATIC_ROOT}),
)
The comments for βdjango.views.static.serveβ include more of the usual admonitions about how one βSHOULD NOTβ do this in a βproduction settingβ. But these similarly-worded-but-never-explained warnings have echoed across Django comments/docs so much theyβre beginning to look like superstitions to me rather than actual best practices.
Yup. Check my updated post.
Thanks for this post! It was very helpful in getting django static files on heroku running.
However, Iβve noticed that every time I deploy a change, even without adding any new static files, collectstatic has to run every time and causes the app restart to be longer. This is sort of annoying because any users on the site would experience a long response if they made a request while this process was happening. Do you have any advice for this problem?
This is because the collectstatic command is part of the Procfile. Quick solution will be creating two versions of Procfile, one with the collectstatic command.
I canβt think of other cleaner solution.
Nice post but I have a problem. I canβt get this done. Iβm getting:
unknown specifier: ?P.
My urls.py looks like:
admin.autodiscover()
urlpatterns = patterns(β,
β¦
β¦
)
if not settings.DEBUG:
urlpatterns += patternsβ,
(rβ^static/(?P.*)$β, βdjango.views.static.serveβ, {βdocument_rootβ: settings.STATIC_ROOT}),
)
Ok I did it. But still, heroku canβt find my static files
Make sure your STATIC_ROOT & STATICFILES_DIR are pointing to the right place.
Pingback: Heroku β Django app static files β Stack Overflow | Programmer Solution
I replace β^static/(?P.*)$β for just β^static/(.*)$β and now is working.
Donβt forget to import your settings file in your urls.py.
from yourapp import settings
Pingback: Heroku β Handling static files in Django app
Pingback: Your first Heroku Django app Β« Fear and Loathing on the Learning Curve Β» Observations on life, tech and web design from a slightly misanthropic mind.
Hey Mathew,
I followed what you have suggested, but Iβm hitting an error: Could not import settings βmy_django_app/settings.pyβ
More details here. Would appreciate any help!
Check my answer here
Pingback: Heroku Django: Handling static files. Could not import settings βmy_django_app/settings.pyβ
Hi! Thank you for the blog post. However, I encountered this issue when running βforeman startβ
13:59:40 web.1 | started with pid 2060
13:59:40 web.1 | Usage: manage.py collectstatic [options]
13:59:40 web.1 |
13:59:40 web.1 | Collect static files in a single location.
13:59:40 web.1 |
13:59:40 web.1 | manage.py: error: no such option: βnoinput;
13:59:40 web.1 | process terminated
13:59:40 system | sending SIGTERM to all processes
I used this line in my Profile:
web: python manage.py collectstatic βnoinput; gunicorn_django βworkers=4 βbind=0.0.0.0:$PORT
It seems to be an issue with chaining the commands together on one lineβ¦any idea?
Seems like itβs an issue with foreman only. I pushed it to the Heroku repo and the app ran fine..very strange.
Yup, the chaining is meant for Heroku only.
Pingback: Heroku β Handling static files in Django app | PHP Developer Resource
Thanks for the post!! Questionβ how would I handle serving just a handful of static files on Heroku, and the majority via my main backend on Amazon S3? There are just a few files that I need on Heroku (to be on the same domain nameβ¦ itβs related to browser compatibility issues), but I still want the rest of my files to be served via S3.
Any suggestions on how to go about this?
Hey Janelle,
I think that is possible. Just donβt use the {{ STATIC_URL }} template tag on the files that you want to serve from Heroku because it points to S3. Instead, use the absolute URL for these files.
For example: /app/lib/python2.7/site-packages/django/contrib/admin/media/css/login.css >
I wrote a bit about how to do this here:
So whatβs stopping you from committing the changed static files after running a collectstatic locally? Seems to work for me so far.
In my settings.py I have:
PROJECT_DIR = os.path.dirname(__file__)
Then I use that in settings.py and urls.py to set the static directoryβ¦ (Rather than a path starting in / as the manual insists on usingβ¦)
STATIC_ROOT = os.path.join(PROJECT_DIR, βstaticβ)
for exampleβ¦
Also, the procfile didnβt work. I got it working with:
web: python manage.py collectstatic βnoinput; gunicorn -b 0.0.0.0:$PORT -w 4 [project name].wsgi:application
[project name] is the folder containing wsgi.py
The following was enough if I committed the static files:
web: gunicorn -b 0.0.0.0:$PORT -w 4 [project name].wsgi:application
Pingback: Django non-rel on Heroku with less and coffee-script compilation Β« Be Amity
Pingback: Deployment of static files to Heroku | Web App (B)Log
Thanks,
I wonder how you would handle static files versions, the best I could have come up with is β
Sorry but after updating your urls.py to serve the static files doesnβt that mean that every static file requested will have to be served by both the Dyno and the Django app instead of just the Dyno.
This will push extra load on your app and that is the reason why it is marked as not good for production in the docs. | http://matthewphiong.com/managing-django-static-files-on-heroku | CC-MAIN-2013-20 | en | refinedweb |
updated copyright years
\ paths.fs path file handling 03may97jaw \ Copyright (C) 1995,1996,1997,1998,2000,2003,2004,2005,2006,2007,2008. \ include string.fs [IFUNDEF] +place : +place ( adr len adr ) 2dup >r >r dup c@ char+ + swap move r> r> dup c@ rot + swap c! ; [THEN] [IFUNDEF] place : place ( c-addr1 u c-addr2 ) 2dup c! char+ swap move ; [THEN] Variable fpath ( -- path-addr ) \ gforth Variable ofile Variable tfile : os-cold ( -- ) fpath $init ofile $init tfile $init pathstring 2@ fpath only-path init-included-files ; \ The path Gforth uses for @code{included} and friends. : also-path ( c-addr len path-addr -- ) \ gforth \G add the directory @i{c-addr len} to @i{path-addr}. >r r@ $@len IF \ add separator if necessary s" |" r@ $+! 0 r@ $@ + 1- c! THEN r> $+! ; : clear-path ( path-addr -- ) \ gforth \G Set the path @i{path-addr} to empty. s" " rot $! ; : $@ ; : next-path ( addr u -- addr1 u1 addr2 u2 ) \ addr2 u2 is the first component of the path, addr1 u1 is the rest 0 $split 2swap ; : ; : pathsep? dup [char] / = swap [char] \ = or ; : need/ ofile $@ 1- + c@ pathsep? 0= IF s" /" ofile $+! THEN ; : extractpath ( adr len -- adr len2 ) BEGIN dup WHILE 1- 2dup + c@ pathsep? IF EXIT THEN REPEAT ; : remove~+ ( -- ) ofile $@ s" ~+/" string-prefix? IF ofile 0 3 $del THEN ; : expandtopic ( -- ) \ stack effect correct? - anton \ expands "./" into an absolute name ofile $@ s" ./" string-prefix? IF ofile $@ 1 /string tfile $! includefilename 2@ extractpath ofile $! \ care of / only if there is a directory ofile $@len IF need/ THEN tfile $@ over c@ pathsep? IF 1 /string THEN ofile $+!@ move r> endif endif + nip over - ; \ test cases: \ s" z/../../../a" compact-filename type cr \ s" ../z/../../../a/c" compact-filename type cr \ s" /././//./../..///x/y/../z/.././..//..//a//b/../c" compact-filename type cr : reworkdir ( -- ) remove~+ ofile $@ compact-filename nip ofile $!len ; : open-ofile ( -- fid ior ) \G opens the file whose name is in ofile expandtopic reworkdir ofile $@ r/o open-file ; : check-path ( adr1 len1 adr2 len2 -- fid 0 | 0 ior ) >r >r ofile $! need/ r> r> ofile $+! $! open-ofile dup 0= IF >r ofile $@ r> THEN EXIT ELSE r> -&37 >r path>string BEGIN next-path dup WHILE r> drop 5 pick 5 pick check-path dup 0= IF drop >r 2drop 2drop r> ofile $@ ; | http://www.complang.tuwien.ac.at/viewcvs/cgi-bin/viewcvs.cgi/gforth/kernel/paths.fs?view=auto&rev=1.37&sortby=rev&only_with_tag=MAIN | CC-MAIN-2013-20 | en | refinedweb |
Is there any way of running and compiling with known errors in the code.
Her is my reason. I am using a reference to word 2008 and word 2010, so as the program will work with both versions. Trouble is that if the computer I am using to test the code, only has one installed (naturally) so the program wont compile or run for me to test other parts of the program. There must be a way of ignoring error which wont make any difference to the run time compile program.
Is there any way of running and compiling with known errors in the code.
Compiling? yes, running? No because the program has to be error-free in order to execute the code. There is no point in trying to execute a program that contains compile-time errors. How do you expect the compiler to generate executable code when the source code is crap?
Do you really need references to both versions of word at the same time? If you have the reference to word 2010 just test your program on a computer that has word 2008 installed on it.
Not as easy as that, and it is not CRAP code it is CRAP software that doesn't allow for this to work. On VB6 it would have worked fine.
The reason for the errors is because word 2003 needs to have the declared
Imports Word = Microsoft.Office.Interop.Word to work, but 2007 onwards uses a completely different method and doesn;t recognise this statement, and thus the several hundred of statement that uses the "word" variable. The fact is that the compiled programme would never error because the code would route the programme to the correct version installed.
And I cant test on a computer that has 2010 on it as that will then error on the 2003 part of the code. nAnd in any case it is not so much as testing the programme as adding new code to other parts of the programme. I am at a loos as to what to do.
The only method I see available to me is to have a different database programme for each version of work, which seems ridiculous. But it looks like that is the way it has to be, or go back to VB6!
Couldn't you check the version and then conditionally branch from there? I found an example here: Click Here. Some sample code to look at might be helpful... By the way, what versions are you trying to support? The original post states Word 2008 and Word 2010, but Word 2008 is in Office 2008 for Mac only as far as I know.
The Microsoft.Office.Interop.Word namespace is documented on MSDN for Word 2003 and Word 2010 only, so apparently not distributed with any other versions of Office. That said, the Interop assemblies are available for redistribution. The assemblies for Office 2010 are found here: Click Here, I have no idea what will happen if you install and reference those assemblies on a system that has Word 2007 installed, and whatever code you write would have to be isolated by version and tested on a specific basis.
HKLM\Word.Application.CurVer also has the version number on my system (Office 2010), but I don't know whether that key exists in any/all other versions.
Again, it would be helpful to know what versions you need to support.
Yes, Interesting reading, and it uses VB6, which seems to work fine without the errors. I am trying to use all versions of word, ie 2000,2002,2003,2007 and 2010. But as 2000 and 2002 are too different I have decided to drop them.
I have now managed to convert the errors to warnings by somehow adding the references even though the computer doesn;t have the relevant versions installed, and it seems to work, I will know for sure when I try running the compiled programme on some other machines that only have one version installed, but I think it is going to work.
If you're all set, mark the thread as solved.
Thanks | http://www.daniweb.com/software-development/vbnet/threads/440593/force-compile-with-errors | CC-MAIN-2013-20 | en | refinedweb |
Case
[1] "It's been quite a year," thought Tom Moline." On top of
their normal efforts at hunger advocacy and education on campus,
the twenty students in the Hunger Concerns group were spending the
entire academic year conducting an extensive study of hunger in
sub-Saharan Africa. Tom's girlfriend, Karen Lindstrom, had
proposed the idea after she returned from a semester-abroad program
in Tanzania last spring. With tears of joy and sorrow, she
had described for the group the beauty and suffering of the people
and land. Wracked by AIDS, drought, and political unrest, the
nations in the region are also fighting a losing war against hunger
and malnutrition. While modest gains have been made for the
more than 800 million people in the world that are chronically
malnourished, sub-Saharan Africa is the only region in the world
where the number of hungry people is actually increasing. It
was not hard for Karen to persuade the group to focus attention on
this problem and so they decided to devote one of their two
meetings per month to this study. In the fall, Karen and Tom
led three meetings examining root causes of hunger in various forms
of powerlessness wrought by poverty, war, and drought.
[2] What Tom had not expected was the special attention the
group would give to the potential which biotechnology poses for
improving food security in the region. This came about for
two reasons. One was the participation of Adam Paulsen in the
group. Majoring in economics and management, Adam had spent
last summer as an intern in the Technology Cooperation Division of
Monsanto. Recognized, and often vilified, as a global leader
in the field of agricultural biotechnology, Monsanto has also been
quietly working with agricultural researchers around the world to
genetically modify crops that are important for subsistence
farmers. For example, Monsanto researchers have collaborated
with governmental and non-governmental research organizations to
develop virus-resistant potatoes in Mexico, "golden mustard" rich
in beta-carotene in India, and virus-resistant papaya in Southeast
Asia.
[3] In December, Adam gave a presentation to the group that
focused on the role Monsanto has played in developing
virus-resistant sweet potatoes for Kenya. Sweet potatoes are
grown widely in Kenya and other developing nations because they are
nutritious and can be stored beneath the ground until they need to
be harvested. The problem, however, is that pests and
diseases can reduce yields by up to 80 percent. Following
extensive research and development that began in 1991, the Kenyan
Agricultural Research Institute (KARI) began field tests of
genetically modified sweet potatoes in 2001. Adam concluded
his presentation by emphasizing what an important impact this
genetically modified (GM) crop could have on food security for
subsistence farmers. Even if losses were only cut in half,
that would still represent a huge increase in food for people who
are too poor to buy the food they need.
[4] The second reason the group wound up learning more about the
potential biotechnology poses for increasing food production in
Kenya was because a new member joined the group. Josephine
Omondi, a first-year international student, had read an
announcement about Adam's presentation in the campus newsletter and
knew right away that she had to attend. She was, after all, a
daughter of one of the scientists engaged in biotechnology research
at the KARI laboratories in Nairobi. Struggling with
homesickness, Josephine was eager to be among people that cared
about her country. She was also impressed with the accuracy
of Adam's presentation and struck up an immediate friendship with
him when they discovered they both knew Florence Wambugu, the
Kenyan researcher that had initiated the sweet potato project and
had worked in Monsanto's labs in St. Louis.
[5] Naturally, Josephine had much to offer the group. A
month after Adam's presentation, she provided a summary of other
biotechnology projects in Kenya. In one case, tissue culture
techniques are being employed to develop banana varieties free of
viruses and other diseases that plague small and large-scale banana
plantations. In another case, cloning techniques are being
utilized to produce more hearty and productive chrysanthemum
varieties, a plant that harbors a chemical, pyrethrum, that
functions as a natural insecticide. Kenya grows nearly half
the global supply of pyrethrum, which is converted elsewhere into
environmentally-friendly mosquito repellants and
insecticides.1
[6] Josephine reserved the majority of her remarks, however, for
two projects that involve the development of herbicide- and
insect-resistant varieties of maize (corn). Every year
stem-boring insects and a weed named Striga decimate up to 60
percent of Kenya's maize harvest.2
Nearly 50 percent of the food Kenyans consume is maize, but maize
production is falling. While the population of East Africa
grew by 20 percent from 1989 to 1998, maize harvests actually
declined during this period.3 Josephine
stressed that this is one of the main reasons the number of hungry
people is increasing in her country. As a result, Kenyan
researchers are working in partnership with the International Maize
and Wheat Improvement Center (CIMMYT) to develop corn varieties
that can resist Striga and combat stem-borers. With pride,
Josephine told the group that both projects are showing signs of
success. In January 2002, KARI scientists announced they had
developed maize varieties from a mutant that is naturally resistant
to a herbicide which is highly effective against Striga. In a
cost-effective process, farmers would recoverthe small cost of
seeds coated with the herbicide through yield increases of up to
400 percent.4
[7] On the other front, Josephine announced that significant
progress was also being made between CIMMYT and KARI in efforts to
genetically engineer "Bt" varieties of Kenyan maize that would
incorporate the gene that produces Bacillus thuringiensis, a
natural insecticide that is used widely by organic farmers.
Josephine concluded her remarks by saying how proud she was of her
father and the fact that poor subsistence farmers in Kenya are
starting to benefit from the fruits of biotechnology, long enjoyed
only by farmers in wealthy nations.
[8] A few days after Josephine's presentation, two members of
the Hunger Concerns group asked if they could meet with Tom since
he was serving as the group's coordinator. As an
environmental studies major, Kelly Ernst is an ardent advocate of
organic farming and a strident critic of industrial approaches to
agriculture. As much as she respected Josephine, she
expressed to Tom her deep concerns that Kenya was embarking on a
path that was unwise ecologically and economically. She
wanted to have a chance to tell the group about the ways organic
farming methods can combat the challenges posed by stem-borers and
Striga.
[9] Similarly, Terra Fielding thought it was important that the
Hunger Concerns group be made aware of the biosafety and human
health risks associated with genetically modified (GM) crops.
Like Terra, Tom was also a biology major so he understood her
concerns about the inadvertent creation of herbicide-resistant
"superweeds" and the likelihood that insects would eventually
develop resistance to Bt through prolonged exposure. He also
understood Terra's concern that it would be nearly impossible to
label GM crops produced in Kenya since most food goes directly from
the field to the table. As a result, few Kenyans would be
able to make an informed decision about whether or not to eat
genetically-engineered foods. Convinced that both sets of
concerns were significant, Tom invited Kelly and Terra to give
presentations in February and March.
[10] The wheels came off during the meeting in April,
however. At the end of a discussion Tom was facilitating
about how the group might share with the rest of the college what
they had learned about hunger in sub-Saharan Africa, Kelly Ernst
brought a different matter to the attention of the group: a plea to
join an international campaign by Greenpeace to ban GM crops.
In the murmurs of assent and disapproval that followed, Kelly
pressed ahead. She explained that she had learned about the
campaign through her participation in the Environmental Concerns
group on campus. They had decided to sign on to the campaign
and were now actively encouraging other groups on campus to join
the cause as well. Reiterating her respect for Josephine and
the work of her father in Kenya, Kelly nevertheless stressed that
Kenya could achieve its food security through organic farming
techniques rather than the "magic bullet" of GM crops, which she
argued pose huge risks to the well-being of the planet as well as
the welfare of Kenyans.
[11] Before Tom could open his mouth, Josephine offered a
counter proposal. Angry yet composed, she said she fully
expected the group to vote down Kelly's proposal, but that she
would not be satisfied with that alone. Instead, she
suggested that a fitting conclusion to their study this year would
be for the group to submit an article for the college newspaper
explaining the benefits that responsible use of agricultural
biotechnology poses for achieving food security in sub-Saharan
Africa, particularly in Kenya.
[12] A veritable riot of discussion ensued among the twenty
students. The group appeared to be evenly divided over the
two proposals. Since the meeting had already run well past
its normal ending time, Tom suggested that they think about both
proposals and then come to the next meeting prepared to make a
decision. Everybody seemed grateful for the chance to think
about it for a while, especially Tom and Karen.
II
[13] Three days later, an intense conversation was taking place
at a corner table after dinner in the cafeteria.
[14] "Come on, Adam. You're the one that told us people
are hungry because they are too poor to buy the food they need,"
said Kelly. "I can tell you right now that there is plenty of
food in the world; we just need to distribute it better. If
we quit feeding 60 percent of our grain in this country to animals,
there would be plenty of food for everyone."
[15] "That may be true, Kelly, but we don't live in some ideal
world where we can wave a magic wand and make food land on the
tables of people in Africa. A decent food distribution
infrastructure doesn't exist within most of the countries.
Moreover, most people in sub-Saharan Africa are so poor they
couldn't afford to buy our grain. And even if we just gave it
away, all we would do is impoverish local farmers in Africa because
there is no way they could compete with our free food. Until
these countries get on their feet and can trade in the global
marketplace, the best thing we can do for their economic
development is to promote agricultural production in their
countries. Genetically modified crops are just one part of a
mix of strategies that Kenyans are adopting to increase food
supplies. They have to be able to feed themselves."
[16] "Yes, Africans need to feed themselves," said Kelly, "but I
just don't think that they need to follow our high-tech approach to
agriculture. Look at what industrial agriculture has done to
our own country. We're still losing topsoil faster than we
can replenish it. Pesticides and fertilizers are still
fouling our streams and groundwater. Massive monocultures
only make crops more susceptible to plant diseases and pests.
At the same time, these monocultures are destroying
biodiversity. Our industrial approach to agriculture is
living off of biological capital that we are not replacing.
Our system of agriculture is not sustainable. Why in God's
name would we want to see others appropriate it?"
[17] "But that's not what we're talking about," Adam
replied. "The vast majority of farmers in the region are
farming a one hectare plot of land that amounts to less than 2.5
acres. They're not buying tractors. They're not using
fertilizer. They're not buying herbicides. They can't
afford those things. Instead, women and children spend most
of their days weeding between rows, picking bugs off of plants, or
hauling precious water. The cheapest and most important
technology they can afford is improved seed that can survive in
poor soils and resist weeds and pests. You heard Josephine's
report. Think of the positive impact that all of those
projects are going to have for poor farmers in Kenya."
[18] Kelly shook her head. "Come on, Adam. Farmers
have been fighting with the weather, poor soils, and pests
forever. How do you think we survived without modern farming
methods? It can be done. We know how to protect soil
fertility through crop rotations and letting ground rest for a
fallow period. We also know how to intercrop in ways that cut
down on plant diseases and pests. I can show you a great
article in WorldWatch magazine that demonstrates how organic
farmers in Kenya are defeating stem-borers and combating
Striga. In many cases they have cut crop losses down to 5
percent. All without genetic engineering and all the dangers
that come with it."
[19] Finally Karen broke in. "But if that knowledge is so
wide-spread, why are there so many hungry people in Kenya?
I've been to the region. Most farmers I saw already practice
some form of intercropping, but they can't afford to let their land
rest for a fallow period because there are too many mouths to
feed. They're caught in a vicious downward spiral.
Until their yields improve, the soils will continue to become more
degraded and less fertile."
[20] Adam and Kelly both nodded their heads, but for different
reasons. The conversation seemed to end where it began; with
more disagreement than agreement.
III
[21] Later that night, Tom was in the library talking with Terra
about their Entomology exam the next day. It didn't take long
for Terra to make the connections between the material they were
studying and her concerns about Bt crops in Kenya. "Tom, we
both know what has happened with chemical insecticide
applications. After a period of time, the few insects that
have an ability to resist the insecticide survive and
reproduce. Then you wind up with an insecticide that is no
longer effective against pests that are resistant to it. Bt
crops present an even more likely scenario for eventual resistance
because the insecticide is not sprayed on the crop every now and
then. Instead, Bt is manufactured in every cell of the plant
and is constantly present, which means pests are constantly
exposed. While this will have a devastating effect on those
insects that don't have a natural resistance to Bt, eventually
those that do will reproduce and a new class of Bt-resistant
insects will return to munch away on the crop. This would be
devastating for organic farmers because Bt is one of the few
natural insecticides they can use and still claim to be
organic."
[22] "I hear you, Terra. But I know that Bt farmers in the
U.S. are instructed by the seed distributors to plant refuges
around their Bt crops so that some pests will not be exposed to Bt
and will breed with the others that are exposed, thus compromising
the genetic advantage that others may have."
[23] "That's true, Tom, but it's my understanding that farmers
are not planting big enough refuges. The stuff I've read
suggests that if you're planting 100 acres in soybeans, 30 acres
should be left in non-Bt soybeans. But it doesn't appear that
farmers are doing that. And that's here in the States.
How reasonable is it to expect a poor, uneducated farmer in East
Africa to understand the need for a refuge and also to resist the
temptation to plant all of the land in Bt corn in order to raise
the yield?"
[24] As fate would have it, Josephine happened to walk by just
as Terra was posing her question to Tom. In response, she
fired off several questions of her own. "Are you suggesting
Kenyan farmers are less intelligent than U.S. farmers, Terra?
Do you think we cannot teach our farmers how to use these new gifts
in a wise way? Haven't farmers in this country learned from
mistakes they have made? Is it not possible that we too can
learn from any mistakes we make?"
[25] "Josephine, those are good questions. It's just that
we're talking about two very different agricultural
situations. Here you have less than two million farmers
feeding 280 million people. With a high literacy rate, a huge
agricultural extension system, e-mail, and computers, it is
relatively easy to provide farmers with the information they
need. But you said during your presentation that 70 percent
of Kenya's 30 million people are engaged in farming. Do you
really think you can teach all of those people how to properly
utilize Bt crops?"
[26] "First of all, U.S. farmers do not provide all of the food
in this country. Where do you think our morning coffee and
bananas come from? Rich nations import food every day from
developing nations, which have to raise cash crops in order to
import other things they need in order to develop, or to pay debts
to rich nations. You speak in sweeping generalizations.
Obviously not every farmer in Kenya will start planting Bt corn
tomorrow. Obviously my government will recognize the need to
educate farmers about the misuse of Bt and equip them to do
so. We care about the environment and have good policies in
place to protect it. We are not fools, Terra. We are
concerned about the biosafety of Kenya."
[27] Trying to take some of the heat off of Terra, Tom asked a
question he knew she wanted to ask. "What about the dangers
to human health, Josephine? The Europeans are so concerned
they have established a moratorium on all new patents of
genetically-engineered foods and have introduced GM labeling
requirements. While we haven't done that here in the U.S.,
many are concerned about severe allergic reactions that could be
caused by foods made from GM crops. Plus, we just don't know
what will happen over the long term as these genes interact or
mutate. Isn't it wise to be more cautious and go slowly?"
[28] There was nothing slow about Josephine's reply. "Tom,
we are concerned about the health and well-being of our
people. But there is one thing that you people don't
understand. We view risks related to agricultural
biotechnology differently. It is reasonable to be concerned
about the possible allergenicity of GM crops, and we test for
these, but we are not faced primarily with concerns about allergic
reactions in Kenya. We are faced with declining food supplies and
growing numbers of hungry people. As Terra said, our
situations are different. As a result, we view the possible
risks and benefits differently. The people of Kenya should be
able to decide these matters for themselves. We are tired of
other people deciding what is best for us. The colonial era
is over. You people need to get used to it."
[29] With that, Josephine left as suddenly as she had
arrived. Worn out and reflective, both Tom and Terra decided
to return to studying for their exam the next day.
IV
[30] On Friday night, Karen and Tom got together for their
weekly date. They decided to have dinner at a local
restaurant that had fairly private booths. After Karen's
semester in Tanzania last spring, they had learned to cherish the
time they spent together. Eventually they started talking
about the decision the Hunger Concerns group would have to make
next week. After Karen summarized her conversation with Kelly
and Adam, Tom described the exchange he and Terra had with
Josephine.
[31] Karen said, "You know, I realize that these environmental
and health issues are important, but I'm surprised that no one else
seems willing to step back and ask whether anyone should be doing
genetic engineering in the first place. Who are we to mess
with God's creation? What makes us think we can improve on
what God has made?"
[32] "But Karen," Tom replied, "human beings have been mixing
genes ever since we figured out how to breed animals or graft
branches onto apple trees. We didn't know we were engaged in
genetic manipulation, but now we know more about the science of
genetics, and that has led to these new technologies. One of
the reasons we can support six billion people on this planet is
because scientists during the Green Revolution used their God-given
intelligence to develop hybrid stocks of rice, corn, and other
cereal crops that boosted yields significantly. They achieved
most of their success by cross-breeding plants, but that takes a
long time and it is a fairly inexact process. Various
biotechnologies including genetic engineering make it possible for
us to reduce the time it takes to develop new varieties, and they
also enable us to transfer only the genes we want into the host
species. The first Green Revolution passed by Africa, but
this second biotechnology revolution could pay huge dividends for
countries in Africa."
[33] "I understand all of that, Tom. I guess what worries
me is that all of this high science will perpetuate the myth that
we are masters of the universe with some God-given mandate to
transform nature in our image. We have got to quit viewing
nature as a machine that we can take apart and put back
together. Nature is more than the sum of its parts.
This mechanistic mindset has left us with all sorts of major
ecological problems. The only reason hybrid seeds produced so
much food during the Green Revolution is because we poured tons of
fertilizer on them and kept them alive with irrigation water.
And what was the result? We produced lots of grain but also
huge amounts of water pollution and waterlogged soils. We
have more imagination than foresight. And so we wind up
developing another technological fix to get us out of the problem
our last technological innovation produced. Instead, we need
to figure out how to live in harmony with nature. Rather than
be independent, we need to realize our ecological
interdependence. We are made from the dust of the universe
and to the dust of the earth we will return."
[34] "Huh, I wonder if anyone would recognize you as a religion
major, Karen? I agree that our scientific and technological
abilities have outpaced our wisdom in their use, but does that mean
we can't learn from our mistakes? Ultimately, aren't
technologies just means that we put to the service of the ends we
want to pursue? Why can't we use genetic engineering to end
hunger? Why would God give us the brains to map and
manipulate genomes if God didn't think we could use that knowledge
to better care for creation? Scientists are already
developing the next wave of products that will give us inexpensive
ways to vaccinate people in developing nations from debilitating
diseases with foods like bananas that carry the vaccine. We
will also be able to make food more nutritious for those that get
precious little. Aren't those good things, Karen?"
[35] Karen, a bit defensive and edging toward the other side of
the horseshoe-shaped booth, said, "Look Tom, the way we live is
just not sustainable. It scares me to see people in China,
and Mexico, and Kenya all following us down the same unsustainable
road. There has got to be a better way. Kelly is
right. Human beings lived more sustainably in the past than
we do now. We need to learn from indigenous peoples how to
live in harmony with the earth. But instead, we seem to be
tempting them to adopt our expensive and inappropriate
technologies. It just doesn't seem right to encourage
developing nations like Kenya to make huge investments in
biotechnology when less expensive solutions might better address
their needs. I really do have my doubts about the ability to
teach farmers how to use these new seeds wisely. I've been
there, Tom. Farmers trade seeds freely and will always follow
a strategy that will produce the most food in the short-term
because people are hungry now. Eventually, whatever gains are
achieved by biotechnology will be lost as weeds and insects become
resistant or the soils just give out entirely from overuse.
But I am really struggling with this vote next week because I also
know that we should not be making decisions for other people.
They should be making decisions for themselves. Josephine is
my friend. I don't want to insult her. But I really do
think Kenya is heading down the wrong road."
[36] "So how are you going to vote next week, Karen?"
[37] "I don't know, Tom. Maybe I just won't show up.
How are you going to vote?"
Commentary
[38] This commentary offers background information on global
food security, agricultural biotechnology, and genetically modified
organisms before it turns to general concerns about genetically
modified crops and specific ethical questions raised by the
case.
Food Security
[39] The nations of the world made significant gains in social
development during the latter half of the 20th century. Since 1960,
life expectancy has risen by one third in developing nations, child
mortality has been cut in half, the percentage of people who have
access to clean water has more than doubled, and the total
enrollment in primary schools has increased by nearly two- thirds.
Similar progress has been made in achieving a greater measure of
food security. Even though the world's population has more than
doubled since 1960, food production grew at a slightly faster rate
so that today per capita food availability is up 24 percent. More
importantly, the proportion of people who suffer from food
insecurity has been cut in half from 37 percent in 1969 to 18
percent in 1995.5
[40] According to the International Food Policy Research
Institute, the world currently produces enough food to meet the
basic needs for each of the planet's six billion people.
Nevertheless, more than 800 million people suffer from food
insecurity. For various reasons, one out of every eight human
beings on the planet cannot produce or purchase the food they need
to lead healthy, productive lives. One out of every three
preschool-age children in developing nations is either malnourished
or severely underweight.6 Of these, 14 million children
become blind each year due to Vitamin A deficiency. Every day,
40,000 people die of illnesses related to their poor
diets.7
[41] Food security is particularly dire in sub-Saharan Africa. It
is the only region in the world where hunger has been increasing
rather than decreasing. Since 1970, the number ofmalnourished
people has increased as the amount of food produced per person has
declined.8
According to the United Nations Development Programme, half of the
673 million people living in sub-Saharan Africa at the beginning of
the 21st century are living in absolute poverty on less than $1 a
day.9 Not
surprisingly, one third of the people are undernourished. In the
eastern portion of this region, nearly half of the children suffer
from stunted growth as a result of their inadequate diets, and that
percentage is increasing.10 In Kenya, 23 percent of
children under the age of five suffer from
malnutrition.11
[42] Several factors contribute to food insecurity in sub-Saharan
Africa. Drought, inadequate water supplies, and crop losses to
pests and disease have devastating impacts on the amount of food
that is available. Less obvious factors, however, often have a
greater impact on food supply. Too frequently, governments in the
region spend valuable resources on weapons, which are then used in
civil or regional conflicts that displace people and reduce food
production. In addition, many governments-hamstrung by
international debt obligations-have pursued economic development
strategies that bypass subsistence farmers and focus on the
production of cash crops for export. As a result, a few countries
produce significant amounts of food, but it is shipped to wealthier
nations and is not available for local consumption. Storage and
transportation limitations also result in inefficient distribution
of surpluses when they are produced within nations in the
region.12
[43] Poverty is another significant factor. Globally, the gap
between the rich and the poor is enormous. For example, the $1,010
average annual purchasing power of a Kenyan pales in comparison
with the $31,910 available to a citizen of the United
States.13 Poor
people in developing nations typically spend 50-80 percent of their
incomes for food, in comparison to the 10-15 percent that people
spend in the United States or the European Union.14 Thus, while food may be
available for purchase, fluctuating market conditions often drive
prices up to unaffordable levels. In addition, poverty limits the
amount of resources a farmer can purchase to "improve" his or her
land and increase yields. Instead, soils are worked without rest in
order to produce food for people who already have too little to
eat.
[44] One way to deal with diminished food supplies or high prices
is through the ability to grow your own food. Over 70 percent of
the people living in sub-Saharan Africa are subsistence farmers,
but the amount of land available per person has been declining over
the last thirty years. While the concentration of land in the hands
of a few for export cropping plays an important role in this
problem, the primary problem is population growth in the region. As
population has grown, less arable land and food is available per
person. In 1970, Asia, Latin America, and Africa all had similar
population growth rates. Since then Asia has cut its rate of growth
by 25 percent, and Latin America has cut its rate by 20
percent.15 In
contrast, sub-Saharan Africa still has a very high population
growth rate, a high fertility rate, and an age structure where 44
percent of its population is under the age of fifteen. As a result,
the United Nations projects that the region's population will more
than double by 2050, even after taking into account the devastating
impact that AIDS will continue to have on many
countries.16
[45] Local food production will need to increase substantially in
the next few decades in order to meet the 133 percent projected
growth of the population in sub-Saharan Africa. Currently, food aid
donations from donor countries only represent 1.1 percent of the
food supply. The region produces 83 percent of its own food and
imports the rest.17 Given the limited financial
resources of these nations, increasing imports is not a viable
strategy for the future. Instead, greater efforts must be made to
stimulate agricultural production within the region, particularly
among subsistence farmers. Unlike Asia, however, increased
production will not likely be achieved through the irrigation of
fields and the application of fertilizer. Most farmers in the
region are simply too poor to afford these expensive inputs.
Instead, the main effort has been to improve the least expensive
input: seeds.
[46] A great deal of public and private research is focused on
developing new crop varieties that are resistant to drought, pests,
and disease and are also hearty enough to thrive in poor
soils.18 While
the vast majority of this research utilizes traditional
plant-breeding methods, nations like Kenya and South Africa are
actively researching ways that the appropriate use of biotechnology
can also increase agricultural yields. These nations, and a growing
list of others, agree with a recent statement by the United Nations
Food and Agriculture Organization:
[47]β¦. It [genetic engineering] could lead to
higher yields on marginal lands in countries that today cannot grow
enough food to feed their people. 19
Agricultural Biotechnology
[48] The United Nations Convention on Biological Diversity (CBD)
defines biotechnology as "any technological application that uses
biological systems, living organisms, or derivatives thereof, to
make or modify products or processes for specific
use."20 The
modification of living organisms is not an entirely new
development, however. Human beings have been grafting branches onto
fruit trees and breeding animals for desired traits since the
advent of agriculture 10,000 years ago. Recent advances in the
fields of molecular biology and genetics, however, considerably
magnify the power of human beings to understand and transform
living organisms.
[49] The cells of every living thing contain genes that determine
the function and appearance of the organism. Each cell contains
thousands of genes. Remarkably, there is very little difference in
the estimated number of genes in plant cells (26,000) and human
cells (30,000). Within each cell, clusters of these genes are
grouped together in long chains called chromosomes. Working in
isolation or in combination, these genes and chromosomes determine
the appearance, composition, and functions of an organism. The
complete list of genes and chromosomes in a particular species is
called the genome.21
[50] Like their predecessors, plant breeders and other
agricultural scientists are making use of this rapidly growing body
of knowledge to manipulate the genetic composition of crops and
livestock, albeit with unprecedented powers. Since the case focuses
only on genetically modified crops, this commentary will examine
briefly the use in Africa of the five most common applications of
biotechnology to plant breeding through the use of tissue culture,
marker-assisted selection, genetic engineering, genomics, and
bioinformatics.22
[51] Tissue culture techniques enable researchers to develop whole
plants from a single cell, or a small cluster of cells. After
scientists isolate the cell of a plant that is disease-free or
particularly hearty, they then use cloning techniques to produce
large numbers of these plants in vitro, in a petri dish. When the
plants reach sufficient maturity in the laboratory, they are
transplanted into agricultural settings where farmers can enjoy the
benefits of crops that are more hearty or disease-free. In the
case, Josephine describes accurately Kenyan successes in this area
with regard to bananas and the plants that produce pyrethrum. This
attempt to micro-propagate crops via tissue cultures constitutes
approximately 52 percent of the activities in the 37 African
countries engaged in various forms of biotechnology
research.23
[52] Marker-assisted selection techniques enable researchers to
identify desirable genes in a plant's genome. The identification
and tracking of these genes speeds up the process of conventional
cross-breeding and reduces the number of unwanted genes that are
transferred. The effort to develop insect-resistant maize in Kenya
uses this technology to identify local varieties of maize that have
greater measures of natural resistance to insects and disease.
South Africa, Zimbabwe, Nigeria, and CΓ΄te d'Ivoire are all
building laboratories to conduct this form of research.
24
[53] Genetic engineering involves the direct transfer of genetic
material between organisms. Whereas conventional crossbreeding
transfers genetic material in a more indirect and less efficient
manner through the traditional propagation of plants, genetic
engineering enables researchers to transfer specific genes directly
into the genome of a plant in vitro. Originally, scientists used
"gene guns" to shoot genetic material into cells. Increasingly,
researchers are using a naturally occurring plant pathogen,
Agrobacterium tumefaciens, to transfer genes more successfully and
selectively into cells. Eventually, Josephine's father intends to
make use of this technology to "engineer" local varieties of maize
that will include a gene from Bacillus thuringiensis (Bt), a
naturally occurring bacterium that interferes with the digestive
systems of insects that chew or burrow into plants. Recent reports
from South Africa indicate thatsmallholder farmers who have planted
a Bt variety of cotton have experienced "great
success."25
[54] Genomics is the study of how all the genes in an organism
work individually or together to express various traits. The
interaction of multiple genes is highly complex and studies aimed
at discerning these relationships require significant computing
power. Bioinformatics moves this research a step further by taking
this genomic information and exploring the ways it may be relevant
to understanding the gene content and gene order of similar
organisms. For example, researchers recently announced that they
had successfully mapped the genomes of two different rice
varieties.26
This information will likely produce improvements in rice yields,
but researchers drawing on the new discipline of bioinformatics
will also explore similarities between rice and other cereal crops
that have not yet been mapped. Nations like Kenya, however, have
not yet engaged in these two forms of biotechnology research
because of the high cost associated with the required computing
capacity.
Genetically Modified Organisms in Agriculture
[55] The first genetically modified organisms were
developed for industry and medicine, not agriculture. In 1972, a
researcher working for General Electric engineered a microbe that
fed upon spilled crude oil, transforming the oil into a more benign
substance. When a patent was applied for the organism, the case
made its way ultimately to the U.S. Supreme Court, which in 1980
ruled that a patent could be awarded for the modification of a
living organism. One year earlier, scientists had managed to splice
the gene that produces human growth hormone into a bacterium, thus
creating a new way to produce this vital hormone.27
[56] In 1994, Calgene introduced the Flavr-Savr tomato. It was the
first commercially produced, genetically modified food product.
Engineered to stay on the vine longer, develop more flavor, and
last longer on grocery shelves, consumers rejected the product not
primarily because it was genetically modified, but rather because
it was too expensive and did not taste any better than ordinary
tomatoes.28
[57] By 1996, the first generation of genetically modified (GM)
crops was approved for planting in six countries. These crops
included varieties of corn, soybeans, cotton, and canola that had
been engineered to resist pests or to tolerate some herbicides.
Virus resistance was also incorporated into some tomato, potato,
and tobacco varieties.
[58] Farmers in the United States quickly embraced these
genetically modified varieties because they reduced the cost of
pesticide and herbicide applications, and in some cases also
increased yields substantially. In 1996, 3.6 million acres were
planted in GM crops. By 2000 that number had grown to 75 million
acres and constituted 69 percent of the world's production of GM
crops.29
According to the U.S. Department of Agriculture's 2002 spring
survey, 74 percent of the nation's soybeans, 71 percent of cotton,
and 32 percent of the corn crop were planted in genetically
engineered varieties, an increase of approximately 5 percent over
2001 levels.30
[59] Among other developed nations, Canada produced 7 percent of
the world's GM crops in 2000, though Australia, France, and Spain
also had plantings.31 In developing nations, crop
area planted in GM varieties grew by over 50 percent between 1999
and 2000.32
Argentina produced 23 percent of the global total in 2000, along
with China, South Africa, Mexico, and Uruguay.33
[60] In Kenya, no GM crops have been approved for commercial
planting, though the Kenyan Agricultural Research Institute (KARI)
received government permission in 2001 to field test genetically
modified sweet potatoes that had been developed in cooperation with
Monsanto.34 In
addition, funding from the Novartis Foundation for Sustainable
Development is supporting research KARI is conducting in
partnership with the International Maize and Wheat and Improvement
Center (CIMYYT) to develop disease and insect-resistant varieties
of maize, including Bt maize.35 A similar funding
relationship with the Rockefeller Foundation is supporting research
to develop varieties of maize from a mutant type that is naturally
resistant to a herbicide thatis highly effective against Striga, a
weed that devastates much of Kenya's maize crop each
year.36 Striga
infests approximately 2040 million hectares of farmlandin
sub-Saharan Africa and reduces yields for an estimated 100 million
farmers by 20-80 percent.37
General Concerns about Genetically Modified (GM)
Crops
[61] The relatively sudden and significant growth of GM crops
around the world has raised various social, economic, and
environmental concerns. People in developed and developing
countries are concerned about threats these crops may pose to human
health and the environment. In addition, many fear that large
agribusiness corporations will gain even greater financial control
of agriculture and limit the options of small-scale farmers.
Finally, some are also raising theological questions about the
appropriateness of genetic engineering.
[62] Food Safety and Human Health. Some critics of GM foods in the
United States disagree with the government's stance that
genetically engineered food products are "substantially equivalent"
to foods derived from conventional plant breeding. Whereas
traditional plant breeders attempt to achieve expression of genetic
material within a species, genetic engineering enables researchers
to introduce genetic material from other species, families, or even
kingdoms. Because researchers can move genes from one life form
into any other, critics are concerned about creating novel
organisms that have no evolutionary history. Their concern is that
we do not know whatimpact these new products will have on human
health because they have never existed before.38
[63] Proponents of genetically engineered foods argue that genetic
modification is much more precise and less random than the methods
employed in traditional plant breeding. Whereas most genetically
engineered foods have involved the transfer of one or two genes
into the host, traditional crossbreeding results in the transfer of
thousands of genes. Proponents also note that GM crops have not
been proven to harm human health since they were approved for use
in 1996. Because the United States does not require the labeling of
genetically engineered foods, most consumers are not aware that
more than half of the products on most grocery store shelves are
made, at least in part, from products derived from GM crops. To
date, no serious human health problems have been attributed to GM
crops.39
Critics are not as sanguine about this brief track record and argue
that it is not possible to know the health effects of GM crops
because their related food products are not labeled.
[64] The potential allergenicity of genetically modified foods is
a concern that is shared by both critics and proponents of the
technology. It is possible that new genetic material may carry with
it substances that could trigger serious human allergic reactions.
Proponents, however, are more confident than critics that these
potential allergens can be identified in the testing process. As a
case in point, they note that researchers working for Pioneer Seeds
scuttled a project when they discovered that a genetically
engineered varietyof soybeans carried the gene that produces severe
allergic reactions associated with Brazil nuts.40 Critics, however, point to
the StarLink corn controversy as evidence of how potentially
dangerous products can easily slip into the human food supply.
Federal officials had only allowed StarLink corn to be used as an
animal feed because tests were inconclusive with regard to the
dangers it posed for human consumption. In September 2000, however,
StarLink corn was found first in a popular bran of taco shells and
later in other consumer goods. These findings prompted several
product recalls and cost Aventis, the producer of StarLink, over $1
billion.41
[65] More recently the U.S. Department of Agriculture and the Food
and Drug Administration levied a $250,000 fine against ProdiGene
Inc. for allowing genetically engineered corn to contaminate
approximately 500,000 bushels of soybeans. ProdiGene had
genetically engineered the corn to produce a protein that serves as
a pig vaccine. When the test crop failed, ProdiGene plowed under
the GM corn and planted food grade soybeans. When ProdiGene
harvested the soybeans federal inspectors discovered that some of
the genetically engineered corn had grown amidst the soybeans.
Under federal law, genetically engineered substances that have not
been approved for human consumption must be removed from the food
chain. The $250,000 fine helped to reimburse the federal government
for the cost of destroying the contaminated soybeans that were
fortunately all contained in a storage facility in Nebraska.
ProdiGenealso was required to post a $1 million bond in order to
pay for any similar problems in the future.42
[66] Another food safety issue involves the use of marker genes
that are resistant to certain antibiotics. The concern is that
these marker genes, which are transferred in almost all successful
genetic engineering projects, may stimulate the appearance of
bacteria resistant to common antibiotics.43 Proponents acknowledge that
concerns exist and are working on ways to either remove the marker
genes from the finished product, or to develop new and harmless
markers. Proponents also acknowledge that it may be necessary to
eliminate the first generation of antibiotic markers through
regulation.44
[67] Finally, critics also claim that genetic engineering may
lower the nutritional quality of some foods. For example, one
variety of GM soybeans has lowerlevels of isoflavones, which
researchers think may protect women from some forms of
cancer.45
Proponents of genetically modified foods, meanwhile, are busy
trumpeting the "second wave" of GM crops that actually increase the
nutritional value of various foods. For example, Swiss researchers
working in collaboration with the Rockefeller Foundation, have
produced "Golden Rice," a genetically engineered rice that is rich
in beta carotene and will help to combat Vitamin A deficiency in
the developing world.
[68] Biosafety and Environmental Harm. Moving from human health to
environmental safety, many critics of GM crops believe that this
use of agricultural biotechnology promotes an industrialized
approach to agriculture that has produced significant ecological
harm. Kelly summarizes these concerns well in the case. Crops that
have been genetically engineered to be resistant to certain types
of herbicide make it possible for farmers to continue to spray
these chemicals on their fields. In addition, GM crops allow
farmers to continue monocropping practices (planting huge tracts of
land in one crop variety), which actually exacerbate pest and
disease problems and diminish biodiversity. Just as widespread and
excessive use of herbicides led to resistant insects, critics argue
that insects eventually will become resistant to the second wave of
herbicides in GM crops. They believe that farmers need to be
turning to a more sustainable form of agriculture that utilizes
fewer chemicals and incorporates strip and inter-cropping
methodologies that diminish crop losses due to pests and
disease.46
[69] Proponents of GM crops are sympathetic to the monocropping
critique and agree that farmers need to adopt more sustainable
approaches to agriculture, but they argue that there is no reason
why GM crops cannot be incorporated in other planting schemes. In
addition, they suggest that biodiversity can be supported through
GM crops that are developed from varieties that thrive in
particular ecological niches. In contrast to the Green Revolution
where hybrids were taken from one part of the world and planted in
another, GM crops can be tailored to indigenous varieties that have
other desirable properties. On the herbicide front, proponents
argue that GM crops make it possible to use less toxic herbicides
than before, thus lowering the risks to consumers. They also point
to ecological benefits of the newest generation of herbicides which
degrade quickly when exposed to sunlight and do not build up in
groundwater.47
Critics, however, dispute these claims and point to evidence that
herbicides are toxic tonon-target species, harm soil fertility, and
also may have adverse effects on human health.48
[70] Just as critics are convinced that insects will develop
resistance to herbicides, so also are they certain that insects
will develop resistance to Bt crops. Terra makes this point in the
case. It is one thing to spray insecticides on crops at various
times during the growing season; it is another thing for insects to
be constantly exposed to Bt since it is expressed through every
cell in the plant, every hour of the day. While the GM crop will
have a devastating impact on most target insects, some will
eventually survive with a resistance to Bt. Proponents acknowledge
that this is a serious concern. As is the case with herbicides,
however, there are different variants of Bt that may continue to be
effective against partially resistant insects. In addition,
proponents note that the U.S. Environmental Protection Agency now
requires farmers planting Bt crops to plant refuges of non-Bt crops
so that exposed insects can mate with others that have not been
exposed, thus reducing the growth of Bt-resistant insects. These
refuges should equal 20 percent of the cropped area. Critics argue
that this percentage is too low and that regulations do not
sufficiently stipulate where these refuges should be in relation to
Bt crops.49
[71] Critics are also concerned about the impact Bt could have on
non-target species like helpful insects, birds, and bees. In May
1999, researchers at Cornell University published a study
suggesting that Bt pollen was leading to increased mortality among
monarch butterflies. This research ignited a firestorm of
controversy that prompted further studies by critics and proponents
of GM crops. One of the complicating factors is that an uncommon
variety of Bt corn was used in both the laboratory and field tests.
Produced by Novartis, the pollen from this type was 40-50 times
more potent than other Bt corn varieties, but it represented less
than 2 percent of the Bt corn crop in 2000. When other factors were
taken into account, proponents concluded that monarch butterflies
have a much greater chance of being harmed through the application
of conventional insecticides than they do through exposure to Bt
corn pollen. Critics, however, point to other studies that indicate
Bt can adversely harm beneficial insect predators and compromise
soil fertility.50
[72] Both critics and proponents are concerned about unintended
gene flow between GM crops and related plants in the wild. In many
cases it is possible for genes, including transplanted genes, to be
spread through the normal cross-pollination of plants. Whether
assisted by the wind or pollen-carrying insects,
cross-fertilization could result in the creation of
herbicide-resistant superweeds. Proponents of GM crops acknowledge
that this could happen, but they note that the weed would only be
resistant to one type of herbicide, not the many others that are
available to farmers. As a result, they argue that
herbicide-resistant superweeds could be controlled and eliminated
over a period of time. Critics are also concerned, however, that
undesired gene flow could "contaminate" the genetic integrity of
organic crops or indigenous varieties. This would be devastating to
organic farmers who trade on their guarantee to consumers that
organic produce has not been genetically engineered. Proponents
argue that this legitimate concern could be remedied with
relatively simple regulations or guidelines governing the location
of organic and genetically engineered crops. Similarly, they argue
that care must be taken to avoid the spread of genes into
unmodified varieties of the crop.51
[73] Agribusiness and Economic Justice. Shifting to another arena
of concern, many critics fear that GM crops will further expand the
gap between the rich and the poor in both developed and developing
countries. Clearly the first generation of GM crops has been
profit-driven rather than need-based. Crops that are
herbicide-tolerant and insect-resistant have been developed for and
marketed to relatively wealthy, large-scale, industrial
farmers.52 To
date, the benefits from these crops have largely accrued to these
large producers and not to small subsistence farmers or even
consumers. Proponents, however, argue that agricultural
biotechnologies are scale-neutral. Because the technology is in the
seed, expensive and time-consuming inputs are not required. As a
result, small farmers can experience the same benefits as large
farmers. In addition, proponents point to the emerging role public
sector institutions are playing in bringing the benefits of
agricultural biotechnology to developing countries. Partnerships
like those described above between KARI, CIMMYT, and various
governmental and non-governmental funding sources indicate that the
next generation of GM crops should have more direct benefits for
subsistence farmers and consumers in developing nations.
[74] While these partnerships in the public sector are developing,
there is no doubt that major biotech corporations like Monsanto
have grown more powerful as a result of the consolidation that has
taken place in the seed and chemical industries. For example, in
1998, Monsanto purchased DeKalb Genetics Corporation, the second
largest seed corn company in the United States. One year later,
Monsanto merged with Pharmacia & Upjohn, a major pharmaceutical
conglomerate. A similar merger took place between Dow Chemical
Corporation and Pioneer Seeds.53 The result of this
consolidation is the vertical integration of the seed and chemical
industries. Today, a company like Monsanto not only sells chemical
herbicides; it also sells seed for crops that have been genetically
engineered to be resistant to the herbicide. In addition, Monsanto
requires farmers to sign a contract that prohibits them from
cleaning and storing a portion of their GM crop to use as seed for
the following year. All of these factors lead critics to fear that
the only ones who will benefit from GM crops are rich corporations
and wealthy farmers who can afford to pay these fees. Critics in
developing nations are particularly concerned about the prohibition
against keeping a portion of this year's harvest as seed stock for
the next. They see this as a means of making farmers in developing
nations dependent upon expensive seed they need to purchase from
powerful agribusiness corporations.54
[75] Proponents acknowledge these concerns but claim that there is
nothing about them that is unique to GM crops. Every form of
technology has a price, and that cost will always be easier to bear
if one has a greater measure of wealth. They note, however, that
farmers throughout the United States have seen the financial wisdom
in planting GM crops and they see no reason why farmers in
developing nations would not reach the same conclusion if the
circumstances warrant. Proponents also note that subsistence
farmers in developing nations will increasingly have access to free
or inexpensive GM seed that has been produced through partnerships
in the public sector. They also tend to shrug off the prohibition
regarding seed storage because this practice has been largely
abandoned in developed nations that grow primarily hybrid crop
varieties. Harvested hybrid seed can be stored for later planting,
but it is not as productive as the original seed that was purchased
from a dealer. As farmers invest in mechanized agriculture, GM seed
becomes just another cost variable that has to be considered in the
business called agriculture. Critics, however, bemoan the loss of
family farms that has followed the mechanization of
agriculture.
[76] The seed storage issue reflects broader concerns about the
ownership of genetic material. For example, some developing nations
have accused major biotech corporations of committing genetic
"piracy." They claim that employees of these corporations have
collected genetic material in these countries without permission
and then have ferried them back to laboratories in the United
States and Europe where they have been studied, genetically
modified, and patented. In response to these and other concerns
related to intellectual property rights, an international
Convention on Biological Diversity was negotiated in 1992. The
convention legally guarantees that all nations, including
developing countries, have full legal control of "indigenous
germplasm."55
It also enables developing countries to seek remuneration for
commercial products derived from the nation's genetic resources.
Proponents of GM crops affirm the legal protections that the
convention affords developing nations and note that the development
of GM crops has flourished in the United States because of the
strong legal framework that protects intellectual property rights.
At the same time, proponents acknowledge that the payment of
royalties related to these rights or patents can drive up the cost
of GM crops and thus slow down the speed by which this technology
can come to the assistance of subsistence farmers.56
[77] Theological Concerns. In addition to the economic and legal
issues related to patenting genetic information and owning novel
forms of life, some are also raising theological questions about
genetic engineering. One set of concerns revolves around the
commodification of life. Critics suggest that it is not appropriate
for human beings to assert ownership over living organisms and the
processes of life that God has created. This concern has reached a
fever pitch in recent years during debates surrounding cloning
research and the therapeutic potential of human stem cells derived
from embryonic tissue. For many, the sanctity of human life is at
stake. Fears abound that parents will seek to "design" their
children through genetic modification, or that embryonic tissue
will be used as a "factory" to produce "spare parts."
[78] While this debate has raged primarily in the field of medical
research, some critics of GM crops offer similar arguments. In the
case, Karen gives voice to one of these concerns when she suggests
that we need to stop viewing nature as a machine that can be taken
apart and reassembled in other ways. Ecofeminist philosophers and
theologians argue that such a mechanistic mindset allows human
beings to objectify and, therefore, dominate nature in the same way
that women and slaves have been objectified and oppressed. Some
proponents of genetic engineering acknowledge this danger but argue
that the science and techniques of agricultural biotechnology can
increase respect for nature rather than diminish it. As human
beings learn more about the genetic foundations of life, it becomes
clearer how all forms of life are interconnected. For proponents of
GM crops, agricultural biotechnology is just a neutral means that
can be put to the service of either good or ill ends. Critics,
however, warn that those with power always use technologies to
protect their privilege and increase their control.
[79] Another set of theological concerns revolves around the
argument that genetic engineering is "unnatural" because it
transfers genetic material across species boundaries in ways that
do not occur in nature. Researchers are revealing, however, that
"lower" organisms like bacteria do not have the same genetic
stability as "higher" organisms that have evolved very slowly over
time. In bacteria, change often occurs by the spontaneous transfer
of genes from one bacterium to another of a different
species.57
Thus, specie boundaries may not be as fixed as has been previously
thought. Another example can be found in the Pacific Yew tree that
produces taxol, a chemical that is useful in fighting breast
cancer. Recently, researchers discovered that a fungus that often
grows on Yew trees also produces the chemical. Apparently the
fungus gained this ability through a natural transfer of genes
across species and even genera boundaries from the tree to the
fungus.58
[80] Appeals to "natural" foods also run into problems when closer
scrutiny is brought to bear on the history of modern crops. For
example, the vast majority of the grain that is harvested in the
world is the product of modern hybrids. These hybrid crops consist
of varieties that could not cross-breed without human assistance.
In fact, traditional plant breeders have used a variety of
high-tech means to develop these hybrids, including exposure to
low-level radiation and various chemicals in order to generate
desired mutations. After the desired traits are achieved, cloning
techniques have been utilized to develop the plant material and to
bring the new product to markets. None of this could have occurred
"naturally," if by that one means without human intervention, and
yet the products of this work are growing in virtually every farm
field. Given the long history of human intervention in nature via
agriculture, it is hard to draw a clear line between what
constitutes natural and unnatural food.59
[81] This leads to a third, related area of theological concern:
With what authority, and to what extent, should human beings
intervene in the world that God has made? It is clear from Genesis
2 that Adam, the first human creature, is given the task of tending
and keeping the Garden of Eden which God has created. In addition,
Adam is allowed to name the animals that God has made. Does that
mean that human beings should see their role primarily as passive
stewards or caretakers of God's creation? In Genesis 1, human
beings are created in the image of God (imago dei) and are told to
subdue the earth and have dominion over it. Does this mean that
human beings, like God, are also creators of life and have been
given the intelligence to use this gift wisely in the exercise of
human dominion?
[82] Answers to these two questions hinge on what it means to be
created in the image of God. Some argue that human beings are
substantially like God in the sense that we possess qualities we
ascribe to the divine, like the capacity for rational thought,
moral action, or creative activity. These distinctive features
confer a greater degree of sanctity to human life and set us apart
from other creatures-if not above them. Others argue that creation
in the image of God has less to do with being substantially
different from other forms of life, and more to do with the
relationality of God to creation. In contrast to substantialist
views which often set human beings above other creatures, the
relational conception of being created in the image of God seeks to
set humanity in a proper relationship of service and devotion to
other creatures and to God. Modeled after the patterns of
relationship exemplified in Christ, human relationships to nature
are to be characterized by sacrificial love and earthly
service.60
[83] It is not necessary to choose between one of these two
conceptions of what it means to be created in the image of God, but
it is important to see how they function in current debates
surrounding genetic engineering. Proponents of genetic engineering
draw on the substantialist conception when they describe the
technology as simply an outgrowth of the capacities for
intelligence and creativity with which God has endowed human
beings. At the same time, critics draw upon the same substantialist
tradition to protect the sanctity of human life from genetic
manipulation. More attention, however, needs to be given to the
relevance of the relational tradition to debates surrounding
genetic engineering. Is it possible that human beings could wield
this tool not as a means to garner wealth or wield power over
others, but rather as a means to improve the lives of others? Is it
possible to use genetic engineering to feed the hungry, heal the
sick, and otherwise to redeem a broken world? Certainly many
proponents of genetic engineering in the non-profit sector believe
this very strongly.
[84] Finally, another theological issue related to genetic
engineering has to do with the ignorance of human beings as well as
the power of sin and evil. Many critics of genetic engineering
believe that all sorts of mischief and harm could result from the
misuse of this new and powerful technology. In the medical arena,
some forecast an inevitable slide down a slippery slope into a
moral morass where human dignity is assaulted on all sides. In
agriculture, many fear that human ignorance could produce
catastrophic ecological problems as human beings design and release
into the "wild" novel organisms that have no evolutionary
history.
[85] There is no doubt that human technological inventions have
been used intentionally to perpetrate great evil in the world,
particularly in the last century. It is also abundantly clear that
human foresight has not anticipated enormous problems associated,
for example, with the introduction of exotic species in foreign
lands or the disposal of high-level nuclear waste. The question,
however, is whether human beings can learn from these mistakes and
organize their societies so that these dangers are lessened and
problems are averted. Certainly most democratic societies have been
able to regulate various technologies so that harm has been
minimized and good has been produced. Is there reason to believe
that the same cannot be done with regard to genetic
engineering?
Specific Ethical Questions
[86] Beyond this review of general concerns about GM crops and
genetic engineering are specific ethical questions raised by the
case. These questions are organized around the four ecojustice
norms that have been discussed in this volume.
[87] Sufficiency. At the heart of this case is the growing problem
of hunger in sub-Saharan Africa. It is clear that many people in
this region simply do not have enough to eat. In the case, however,
Kelly suggests that the world produces enough food to provide
everyone with an adequate diet. Is she right?
[88] As noted earlier, studies by the International Food Policy
and Research Institute indicate that the world does produce enough
food to provide everyone in the world with a modest diet. Moreover,
the Institute projects that global food production should keep pace
with population growth between 2000-2020. So, technically, Kelly is
right. Currently, there is enough food for everyone-so long as
people would be satisfied by a simple vegetarian diet with very
little meat consumption. The reality, however, is that meat
consumption is on the rise around the world, particularly among
people in developing nations that have subsisted primarily on
vegetarian diets that often lack protein.61 Thus, while it appears that
a balanced vegetarian diet for all might be possible, and even
desirable from a health standpoint, it is not a very realistic
possibility. In addition, Adam raises a series of persuasive
arguments that further challenge Kelly's claim that food just needs
to be distributed better. At a time when donor nations only supply
1.1 percent of the food in sub-Saharan Africa, it is very
unrealistic to think that existing distribution systems could be
"ramped up" to provide the region with the food it needs.
[89] Does that mean, however, that GM crops represent a "magic
bullet" when it comes to increasing food supplies in the region?
Will GM crops end hunger in sub-Saharan Africa? It is important to
note that neither Adam nor Josephine make this claim in the case;
Kelly does. Instead, Adam argues that GM crops should be part of a
"mix" of agricultural strategies that will be employed to increase
food production and reduce hunger in the region. When stem-borers
and Striga decimate up to 60 percent of the annual maize harvest,
herbicide- and insect-resistant varieties could significantly
increase the food supply. One of the problems not mentioned in the
case, however, is that maize production is also very taxing on
soils. This could be remedied, to some extent, by rotating maize
with nitrogen-fixing, leguminous crops.
[90] In the end, the primary drain on soil fertility is the heavy
pressure which population growth puts on agricultural production.
Until population growth declines to levels similar to those in Asia
or Latin America, food insecurity will persist in sub-Saharan
Africa. One of the keys to achieving this goal is reducing the rate
of infant and child mortality. When so many children die in
childhood due to poor diets, parents continue to have several
children with the hope that some will survive to care for them in
their old age. When more children survive childhood, fertility
rates decline. Thus, one of the keys to reducing population growth
is increasing food security for children. Other keys include
reducing maternal mortality, increasing access to a full range of
reproductive health services including modern means of family
planning, increasing educational and literacy levels, and removing
various cultural and legal barriers that constrain the choices of
women and girl children.
[91] A third question raised by the sufficiency norm has to do with
the dangers GM crops might pose to human health. Does Kenya have
adequate policies and institutions in place to test GM crops and
protect the health of its citizens? The short answer to this
question is no. While the nation does have a rather substantial set
of biosafety regulations, government officials have not developed
similar public health regulations. One of the reasons for this is
because Kenya is still in the research stage and does not yet have
any GM crops growing in its fields. Thus, regulations have not yet
been developed because there are no GM food products available for
consumers. Nevertheless, even when products like GM sweet potatoes
or maize do become available, it is likely that Kenya may still not
develop highly restrictive public health regulations. This is
because the Ministry of Health faces what it perceives to be much
more immediate threats to public health from large-scale outbreaks
of malaria, polio, and HIV-AIDS. The potential allergenicity of GM
crops pales in comparison to the real devastation wrought by these
diseases. In addition, it is likely that officials will continue to
focus on more mundane problems that contaminate food products like
inadequate refrigeration or the unsanitary storage and preparation
of food. 62In
the end, people who are hungry tend to assess food safety risks
differently from those who are well fed. Hassan Adamu, Minister of
Agriculture in Nigeria, summarizes this position well in the
following excerpt from an op-ed piece published in The Washington
We do not want to be denied this technology [agricultural
biotechnology] because of a misguided notion that we do not
understand the dangers and future consequences. We
understandβ¦. that they
have the right to impose their values on us. The harsh reality is
that, without the help of agricultural biotechnology, many will not
live.63
[92] Despite Adamu's passionate plea, other leaders in Africa are
not as supportive of genetically modified crops. During the food
emergency that brought over 30 million people in sub-Saharan Africa
to the brink of starvation in 2002, President Levy Mwanawasa of
Zambia rejected a shipment of genetically modified food aid
furnished by the U.N. World Food Programme. Drawing on a report
produced by a team of Zambian scientists, and appealing to the
precautionaryprinciple, Mwanawasa said, "We will rather starve than
give something toxic [to our citizens.]"64 In addition to concerns
about the impact that GM food may have on human health, Mwanawasa
also expressed concern that the GM maize might contaminate Zambia's
local maize production in the future. Given Josephine's ardent
support for agricultural biotechnology in the case, it is important
to note that not all Africans share her confidence about the
benefits of GM crops.
[93] Sustainability. If, however, Kenyans downplay the dangers
posed to human beings by GM crops, how likely is it that the nation
will develop policies and regulatory bodies to address biosafety
and protect the environment?
[94] In fact, Kenya does have serious biosafety policies on the
books. Prompted by the work that Florence Wambugu did on GM sweet
potatoes in collaboration with Monsanto in the early 1990s, these
policies were developed with substantial financial assistance
furnished by the government of the Netherlands, the World Bank, the
U.S. Agency for International Development, and the United Nations
Environment Programme. The Regulations and Guidelines for Biosafety
in Biotechnology in Kenya establish laboratory standards and other
containment safeguards for the handling of genetically modified
organisms. In addition, the regulatory document applies more
rigorous biosafety standards to GM crops than it does to crops that
have not been genetically modified. In general, Kenya's extensive
regulations reflect a very cautious approach to GM
products.65
[95] The problem, however, is that although Kenya has a strong
biosafety policy on paper, the administrative means to implement
and enforce the policy are weak. The National Biosafety Committee
(NBC) was established in 1996 to govern the importation, testing,
and commercial release of genetically modified organisms, but
limited resources have hampered its effectiveness. In 2001, the NBC
employed only one full-time staff person and had to borrow funds to
do its work from Kenya's National Council for Science and
Technology.66
One of the consequences of this inadequate regulatory capacity has
been a delay in conducting field tests on Wambugu's GM sweet
potatoes. Clearly much progress needs to be achieved on this front
before such tests take place on varieties of maize that have been
genetically modified to be insect- or herbicide-resistant. It is
important to note, however, that KARI and CIMMYT are both well
aware of the biosafety dangers related to the development of these
GM crops and are engaged in studies todetermine, for example, the
appropriate size and placement of refuges for Bt varieties of
maize.67
Because much of KARI's work is supported by grants from foreign
donors, necessary biosafety research will be conducted and made
available to the NBC. The problem is that the NBC currently lacks
the resources to make timely decisions after it receives the
data.
[96] Another concern in the case has to do with the ecological
consequences of industrial agriculture. Karen disagrees with Tom's
glowing account of the Green Revolution. While it produced food to
feed more than two billion people during the latter half of the
20th century, it did so only by exacting a heavy ecological
toll.68 It also
had a major impact on the distribution of wealth and income in
developing nations. As a result, Karen is concerned about Tom's
view that GM crops could have a tremendous impact on increasing
food supply in sub-Saharan Africa. Karen fears that GM crops in
Kenya may open the floodgates to industrial agriculture and create
more problems than it solves.
[97] The question, however, is whether this is likely to happen.
With the significant poverty and the small landholdings of the over
70 percent of Kenyans who are subsistence farmers, it is hard to
see how the ecologically damaging practices of the Green Revolution
could have a significant impact in the near future. The cost of
fertilizers, herbicides, or irrigation put these practices out of
reach for most farmers in Kenya. If anything, most of the
ecological degradation of Kenya's agricultural land is due to
intensive cropping and stressed soils. Yield increases from GM
crops might relieve some of this pressure, although much relief is
not likely since food production needs to increase in order to meet
demand.
[98] This raises a third question related to the sustainability
norm. Can organic farming methods achieve the same results as GM
crops? Certainly Kelly believes that this is the case, and there is
some research to support her view. On the Striga front, some
farmers in East Africa have suppressed the weed by planting
leguminous tree crops during the dry season from February to April.
Since Striga is most voracious in fields that have been
consistently planted in maize and thus have depleted soil, the
nitrogen-fixing trees help to replenish the soil in their brief
three months of life before they are pulled up prior to maize
planting. Farmers report reducing Striga infestations by over 90
percent with this method of weed control. A bonus is that
theuprooted, young trees provide a nutritious feed for those
farmers who also have some livestock.69
[99] A similar organic strategy has been employed in Kenya to
combat stem-borers. In this "push-pull" approach, silver leaf
desmodium and molasses grass are grown amidst the maize. These
plants have properties that repel stem-borers toward the edges of
the field where other plants like Napier grass and Sudan grass
attract the bugs and then trap their larvae in sticky substances
produced by the plants. When this method is employed, farmers have
been able to reduce losses to stemborers from 40 percent to less
than 5 percent. In addition, silver leaf desmodium helps to combat
Striga infestation, thus further raising yields.70
[100] Results like these indicate that agroecological methods
associated with organic farming may offer a less expensive and more
sustainable approach to insect and pest control than those achieved
through the expensive development of GM crops and the purchase of
their seed. Agroecology utilizes ecological principles to design
and manage sustainable and resource-conserving agricultural
systems. It draws upon indigenous knowledge and resources to
develop farming strategies that rely on biodiversity and the
synergy among crops, animals, and soils.71 More research in this area
is definitely justified.
[101] It is not clear, however, that agroecological farming
techniques and GM crops need to be viewed as opposing or exclusive
alternatives. Some researchers argue that these organic techniques
are not as effective in different ecological niches in East Africa.
Nor, in some areas, do farmers feel they have the luxury to fallow
their fields during the dry season.72 In these contexts, GM crops
might be able to raise yields where they are desperately needed. It
is also not likely that the seeds for these crops will be very
expensive since they are being produced through research in the
public and non-profit sectors. Still, it is certainly the case that
more serious ecological problems could result from the use of GM
crops in Kenya, and even though donors are currently footing the
bill for most of the research, agricultural biotechnology requires
a more substantial financial investment than agroecological
approaches.
[102] Participation. The source of funding for GM crop research in
Kenya raises an important question related to the participation
norm. Are biotechnology and GM crops being forced on the people of
Kenya?
[103] Given the history of colonialism in Africa, this question is
not unreasonable, but in this case it would not appear warranted.
Kenya's Agricultural Research Institute (KARI) began experimenting
with tissue culture and micropropagation in the 1980s. A few years
later, one of KARI's researchers, Florence Wambugu, was awarded a
three-year post-doctoral fellowship by the U.S. Agency for
International Development to study how sweet potatoes could be
genetically modified to be resistant to feathery mottle virus. Even
though this research was conducted in Monsanto's laboratory
facilities, and the company provided substantial assistance to the
project long after Wambugu's fellowship ended, it is clearly the
case that this groundbreaking work in GM crop research was
initiated by a Kenyan to benefit the people of her
country.73 In
addition, the funding for GM crop research in Kenya has come almost
entirely through public sector institutions rather than private
corporate sources. Even the Novartis funds that support the
insect-resistant maize project are being provided from a foundation
for sustainable development that is legally and financially
separate from the Novartis Corporation. Thus, it does not appear
that transnational biotechnology corporations are manipulating
Kenya, but it is true that the country's openness to biotechnology
and GM crops may open doors to the sale of privately-developed GM
products in the future.
[104] Josephine, however, might turn the colonialism argument
around and apply it to Greenpeace's campaign to ban GM crops.
Specifically, Greenpeace International urges people around the
world to "write to your local and national politicians demanding
that your government ban the growing of genetically engineered
crops in your country."74 Though Josephine does not
pose the question, is this well-intentioned effort to protect the
environment and the health of human beings a form of paternalism or
neocolonialism? Does the Greenpeace campaign exert undue pressure
on the people of Kenya and perhaps provoke a lack of confidence in
Kenyan authorities, or does it merely urge Kenyans to use the
democratic powers at their disposal to express their concerns? It
is not clear how these questions should be answered, but the
participation norm requires reflection about them.
[105] The concern about paternalism also arises with regard to a
set of questions about appropriate technology. Are GM crops an
"appropriate" agricultural technology for the people of Kenya?
Genetic engineering and other forms of agricultural biotechnology
are very sophisticated and expensive. Is such a "high-tech"
approach to agriculture "appropriate" given the status of a
developing nation like Kenya? Is it realistic to expect that
undereducated and impoverished subsistence farmers will have the
capacities and the resources to properly manage GM crops, for
example through the appropriate use of refuges?
[106] In the case, Josephine responds aggressively to concerns
like these when she overhears Terra's conversation with Tom. She
asserts that Kenya will do what it takes to educate farmers about
the proper use of GM crops, and it is true that KARI is designing
farmer-training strategies as a part of the insect-resistant maize
project.75
Compared to other countries in sub-Saharan Africa, Kenya has very
high rates of adult literacy. In 2000, 89 percent of men and 76
percent of women were literate. At the same time, only 26 percent
of boys and 22 percent of girls are enrolled in secondary
education.76
Thus, while literacy is high, the level of education is low. The
hunger and poverty among many Kenyans, however, may be the most
significant impediment to the responsible use of GM crops. In a
situation where hunger is on the rise, how likely is it that
subsistence farmers will plant 20 percent of their fields in non-Bt
maize if they see that the Bt varieties are producing substantially
higher yields?
[107] This is a fair question. The norm of participation supports
people making decisions that affect their lives, but in this case
the immediate threat of hunger and malnutrition may limit the range
of their choices. At the same time, GM crops have the potential to
significantly reduce the amount of time that women and children
spend weeding, picking bugs off of plants, and scaring birds away.
Organic farming methods would require even larger investments of
time. This is time children could use to attend more school or that
women could use to increase their literacy or to engage in other
activities that might increase family income and confer a slightly
greater degree of security and independence. Aspects of the
participation norm cut both ways.
[108] Solidarity. Among other things, the ecojustice norm of
solidarity is concerned about the equitable distribution of the
burdens and benefits associated with GM crops. If problems emerge
in Kenya, who will bear the costs? If GM crops are finally approved
for planting, who will receive most of the benefits?
[109] Thus far, critics argue that the benefits of GM crops in
developed nations have accrued only to biotech corporations through
higher sales and to large-scale farmers through lower production
costs. Moreover, critics claim that the dangers GM crops pose to
human health and biosafety are dumped on consumers who do not fully
understand the risks associated with GM crops and the food products
that are derived from them. It is not clear that the same could be
said for the production of GM crops in Kenya where these crops are
being developed through partnerships in the non-profit and public
sectors. Researchers expect to make these products available at
little cost to farmers and few corporations will earn much money
off the sale of these seeds. Thus, the benefits from GM crops
should accrue to a larger percentage of people in Kenya because 70
percent of the population is engaged in subsistence agriculture.
Like developed nations, however, food safety problems could affect
all consumers and a case could be made that this would be more
severe in a nation like Kenya where it would be very difficult to
adequately label GM crop products that often move directly from the
field to the dinner table.
[110] Another aspect of solidarity involves supporting others in
their struggles. Josephine does not explicitly appeal to this norm
in the case, but some members of the Hunger Concerns group are
probably wondering whether they should just support Josephine's
proposal as a way to show respect to her and to the
self-determination of the Kenyan people. There is much to commend
this stance and, ultimately, it might be ethically preferable. One
of the dangers, however, is that Josephine's colleagues may squelch
their moral qualms and simply "pass the buck" ethically to the
Kenyans. Karen seems close to making this decision, despite her
serious social, ecological, and theological concerns about GM
crops. Friendship requires support and respect, but it also thrives
on honesty.
Conclusion
[111] Tom and Karen face a difficult choice, as do the other
members of the Hunger Concerns group. Next week they will have to
decide if the group should join the Greenpeace campaign to ban GM
crops or whether it wants to submit an article for the campus
newspaper supporting the responsible use of GM crops to bolster
food security in Kenya. While convenient, skipping the meeting
would just dodge the ethical issues at stake. As students consider
these alternatives and others, the goods associated with solidarity
need to be put into dialogue with the harms to ecological
sustainability and human health that could result from the
development of GM crops in Kenya. Similarly, these potential harms
also need to be weighed against the real harms that are the result
of an insufficient food supply. The problem of hunger in
sub-Saharan Africa is only getting worse, not better.
Β© Orbis Books
Printed by permission.
Β© December 2003
Journal of Lutheran Ethics (JLE)
Volume 3, Issue 12
1 Florence Wambugu, Modifying Africa: How biotechnology
can benefit the poor and hungry; a case study from Kenya (Nairobi,
Kenya, 2001), pp. 22-44.
2 J. DeVries and G. Toenniessen, Securing the Harvest:
Biotechnology, Breeding and Seed Systems for African Crops (New
York: CABI Publishing, 2001), p. 103.
3 Ibid., p. 101.
4 Susan Mabonga, "Centre finds new way to curb weed,"
Biosafety News, (Nairobi), No. 28, January 2002, pp. 1, 3.
5 Klaus M. Leisinger, et al., Six Billion and Counting:
Population and Food Security in the 21st Century (Washington, DC:
International Food Policy Research Institute, 2002), pp. 4-6. I am
indebted to Todd Benson, an old friend and staff member at the
International Food Policy Research Institute, for better
understanding issues related to food security in sub-Saharan
Africa.
6 Ibid, p. 57.
7 Per Pinstrup-Andersen and Ebbe SchiΓΈler, Seeds of
Contention: World Hunger and the Global Controversy over GM Crops
(Baltimore: The Johns Hopkins University Press, 2001), p. 61.
8 Klaus M. Leisinger, et al., Six Billion and Counting, p.
8.
9 Ibid, p. x. Globally, the World Bank estimates that 1.3
billion people are trying to survive on $1 a day. Another two
billion people are trying to get by on only $2 a day. Half of the
world's population is trying to live on $2 a day or less.
10 J. DeVries and G. Toenniessen, Securing the Harvest:
Biotechnology, Breeding and Seed Systems for African Crops (New
York: CABI Publishing, 2001), pp. 30-31.
11 The World Bank Group, "Kenya at a Glance," accessed
on-line April 9, 2002:.
12 J. DeVries and G. Toenniessen, Securing the Harvest, p.
29. See also, Per Pinstrup-Andersen and Ebbe SchiΓΈler, Seeds
of Contention, pp. 59-67. I am indebted to Gary Toenniessen at the
Rockefeller Foundation for his wise counsel as I began to research
ethical implications of genetically modified crops in sub-Saharan
Africa.
13 Population Reference Bureau, 2001 World Population Data
Sheet, book edition (Washington, DC: Population Reference Bureau,
2001), pp. 3-4. I am indebted to Dick Hoehn at Bread for the World
Institute for helping me better understand the root causes of
hunger in sub-Saharan Africa.
14 Per Pinstrup-Andersen and Ebbe SchiΓΈler, Seeds
of Contention, pp. 106-107.
15 Ibid.
16 Population Reference Bureau, 2001 World Population Data
Sheet, p. 2.
17 J. DeVries and G. Toenniessen, Securing the Harvest, p.
33.
18 Ibid, p. 7, 21.
19 Food and Agriculture Organization, Statement on
Biotechnology, accessed on-line April 9, 2002:.
20 United Nations Environment Programme, Secretariat of
the Convention on Biological Diversity, accessed on-line April 9,
2002:.
21 Per Pinstrup-Andersen and Ebbe SchiΓΈler, Seeds
of Contention, p. 33.
22 J. DeVries and G. Toenniessen, Securing the Harvest,
pp. 59-66.
23 Ibid, p. 67.
24 International Maize and Wheat and Improvement Center
and The Kenya Agricultural Research Institute, Annual Report 2000:
Insect Resistant Maize for Africa (IRMA) Project,, IRMA Project
Document, No. 4, September 2001, pp. 1-12.
25 J. DeVries and G. Toenniessen, Securing the Harvest, p.
65.
26 Nicholas Wade, "Experts Say They Have Key to Rice
Genes," The New York Times, accessed on-line April 5, 2002: (registration
required).
27 Daniel Charles, Lords of the Harvest: Biotech, Big
Money, and the Future of Food (Cambridge, MA: Perseus Publishing,
2001), p. 10
28 Ibid, p. 139.
29 Per Pinstrup-Andersen and Marc J. Cohen, "Rich and Poor
Country Perspectives on Biotechnology," in The Future of Food:
Biotechnology Markets and Policies in an International Setting, P.
Pardey, ed., (Washington, DC: International Food Policy Research
Institute, 2001), pp. 34-35. See also, Bill Lambrecht, Dinner at
the New Gene CafΓ©: How Genetic Engineering is Changing What
We Eat, How We Live, and the Global Politics of Food (New York: St,
Martin's Press, 2001), p. 7.
30 Philip Brasher, "American Farmers Planting More Biotech
Crops This Year Despite International Resistance," accessed on line
March 29, 2002:.
31 Robert L. Paarlberg, The Politics of Precaution:
Genetically Modified Crops in Developing Countries (Baltimore: The
Johns Hopkins University Press, 2001), p. 3.
32 Per Pinstrup-Andersen and Marc J. Cohen, "Rich and Poor
Country Perspectives on Biotechnology," in The Future of Food, p.
34.
33 Robert L. Paarlberg, The Politics of Precaution, p.
3.
34 J. DeVries and G. Toenniessen, Securing the Harvest, p.
68. I am indebted to Jill Montgomery, director of Technology
Cooperation at Monsanto, for better understanding how Monsanto has
assisted biotechnology research and subsistence agriculture in
Kenya.
35 International Maize and Wheat and Improvement Center
and The Kenya Agricultural Research Institute, Annual Report 2000:
Insect Resistant Maize for Africa (IRMA) Project, pp. 1-12.
36 Susan Mabonga, "Centre finds new way to curb weed,"
Biosafety News, (Nairobi), No. 28, January 2002, pgs. 1, 3.
37 Debbie Weiss, "New Witchweed-fighting method, developed
by CIMMYT and Weismann Institute, to become public in July," Today
in AgBioView, July 10, 2002, accessed on line July 12, 2002:.
38 Miguel A. Altieri, Genetic Engineering in Agriculture:
The Myths, Environmental Risks, and Alternatives (Oakland, CA: Food
First/Institute for Food and Development Policy, 2001), pp. 16-17.
Concerns about the dangers GM crops could pose to human and
ecological health lead many critics to invoke the "precautionary
principle" in their arguments. For more information about this
important concept, see sections of the case and commentary for the
preceding case, "Chlorine Sunrise?"
39 Daniel Charles, Lords of the Harvest, pp. 303-304.
40 Bill Lambrecht, Dinner at the New Gene CafΓ©, pp.
46-47.
41 Per Pinstrup-Andersen and Ebbe SchiΓΈler, Seeds
of Contention, p. 90.
42 Environmental News Service, "ProdiGene Fined for
Biotechnology Blunders," accessed on-line December 10, 2002:.
43 Miguel A. Altieri, Genetic Engineering in Agriculture,
p. 19.
44 Per Pinstrup-Andersen and Ebbe SchiΓΈler, Seeds
of Contention, p. 140-141.
45 Miguel A. Altieri, Genetic Engineering in Agriculture,
p. 19.
46 Ibid, p. 20.
47 Per Pinstrup-Andersen and Ebbe SchiΓΈler, Seeds
of Contention, p. 44-45.
48 Miguel A. Altieri, i>Genetic Engineering in
Agriculture, pp. 22-23.
49 See Per Pinstrup-Andersen and Ebbe SchiΓΈler,
Seeds of Contention, p. 45-46 and Miguel A. Altieri, Genetic
Engineering in Agriculture, pp. 26-29.
50 See Per Pinstrup-Andersen and Ebbe SchiΓΈler,
Seeds of Contention, p. 47-49 and Miguel A. Altieri, Genetic
Engineering in Agriculture, pp. 29-31. See also Daniel Charles,
Lords of the Harvest, pp. 247-248; Bill Lambrecht, Dinner at the
New Gene CafΓ©, pp. 78-82; and Alan McHughen, Pandora's
Picnic Basket: The Potential and Hazards of Genetically Modified
Foods (New York: Oxford University Press, 2000), p. 190.
51 See Per Pinstrup-Andersen and Ebbe SchiΓΈler,
Seeds of Contention, p. 49-50 and Miguel A. Altieri, Genetic
Engineering in Agriculture, pp. 23-25. Controversy erupted in 2002
after the prestigious scientific journal, Nature, published a study
by scientists claiming that gene flow had occurred between GM maize
and indigenous varieties of maize in Mexico. Since Mexico is the
birthplace of maize, this study ignited alarm and produced a
backlash against GM crops. In the spring of 2002, however, Nature
announced that it should not have published the study because the
study's methodology was flawed. See Carol Kaesuk Yoon, "Journal
Raises Doubts on Biotech Study," The New York Times, April 5, 2002,
accessed on-line April 5, 2002: (registration
required).05CORN.html
52 Miguel A. Altieri, Genetic Engineering in Agriculture,
p. 4.
53 Bill Lambrecht, Dinner at the New Gene CafΓ©, pp.
113-123.
54 Opposition reached a fevered pitch when the Delta and
Pine Land Company announced that they had developed a "technology
protection system" that would render seeds sterile. The company
pointed out that this would end concerns about the creation of
superweeds through undesired gene flow, but opponents dubbed the
technology as "the terminator" and viewed it as a diabolical means
to make farmers entirely dependent on seed companies for their most
valuable input, seed. When Monsanto considered purchasing Delta and
Pine Land in 1999, Monsanto bowed to public pressure and declared
that it would not market the new seed technology if it acquired the
company. In the end, it did not. See Bill Lambrecht, Dinner at the
New Gene CafΓ©, pp. 113-123.
55 Robert L. Paarlberg, The Politics of Precaution, pp.
16-17.
56 Per Pinstrup-Andersen and Ebbe SchiΓΈler, Seeds
of Contention, pp. 123-126.
57 Ibid, pp. 33-34.
58 Richard Manning, Food's Frontier: The Next Green
Revolution (New York: North Point Press, 2000), p. 195.
59 Ibid, 194. See also, Per Pinstrup-Andersen and Ebbe
SchiΓΈler, Seeds of Contention, pp. 80-81.
60 See Douglas John Hall, Imaging God: Dominion as
Stewardship (Grand Rapids: Eerdmans Publishing Company, 1986), pp.
89-116; and The Steward: A Biblical Symbol Come of Age (Grand
Rapids: Eerdmans Publishing Company, 1990).
61 Per Pinstrup-Andersen and Ebbe SchiΓΈler, Seeds
of Contention, pp. 73-75.
62 Robert L. Paarlberg, The Politics of Precaution, pp.
58-59.
63 Hassan Adamu, "We'll feed our people as we see fit,"
The Washington Post, (September 11, 2000), p. A23; cited by Per
Pinstrup-Andersen and Marc J. Cohen, "Rich and Poor Country
Perspectives on Biotechnology," in The Future of Food, p. 20.
64 James Lamont, "U.N. Withdraws Maize Food Aid From
Zambia," Financial Times (Johannesburg), December 10, 2002.
Reprinted in Today in AgBioView, accessed on-line December 11,
2002:.
65 Robert L. Paarlberg, The Politics of Precaution, pp.
50-54.
66 Ibid.
67 International Maize and Wheat and Improvement Center
and The Kenya Agricultural Research Institute, Annual Report 2000:
Insect Resistant Maize for Africa (IRMA) Project, pp. 15-16.
68 For a brief summary, see a section devoted to the rise
of dysfunctional farming in Brian Halweil, "Farming in the Public
Interest," in State of the World 2002 (New York: W.W. Norton &
Co., 2002), pp. 53-57.
69 Brian Halweil, "Biotech, African Corn, and the Vampire
Weed," WorldWatch, (September/October 2001), Vol. 14, No. 5, pp.
28-29.
70 Ibid., p. 29.
71 Miguel A. Altieri, Genetic Engineering in Agriculture,
pp. 35-47.
72 These observations are based on remarks made by
researchers from sub-Saharan Africa, Europe, and the United States
in response to a presentation by Brian Halweil at a conference I
attended in Washington, DC on March 6, 2002. The conference was
sponsored by Bread for the World Institute and was titled,
Agricultural Biotechnology: Can it Help Reduce Hunger in
Africa?
73 Florence Wambugu, Modifying Africa: How biotechnology
can benefit the poor and hungry; a case study from Kenya, (Nairobi,
Kenya, 2001), pp. 16-17; 45-54.
74 Greenpeace International.. Accessed on-line:
April 19, 2002.
75 International Maize and Wheat and Improvement Center
and The Kenya Agricultural Research Institute, Annual Report 2000:
Insect Resistant Maize for Africa (IRMA) Project, pp. 23-33.
76 Population Reference Bureau, "Country Fact Sheet:
Kenya," accessed on-line April 19, 2002: | http://www.elca.org/What-We-Believe/Social-Issues/Journal-of-Lutheran-Ethics/Issues/December-2003/Harvesting-Controversy-Genetic-Engineering-and-Food-Security-in-SubSaharan-Africa.aspx | CC-MAIN-2013-20 | en | refinedweb |
16 July 2009 15:44 [Source: ICIS news]
(Recasts, adding detail in headline and lead)
LONDON (ICIS news)--INEOSβ 320,000 tonne/year polyethylene (PE) plant at ?xml:namespace>
βThe plant went down some time over the weekend [11/12 July], as it was well into its high density PE (HDPE) campaign,β said the source. βWe expect it to restart on Monday [20 July].β
The plant is a linear low density PE (LLDPE)/HDPE swing unit.
INEOS declared force majeure on one of its HDPE injection grades.
βThis is just one particular grade of HDPE injection of many that we produce,β said the source.
PE availability has tightened considerably in
Prices in July increased by β¬100/tonne ($141/tonne), leaving gross low density PE (LDPE) levels at β¬1,000/tonne FD (free delivered) NWE (northwest
PE producers in
($1 = β¬0.71). | http://www.icis.com/Articles/2009/07/16/9233138/ineos-pe-down-at-grangemouth-uk-after-unexpected-outage.html | CC-MAIN-2013-20 | en | refinedweb |
20 October 2009 17:26 [Source: ICIS news]
By Nigel Davis
?xml:namespace>
CEO Ellen Kullman on Tuesday described βa developing recovery that is shaped different by market and geographyβ.
Not surprisingly, DuPontβs
Central
But the picture is shifting slightly and the outlook is certainly more positive than three months ago.
There are signs of restocking in the automobile-related product chains that are so important to the company. Kullman said in a conference call that the third quarter seemed to represent true demand for DuPontβs industrial polymers and performance elastomers. The sign must be welcome.
All in all, the chemicals giant is seeing its markets stabilise and some early indications of an upturn.
Titanium dioxide, an early cycle indicator, is doing well and DuPont is almost sold out. Other important products for the company, however, are still feeling the squeeze. It could be months before they might be expected to recover.
The company continues to do well in driving costs down and is on target to save $1bn (β¬670m) in fixed costs this year.
Kullman said $750m of these costs savings can be retained over the longer term. There is a clear commitment to deliver on promises.
What is also important is that DuPontβs product development engine continues to fire on all cylinders.
The company launched 323 new products in the third quarter, bringing the year-to-date total to 1,107. Thatβs a 50% higher launch rate than last year.
The new products help drive growth in the continued weak market environment and will help lay the foundations for faster growth.
On the demand side, then, there is not a great deal to get excited about. But given the unclear global economic picture, that is hardly surprising.
DuPont is confident enough, nevertheless, to forecast that its earnings per share this year will be at the top of an earlier stated range. A solid foundation has been laid in 2009. The company is holding on to product prices.
It is the degree to which savings have been made and the research engine delivered that have contributed immensely to confidence this year. Yet the market has begun to more forcefully respond.
Erratic as the recovery may be, it appears as if there are more widespread opportunities to grasp.
($1 = β¬0.67). | http://www.icis.com/Articles/2009/10/20/9256404/insight-stronger-signs-of-market-growth.html | CC-MAIN-2013-20 | en | refinedweb |
LLVM API Documentation
#include <LibCallSemantics.h>
LibCallInfo - Abstract interface to query about library call information. Instances of this class return known information about some set of libcalls.
Definition at line 127 of file LibCallSemantics.h.
Definition at line 133 of file LibCallSemantics.h.
Definition at line 27 of file LibCallSemantics.cpp.
getFunctionInfo - Return the LibCallFunctionInfo object corresponding to the specified function if we have it. If not, return null.
If this is the first time we are querying for this info, lazily construct the StringMap to index it.
Definition at line 44 of file LibCallSemantics.cpp.
References getFunctionInfoArray(), getMap(), llvm::Value::getName(), and llvm::StringMap< ValueTy, AllocatorTy >::lookup().
Referenced by llvm::LibCallAliasAnalysis::getModRefInfo().
getFunctionInfoArray - Return an array of descriptors that describe the set of libcalls represented by this LibCallInfo object. This array is terminated by an entry with a NULL name.
Referenced by getFunctionInfo().
getLocationInfo - Return information about the specified LocationID.
Definition at line 31 of file LibCallSemantics.cpp.
getLocationInfo - Return descriptors for the locations referenced by this set of libcalls.
Definition at line 155 of file LibCallSemantics.h. | http://llvm.org/docs/doxygen/html/classllvm_1_1LibCallInfo.html | CC-MAIN-2013-20 | en | refinedweb |
Spring Integration's JPA (Java Persistence API) module provides components for performing various database operations using JPA. The following components are provided:
Updating Outbound Gateway
Retrieving Outbound Gateway
These components can be used to perform select, create, update and delete operations on the targeted databases by sending/receiving messages to them.
The JPA Inbound Channel Adapter lets you poll and retrieve (select) data from the database using JPA whereas the JPA Outbound Channel Adapter lets you create, update and delete entities.
Outbound Gateways for JPA can be used to persist entities to the database, yet allowing you to continue with the flow and execute further components downstream. Similarly, you can use an Outbound Gateway to retrieve entities from the database.
For example, you may use the Outbound Gateway, which receives a Message with a user Id as payload on its request channel, to query the database and retrieve the User entity and pass it downstream for further processing.
Recognizing these semantic differences, Spring Integration provides 2 separate JPA Outbound Gateways:
Retrieving Outbound Gateway
Updating Outbound Gateway
Functionality
All JPA components perform their respective JPA operations by using either one of the following:
Entity classes
Java Persistence Query Language (JPQL) for update, select and delete (inserts are not supported by JPQL)
Native Query
Named Query
In the following sections we will describe each of these components in more detail.
The Spring Integration JPA support has been tested using the following persistence providers:
Hibernate
OpenJPA
EclipseLink
When using a persistence provider, please ensure that the provider is compatible with JPA 2.0.
Each of the provided components will use the
o.s.i.jpa.core.JpaExecutor
class which in turn will use an implementation of the
o.s.i.jpa.core.JpaOperations
interface.
JpaOperations operates like a
typical Data Access Object (DAO) and provides methods such as
find,
persist,
executeUpdate etc. For most use cases the provided
default implementation
o.s.i.jpa.core.DefaultJpaOperations
should be sufficient. Nevertheless, you have the option to
optionally specify your own implementation in case you require custom
behavior.
For initializing a
JpaExecutor
you have to use one of 3 available constructors that accept one of:
EntityManagerFactory
EntityManager or
JpaOperations
Java Configuration Example
The following example of a JPA Retrieving Outbound Gateway is configured purely through Java. In typical usage scenarios you will most likely prefer the XML Namespace Support described further below. However, the example illustrates how the classes are wired up. Understanding the inner workings can also be very helpful for debugging or customizing the individual JPA components.
First, we instantiate a
JpaExecutor using an
EntityManager as constructor argument.
The
JpaExecutor is then in return used as
constructor argument for the
o.s.i.jpa.outbound.JpaOutboundGateway
and the
JpaOutboundGateway will be passed as constructor
argument into the
EventDrivenConsumer.
<bean id="jpaExecutor" class="o.s.i.jpa.core.JpaExecutor"> <constructor-arg <property name="entityClass" value="o.s.i.jpa.test.entity.StudentDomain"/> <property name="jpaQuery" value="select s from Student s where s.id = :id"/> <property name="expectSingleResult" value="true"/> <property name="jpaParameters" > <util:list> <bean class="org.springframework.integration.jpa.support.JpaParameter"> <property name="name" value="id"/> <property name="expression" value="payload"/> </bean> </util:list> </property> </bean> <bean id="jpaOutboundGateway" class="o.s.i.jpa.outbound.JpaOutboundGateway"> <constructor-arg <property name="gatewayType" value="RETRIEVING"/> <property name="outputChannel" ref="studentReplyChannel"/> </bean> <bean id="getStudentEndpoint" class="org.springframework.integration.endpoint.EventDrivenConsumer"> <constructor-arg <constructor-arg </bean>
When using XML namespace support, the underlying parser classes will instantiate the relevant Java classes for you. Thus, you typically don't have to deal with the inner workings of the JPA adapter. This section will document the XML Namespace Support provided by the Spring Integration and will show you how to use the XML Namespace Support to configure the Jpa components.
Certain configuration parameters are shared amongst all JPA components and are described below:
auto-startup
Lifecycle attribute signaling if this component should
be started during Application Context startup.
Defaults to
true.
Optional.
id
Identifies the underlying Spring bean definition, which
is an instance of either
EventDrivenConsumer
or
PollingConsumer.
Optional.
entity-manager-factory
The reference to the JPA Entity Manager Factory
that will be used by the adapter to create the
EntityManager.
Either this attribute or the entity-manager attribute
or the jpa-operations attribute must be provided.
entity-manager
The reference to the JPA Entity Manager that will be used by the component. Either this attribute or the enity-manager-factory attribute or the jpa-operations attribute must be provided.
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean"> <property name="entityManagerFactory" ref="entityManagerFactoryBean" /> </bean>
jpa-operations
Reference to a bean implementing the
JpaOperations interface. In rare cases
it might be advisable to provide your own implementation
of the
JpaOperations interface, instead
of relying on the default implementation
org.springframework.integration.jpa.core.DefaultJpaOperations.
As
JpaOperations wraps the necessary
datasource; the JPA Entity Manager or JPA Entity Manager Factory
must not be provided, if the jpa-operations
attribute is used.
entity-class
The fully qualified name of the entity class. The exact semantics of this attribute vary, depending on whether we are performing a persist/update operation or whether we are retrieving objects from the database.
When retrieving data, you can specify the entity-class attribute to indicate that you would like to retrieve objects of this type from the database. In that case you must not define any of the query attributes ( jpa-query, native-query or named-query )
When persisting data, the entity-class attribute will indicate the type of object to persist. If not specified (for persist operations) the entity class will be automatically retrieved from the Message's payload.
jpa-query
Defines the JPA query (Java Persistence Query Language) to be used.
native-query
Defines the native SQL query to be used.
named-query
This attribute refers to a named query. A named query can either be defined in Native SQL or JPAQL but the underlying JPA persistence provider handles that distinction internally.
For providing parameters, the parameter XML sub-element can be used. It provides a mechanism to provide parameters for the queries that are either based on the Java Persistence Query Language (JPQL) or native SQL queries. Parameters can also be provided for Named Queries.
Expression based Parameters
<int-jpa:parameter
Value based Parameters
<int-jpa:parameter
Positional Parameters
<int-jpa:parameter <int-jpa:parameter
All JPA operations like Insert, Update and Delete require a transaction to be active whenever they are performed. For Inbound Channel Adapters there is nothing special to be done, it is similar to the way we configure transaction managers with pollers used with other inbound channel adapters.The xml snippet below shows a sample where a transaction manager is configured with the poller used with an Inbound Channel Adapter.
<int-jpa:inbound-channel-adapter <int:poller <int:transactional </int:poller> </int-jpa:inbound-channel-adapter>
However, it may be necessary to specifically start a transaction when using an Outbound Channel Adapter/Gateway. If a DirectChannel is an input channel for the outbound adapter/gateway, and if transaction is active in the current thread of execution, the JPA operation will be performed in the same transaction context. We can also configure to execute this JPA operation in a new transaction as below.
<int-jpa:outbound-gateway <int-jpa:parameter <int-jpa:parameter <int-jpa:transactional </int-jpa:outbound-gateway>
As we can see above, the transactional sub element of the outbound gateway/adapter will be used to specify the transaction attributes. It is optional to define this child element if you have DirectChannel as an input channel to the adapter and you want the adapter to execute the operations in the same transaction context as the caller. If, however, you are using an ExecutorChannel, it is required to have the transactional sub element as the invoking client's transaction context is not propagated.
An Inbound Channel Adapter is used to execute a select query over the
database using JPA QL and return the result. The message payload will be either a single
entity or a
List of entities. Below is a sample xml snippet that shows
a sample usage of inbound-channel-adapter.
<int-jpa:inbound-channel-adapter
<int:poller <int:transactional </int:poller> </int-jpa:inbound-channel-adapter><int:poller <int:transactional </int:poller> </int-jpa:inbound-channel-adapter>
<int-jpa:inbound-channel-adapter <int:poller </int-jpa:inbound-channel-adapter>> <int:poller </int-jpa:inbound-channel-adapter>
The JPA Outbound channel adapter allows you to accept messages over a request channel. The payload can either be used as the entity to be persisted, or used along with the headers in parameter expressions for a defined JPQL query to be executed. In the following sub sections we shall see what those possible ways of performing these operations are.
The XML snippet below shows how we can use the Outbound Channel Adapter to persist an entity to the database.
<int-jpa:outbound-channel-adapter
As we can see above these 4 attributes of the outbound-channel-adapter are all we need to configure it to accept entities over the input channel and process them to PERSIST,MERGE or DELETE it from the underlying data source.
We have seen in the above sub section how to perform a PERSIST action using an entity We will now see how to use the outbound channel adapter which uses JPA QL (Java Persistence API Query Language)
<int-jpa:outbound-channel-adapter
<int-jpa:parameter<int-jpa:parameter
<int-jpa:parameter </int-jpa:outbound-channel-adapter><int-jpa:parameter </int-jpa:outbound-channel-adapter>
The parameter sub element accepts an attribute name which corresponds to the named parameter specified in the provided JPA QL (point 2 in the above mentioned sample). The value of the parameter can either be static or can be derived using an expression. The static value and the expression to derive the value is specified using the value and the expression attributes respectively. These attributes are mutually exclusive.
If the value attribute is specified we can provide an optional
type attribute. The value of this attribute is the fully qualified name of the class
whose value is represented by the value attribute. By default
the type is assumed to be a
java.lang.String.
<int-jpa:outbound-channel-adapter ... > <int-jpa:parameter <int-jpa:parameter </int-jpa:outbound-channel-adapter>
As seen in the above snippet, it is perfectly valid to use multiple parameter sub elements within an outbound channel adapter
tag and derive some parameters using expressions and some with static value. However, care should
be taken not to specify the same parameter name multiple times, and, provide one parameter sub element for
each named parameter specified in the JPA query. For example, we are specifying two parameters
level and name where level attribute is a static value of type
java.lang.Integer, where as the name attribute is derived from the payload of the message
In this section we will see how to use native queries to perform the operations using JPA outbound channel adapter. Using native queries is similar to using JPA QL, except that the query specified here is a native database query. By choosing native queries we lose the database vendor independence which we get using JPA QL.
One of the things we can achieve using native queries is to perform database inserts, which is not possible using JPA QL (To perform inserts we send JPA entities to the channel adapter as we have seen earlier). Below is a small xml fragment that demonstrates the use of native query to insert values in a table. Please note that we have only mentioned the important attributes below. All other attributes like channel, entity-manager and the parameter sub element has the same semantics as when we use JPA QL.
<int-jpa:outbound-channel-adapter
We will now see how to use named queries after seeing using entity, JPA QL and native query in previous sub sections. Using named query is also very similar to using JPA QL or a native query, except that we specify a named query instead of a query. Before we go further and see the xml fragment for the declaration of the outbound-channel-adapter, we will see how named JPA named queries are defined.
In our case, if we have an entity called
Student, then we have the following in the class to define
two named queries selectStudent and updateStudent. Below is a way to define
named queries using annotations
@Entity @Table(name="Student") @NamedQueries({ @NamedQuery(name="selectStudent", query="select s from Student s where s.lastName = 'Last One'"), @NamedQuery(name="updateStudent", query="update Student s set s.lastName = :lastName, lastUpdated = :lastUpdated where s.id in (select max(a.id) from Student a)") }) public class Student { ...
You can alternatively use the orm.xml to define named queries as seen below
<entity-mappings ...> ... <named-query <query>select s from Student s where s.lastName = 'Last One'</query> </named-query> </entity-mappings>
Now that we have seen how we can define named queries using annotations or using orm.xml, we will now see a small xml fragment for defining an outbound-channel-adapter using named query
<int-jpa:outbound-channel-adapter
<int-jpa:outbound-channel-adapter <int:poller/> <int-jpa:transactional/>> <int:poller/> <int-jpa:transactional/>
> <int-jpa:parameter/>> <int-jpa:parameter/>
> </int-jpa:outbound-channel-adapter>> </int-jpa:outbound-channel-adapter>
The JPA Inbound Channel Adapter allows you to poll a database in order to retrieve one or more JPA entities and the retrieved data is consequently used to start a Spring Integration flow using the retrieved data as message payload.
Additionally, you may use JPA Outbound Channel Adapters at the end of your flow in order to persist data, essentially terminating the flow at the end of the persistence operation.
However, how can you execute JPA persistence operation in the middle of a flow? For example, you may have business data that you are processing in your Spring Integration message flow, that you would like to persist, yet you still need to execute other components further downstream. Or instead of polling the database using a poller, you rather have the need to execute JPQL queries and retrieve data actively which then is used to being processed in subsequent components within your flow.
This is where JPA Outbound Gateways come into play. They give you the ability to persist data as well as retrieving data. To facilitate these uses, Spring Integration provides two types of JPA Outbound Gateways:
Whenever the Outbound Gateway is used to perform an action that saves, updates or soley deletes some records in the database, you need to use an Updating Outbound Gateway gateway. If for example an entity is used to persist it, then a merged/persisted entity is returned as a result. In other cases the number of records affected (updated or deleted) is returned instead.
When retrieving (selecting) data from the database, we use a Retrieving Outbound Gateway. With a Retrieving Outbound Gateway gateway, we can use either JPQL, Named Queries (native or JPQL-based) or Native Queries (SQL) for selecting the data and retrieving the results.
An Updating Outbound Gateway is functionally very similar to an Outbound Channel Adapter, except that an Updating Outbound Gateway is used to send a result to the Gateway's reply channel after performing the given JPA operation.
A Retrieving Outbound Gateway is quite similar to an Inbound Channel Adapter.
This similarity was the main factor to use the central
JpaExecutor class to unify common functionality
as much as possible.
Common for all JPA Outbound Gateways and simlar to the outbound-channel-adapter, we can use
Entity classes
JPA Query Language (JPQL)
Native query
Named query
for performing various JPA operations. For configuration examples please see Section 18.6.4, βJPA Outbound Gateway Samplesβ.
JPA Outbound Gateways always have access to the Spring Integration Message as input. As such the following parameters are available:
parameter-source-factory
An instance of
o.s.i.jpa.support.parametersource.ParameterSourceFactory
that will be used to get an instance of
o.s.i.jpa.support.parametersource.ParameterSource.
The ParameterSource is used to resolve the
values of the parameters provided in the query. The
parameter-source-factory attribute is ignored,
if operations are performed using a JPA entity. If a
parameter sub-element is used, the factory
must be of type
ExpressionEvaluatingParameterSourceFactory,
located in package o.s.i.jpa.support.parametersource.
Optional.
use-payload-as-parameter-source
If set to true, the payload of the Message
will be used as a source for providing parameters. If set to
false, the entire Message will be available
as a source for parameters. If no JPA Parameters are passed in,
this property will default to true.
This means that using a default
BeanPropertyParameterSourceFactory, the
bean properties of the payload will be used as a source for
parameter values for the to-be-executed JPA query. However, if
JPA Parameters are passed in, then this property will by default
evaluate to false. The reason is that JPA
Parameters allow for SpEL Expressions to be provided and therefore
it is highly beneficial to have access to the entire Message,
including the Headers.
<int-jpa:updating-outbound-gateway <int:poller/> <int-jpa:transactional/> <int-jpa:parameter <int-jpa:parameter </int-jpa:updating-outbound-gateway> <int:poller/> <int-jpa:transactional/> <int-jpa:parameter <int-jpa:parameter </int-jpa:updating-outbound-gateway>
<int-jpa:retrieving-outbound-gateway <int:poller></int:poller> <int-jpa:transactional/> <int-jpa:parameter <int-jpa:parameter </int-jpa:retrieving-outbound-gateway> <int:poller></int:poller> <int-jpa:transactional/> <int-jpa:parameter <int-jpa:parameter </int-jpa:retrieving-outbound-gateway>
This section contains various examples of the Updating Outbound Gateway and Retrieving Outbound Gateway
Update using an Entity Class
In this example an Updating Outbound Gateway
is persisted using solely the entity class
org.springframework.integration.jpa.test.entity.Student
as JPA defining parameter.
<int-jpa:updating-outbound-gateway
Update using JPQL
In this example, we will see how we can update an entity using the Java Persistence Query Language (JPQL). For this we use an Updating Outbound Gateway.
<int-jpa:updating-outbound-gateway <int-jpa:parameter <int-jpa:parameter </int-jpa:updating-outbound-gateway> <int-jpa:parameter <int-jpa:parameter </int-jpa:updating-outbound-gateway>
When sending a message with a String payload and containing a header rollNumber with a long value, the last name of the student with the provided roll number is updated to the value provided in the message payload. When using an UPDATING gateway, the return value is always an integer value which denotes the number of records affected by execution of the JPA QL.
Retrieving an Entity using JPQL
The following examples uses a Retrieving Outbound Gateway together with JPQL to retrieve (select) one or more entities from the database.
<int-jpa:retrieving-outbound-gateway <int-jpa:parameter <int-jpa:parameter </int-jpa:outbound-gateway>
Update using a Named Query
Using a Named Query is basically the same as using a JPQL query directly. The difference is that the named-query attribute is used instead, as seen in the xml snippet below.
<int-jpa:updating-outbound-gateway <int-jpa:parameter <int-jpa:parameter </int-jpa:outbound-gateway> | http://static.springsource.org/spring-integration/docs/2.2.0.RELEASE/reference/html/jpa.html | CC-MAIN-2013-20 | en | refinedweb |
Write Once, Communicate⦠Nowhere?
Back in August I made the off-hand comment "thank goodness for RXTX" when talking about communicating with serial ports using Java. I've been meaning to revisit that topic in a bit more detail, and now is as good a time as any.
More Insights
White Papers
- Transforming Change into a Competitive Advantage
- Accelerating Economic Growth and Vitality through Smarter Public Safety Management
Reports
- Strategy: How Cybercriminals Choose Their Targets and Tactics
- Strategy: Apple iOS 6: 6 Features You Need to Know
WebcastsMore >>
I can't decide if I love Java or hate it. I've written books on Java, produced a special DDJ issue on Java, and was a Java columnist for one of our sister magazines, back when we had those. I even edited the Dobb's Java newsletter for a while. There must be something I like. However, I always find I like it more in the server and network environment. For user interfaces, I tend towards Qt these days. For embedded systems, I haven't warmed to Java, even though there are a few options out there, some of which I will talk about sometime later this year.
The lines, however, are blurring between all the different kinds of systems. You almost can't avoid Java somewhere. The Arduino uses Java internally. So does Eclipse. Many data acquisition systems need to connect over a network and Java works well for that, either on the device or running on a host PC (or even a Raspberry Pi).
Another love-hate relationship I have is with the serial port. My first real job was with a company that made RS-232 devices, so like many people I have a long history with serial communications. We keep hearing that the office is going paperless and serial ports are dead. Neither of those seems to have much chance of being true anytime soon. Even a lot of USB devices still look like serial ports, so it is pretty hard to completely give up on the old standard, at least for now.
It isn't that Java doesn't support the serial port. Sun released the Java Communications API in 1997 and Oracle still nominally supports it. It covers using serial ports and parallel ports (which are mostly, but not completely, dead). The problem has always been in the implementation.
When reading the official Oracle page, I noticed that there are reference implementations for Solaris (both SPARC and x86) and Linux x86. I guess they quit trying to support Windows, which is probably a good thing. The last time I tried to use the Windows port, it suffered from many strange errors. For example, if the library wasn't on the same drive as the Java byte code, you couldn't enumerate ports. Things like that.
Pretty much everyone I know has switched to using an open project's implementation, RXTX. The Arduino, for example, uses this set of libraries to talk to the serial port (even if the serial port is really a USB port). The project implements the "official" API and requires a native library, but works on most flavors of Windows, Linux, Solaris, and MacOS. The project is pretty much a drop-in replacement unless you use the latest version.
The 2.1 series of versions still implement the standard API (more or less), but they change the namespace to gnu.io.*. If you use the older 2.0 series, you don't have to even change the namespace from the official examples.
Speaking of examples, instead of rewriting code here, I'll simply point you to the RXTX examples if you want to experiment.
One thing I did find interesting, however, is that RXTX uses JNI to interface with the native library (which, of course, varies by platform). I have always found JNI to be a pain to use (although, you don't use JNI yourself if you are just using RXTX in your program). I much prefer JNA. JNA is another way to call native code in Java programs, and it is much easier to manage. Granted, you can get slightly better performance in some cases using JNI, but in general, modern versions of JNA perform well and typically slash development costs.
I did a quick search to see if there was something equivalent to RXTX but using JNA. There is PureJavaComm. Even if you don't want to switch off RXTX, the analysis of the design of PureJavaComm at that link is interesting reading. Using JNA, the library directly calls operating system calls and avoids having a platform-specific shared library, which is a good thing for many reasons.
Have you managed to dump all your serial ports? Leave a comment and share your experiences. | http://www.drdobbs.com/embedded-systems/write-once-communicate-nowhere/240149018?cid=SBX_ddj_related_mostpopular_default_testing&itc=SBX_ddj_related_mostpopular_default_testing | CC-MAIN-2013-20 | en | refinedweb |
03 May 2007 06:17 [Source: ICIS news]
By Jeanne Lim
(updates with latest developments, analyst and market comments)
SINGAPORE (ICIS news)--A fire broke out at ExxonMobilβs Singapore refinery at 01:15 local time (18:15 GMT) on Thursday, killing two people and injuring two others, a company spokeswoman said.
The fire at the refinery at Pulau Ayer Chawan, ?xml:namespace>
The 115,000 bbl/day CDU, which is one of two at the refinery, was shut down immediately following the fire while the other, which has a capacity of 185,000 bbl/day, continues to operate, Ho added.
It wasnβt clear whether the companyβs aromatics unit was affected by the fire at the
βWe are still checking the refinery situation and cannot comment further on this,β he added.
The 300,000 bbl/day refinery processes feedstock for its petrochemical plant producing 400,000 tonnes/year of paraxylene (PX) and 150,000 tonnes/year of benzene.
So far, it appears that downstream production has not been affected by the fire at the refinery.
βNo impact has been heard on the market as far as polymers as concerned,β said Aaron Yap, a trader at Singapore-based petrochemical firm, Integra.
The fire didnβt have a substantial impact on the naphtha market during the morning, a Singapore-based broker said.
The company said that its other refinery at its Jurong site was not affected. The CDUs at Jurong have a combined capacity of 225,000 bbl/day.
Meanwhile, the cause of the fire has yet to be determined, ExxonMobilβs Ho told ICIS news.
All parties involved in the fire were contractors, and the two injured have been sent to the hospital, the firm said in a statement issued a few hours after the incident.
βWe are sorry that this has happened. We are greatly saddened by this tragic event and express our deepest sympathy to the families of those affected,β said the refineryβs manager Steve Blume in the statement.
The company said that it was cooperating with the Singapore Civil Defence Force and other relevant agencies to investigate the incident.
James Dennis and Mahua Mitra. | http://www.icis.com/Articles/2007/05/03/9025850/one+cdu+down+in+exxonmobil+singapore+fire.html | CC-MAIN-2013-20 | en | refinedweb |
MIDP's main user -interface classes are based on abstractions that can be adapted to devices that have different display and input capabilities. Several varieties of prepackaged screen classes make it easy to create a user interface. Screens have a title and an optional ticker. Most importantly, screens can contain Commands , which the implementation makes available to the user. Your application can respond to commands by acting as a listener object. This chapter described TextBox , a screen for accepting user input, and Alert , a simple screen for displaying information. In the next chapter, we'll get into the more complex List and Form classes.
In the last chapter, you learned about MIDP's simpler screen classes. Now we're getting into deeper waters, with screens that show lists and screens with mixed types of controls.
After TextBox and Alert , the next simplest Screen is List , which allows the user to select items (called elements ) from a list of choices. A text string or an image is used to represent each element in the list. List supports the selection of a single element or of multiple elements.
There are two main types of List , denoted by constants in the Choice interface:
MULTIPLE designates a list where multiple elements may be selected simultaneously .
EXCLUSIVE specifies a list where only one element may be selected. It is akin to a group of radio buttons .
For both MULTIPLE and EXCLUSIVE lists, selection and confirmation are separate steps. In fact, List does not handle confirmation for these types of lists-your MIDlet will need to provide some other mechanism (probably a Command ) that allows users to confirm their choices. MULTIPLE lists allow users to select and deselect various elements before confirming the selection. EXCLUSIVE lists permit users to change their minds several times before confirming the selection.
Figure 6-1a shows an EXCLUSIVE list. The user navigates through the list using the arrow up and down keys. An element is selected by pressing the select button on the device. Figure 6-1b shows a MULTIPLE list. It works basically the same way as an EXCLUSIVE list, but multiple elements can be selected simultaneously. As before, the user moves through the list with the up and down arrow keys. The select key toggles the selection of a particular element.
Figure 6-1: List types: (a) EXCLUSIVE and (b) MULTIPLE lists
A further refinement of EXCLUSIVE also exists: IMPLICIT lists combine the steps of selection and confirmation. The IMPLICIT list acts just like a menu. Figure 6-2 shows an IMPLICIT list with images and text for each element. When the user hits the select key, the list immediately fires off an event, just like a Command . An IMPLICIT list is just like an EXCLUSIVE list in that the user can only select one of the list elements. But with IMPLICIT lists, there's no opportunity for the user to change his or her mind before confirming the selection.
Figure 6-2: IMPLICIT lists combine selection and confirmation.
When the user makes a selection in an IMPLICIT List , the commandAction() method of the List 's CommandListener is invoked. A special value is passed to commandAction() as the Command parameter:
public static final Command SELECT_COMMAND
For example, you can test the source of command events like this:
public void commandAction(Command c, Displayable s) { if (c == nextCommand) // ... else if (c == List.SELECT_COMMAND) // ... }
There's an example at the end of this chapter that demonstrates an IMPLICIT List .
To create a List , specify a title and a list type. If you have the element names and images available ahead of time, you can pass them in the constructor:
public List(String title, int type) public List(String title, int type, String[] stringElements, Image[] imageElements)
The stringElements parameter cannot be null ; however, stringElements or imageElements may contain null array elements. If both the string and image for a given list element are null , the element is displayed blank. If both the string and the image are defined, the element will display using the image and the string.
Some List s will have more elements than can be displayed on the screen. Indeed, the actual number of elements that will fit varies from device to device. But don't worry: List implementations automatically handle scrolling up and down to show the full contents of the List .
Our romp through the List class yields a first look at images. Instances of the javax.microedition.lcdui.Image class represent images in the MIDP. The specification dictates that implementations be able to load images files in PNG format. [1] This format supports both a transparent color and animated images.
Image has no constructors, but the Image class offers four createImage() factory methods for obtaining Image instances. The first two are for loading images from PNG data.
public static Image createImage(String name ) public static Image createImage(byte[] imagedata , int imageoffset, int imagelength)
The first method attempts to create an Image from the named file, which should be packaged inside the JAR that contains your MIDlet. You should use an absolute pathname or the image file may not be found. The second method creates an Image using data in the supplied array. The data starts at the given array offset, imageoffset , and is imagelength bytes long.
Images may be mutable or immutable . Mutable Images can be modified by calling getGraphics() and using the returned Graphics object to draw on the image. (For full details on Graphics , see Chapter 9.) If you try to call getGraphics() on an immutable Image , an IllegalStateException will be thrown.
The two createImage() methods described above return immutable Images . To create a mutable Image , use the following method:
public static Image createImage(int width, int height)
Typically you would create a mutable Image for off-screen drawing, perhaps for an animation or to reduce flicker if the device's display is not double buffered.
Any Image you pass to Alert , ChoiceGroup , ImageItem , or List should be immutable. To create an immutable Image from a mutable one, use the following method: public static Image createImage(Image image) .
List provides methods for adding items, removing elements, and examining elements. Each element in the List has an index. The first element is at index 0, then next at index 1, and so forth. You can replace an element with setElement() or add an element to the end of the list with appendElement() . The insertElement() method adds a new element to the list at the given index; this bumps all elements at that position and higher up by one.
public void setElement(int index, String stringElement, Image imageElement) public void insertElement(int index, String stringElement, Image imageElement) public int appendElement(String stringElement, Image imageElement)
You can examine the string or image for a given element by supplying its index. Similarly, you can use deleteElement() to remove an element from the List .
public String getString(int index) public Image getImage(int index) public void deleteElement(int index)
Finally, the size () method returns the number of elements in the List .
public int size()
You can find out whether a particular element in a List is selected by supplying the element's index to the following method:
public boolean isSelected(int index)
For EXCLUSIVE and IMPLICIT lists, the index of the single selected element is returned from the following method:
public int getSelectedIndex()
If you call getSelectedIndex() on a MULTIPLE list, it will returnβ1.
To change the current selection programmatically, use setSelectedIndex() .
public void setSelectedIndex(int index, boolean selected)
Finally, List allows you to set or get the selection state en masse with the following methods. The supplied arrays must have as many array elements as there are list elements.
public int getSelectedFlags(boolean[] selectedArray_return) public void setSelectedFlags(boolean[] selectedArray)
The example in Listing 6-1 shows a simple MIDlet that could be part of a travel reservation application. The user chooses what type of reservation to make. This example uses an IMPLICIT list, which is essentially a menu.
Listing 6-1: The TravelList source code.
import java.io.*; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class TravelList extends MIDlet { public void startApp() { final String[] stringElements = { "Airplane", "Car", "Hotel" }; Image[] imageElements = { loadImage("/airplane.png"), loadImage("/car.png"), loadImage("/hotel.png") }; final List list = new List("Reservation type", List.IMPLICIT, stringElements, imageElements); final Command nextCommand = new Command("Next", Command.SCREEN, 0); Command quitCommand = new Command("Quit", Command.SCREEN, 0); list.addCommand(nextCommand); list.addCommand(quitCommand); list.setCommandListener(new CommandListener() { public void commandAction(Command c, Displayable s) { if (c == nextCommand c == List.SELECT_COMMAND) { int index = list.getSelectedIndex(); System.out.println("Your selection: " + stringElements[index]); // Move on to the next screen. Here, we just exit. notifyDestroyed(); } else notifyDestroyed(); } }); Display.getDisplay(this).setCurrent(list); } public void pauseApp() public void destroyApp(boolean unconditional) private Image loadImage(String name) { Image image = null; try { image = Image.createImage(name); } catch (IOException ioe) { System.out.println(ioe); } return image; } }
To see images in this example, you'll need to either download the examples from the book's Web site or supply your own images. With the J2MEWTK, image files should go in the res directory of your J2MEWTK project directory. TravelList expects to find three images named airplane.png, car.png , and hotel.png .
Construction of the List itself is very straightforward. Our application also includes a Next command and a Quit command, which are both added to the List . An inner class is registered as the CommandListener for the List . If the Next command or the List 's IMPLICIT command are fired off, we simply retrieve the selected item from the List and print it to the console.
The Next command, in fact, is not strictly necessary in this example since you can achieve the same result by clicking the select button on one of the elements in the List . Nevertheless, it might be a good idea to leave it there. Maybe all of the other screens in your application have a Next command, so you could keep it for user interface consistency. It never hurts to provide the user with more than one way of doing things, either.
The difference between EXCLUSIVE and IMPLICIT lists can be subtle. Try changing the List in this example to EXCLUSIVE to see how the user experience is different.
[1] MIDP implementations are not required to recognize all varieties of PNG files. The documentation for the Image class has the specifics. | http://flylib.com/books/en/1.520.1.42/1/ | CC-MAIN-2013-20 | en | refinedweb |
NAME
munmap -- remove a mapping
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <sys/mman.h> int munmap(void *addr, size_t len);
DESCRIPTION
The munmap() system call deletes the mappings for the specified address range, and causes further references to addresses within the range to generate invalid memory references.
RETURN VALUES
The munmap() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.
ERRORS
The munmap() system call will fail if: [EINVAL] The addr argument was not page aligned, the len argument was zero or negative, or some part of the region being unmapped is outside the valid address range for a process.
SEE ALSO
madvise(2), mincore(2), mmap(2), mprotect(2), msync(2), getpagesize(3)
HISTORY
The munmap() system call first appeared in 4.4BSD. | http://manpages.ubuntu.com/manpages/oneiric/man2/munmap.2freebsd.html | CC-MAIN-2013-20 | en | refinedweb |
ConcurrentDictionary<TKey, TValue> Class
Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.
System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>
Assembly: mscorlib (in mscorlib.dll)
[SerializableAttribute] [ComVisibleAttribute(false)] [HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)] public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
Type Parameters
- TKey
The type of the keys in the dictionary.
- TValue
The type of the values in the dictionary.
The ConcurrentDictionary<TKey, TValue> type exposes the following members. *. | http://msdn.microsoft.com/en-us/library/dd287191(v=VS.100).aspx | CC-MAIN-2013-20 | en | refinedweb |
RE: ViewcvsOxley, David wrote:
> Yes, I read the install file. It said to copy the files
> under mod_python to a directory hosted by Apache.
>
> I've just run "cvs up -D 06/14/2003" on viewcvs and got it
> working with the main links, but the links at the top ([svn]
> /Project/trunk) are giving the original error. HEAD of
> viewcvs is completely hosed and unusable unless you type in
> the urls manually. i.e. None of the links work..
>
> Dave
This appears to be caused by bug in mod_python. I posted a bug report to the
mod_python mailing list about this (for some reason it hasn't shown up yet).
Anyway, here's a temporary workaround for viewcvs:
--- sapi.py.orig Fri Aug 8 19:29:24 2003
+++ sapi.py Sat Aug 9 08:06:31 2003
@@ -282,6 +282,18 @@
def getenv(self, name, value = None):
try:
+ if name == 'SCRIPT_NAME':
+ path_info = self.request.subprocess_env.get('PATH_INFO', None)
+ if path_info and path_info[-1] == '/':
+ script_name = self.request.subprocess_env['SCRIPT_NAME']
+ path_len = len(path_info) - 1
+ if path_len:
+ assert script_name[-path_len:] == path_info[:-1]
+ return script_name[:-path_len]
+ else:
+ assert script_name[-1] == '/'
+ return script_name[:-1]
+
return self.request.subprocess_env[name]
except KeyError:
return value
- Russ
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org
For additional commands, e-mail: dev-help@subversion.tigris.org
Received on Sat Aug 9 17:38:00 2003
This is an archived mail posted to the Subversion Dev
mailing list. | http://svn.haxx.se/dev/archive-2003-08/0457.shtml | CC-MAIN-2013-20 | en | refinedweb |
Generally, I've seen that warning when the WordPerfect
importer mis-identifies the file type, and decides to
import the document. If you have that plugin
installed, try removing it.
--- Scott Prelewicz <scottp@noein.com> wrote:
>
>
> This could be for any file. Specifically, we want to
> be able to convert
> uploaded resumes to pdf for the client. Actually,
> the files could be
> Word files or .txt files, though 95% of them will be
> Word files.
>
>
> -----Original Message-----
> From: Dom Lachowicz [mailto:domlachowicz@yahoo.com]
> Sent: Tuesday, June 06, 2006 2:30 PM
> To: Scott Prelewicz; abiword-user@abisource.com
> Subject: Re: AbiWord - .doc to pdf command line
> conversion
>
> Is this for just 1-2 files in particular, or any
> Word
> file?
>
> --- Scott Prelewicz <scottp@noein.com> wrote:
>
> >
> > Hello All,
> >
> > I am trying to convert .doc files to .pdf
> > programmatically. With help
> > from those on IRC, I've managed to make some
> > progress on this however I
> > am getting stuck at the error below while trying
> to
> > test on the command
> > line interface.
> >
> > I am not familiar with AbiWord much, a newbie, but
> > I'm thinking it's
> > possibly an installation issue? Correct? And if
> so,
> > what should I do? :)
> >
> > Running AbiWord 2.4 on OpenBSD 3.6.
> >
> >
> >
> > >> abiword --to=/tmp/foo.pdf /tmp/bar.doc
> >
> > (abiword:14375): libgsf:msole-CRITICAL **:
> > ole_get_block: assertion
> > `block < ole->info->max_block' failed
> >
> > ** (abiword:14375): WARNING **: failed request
> with
> > status 1030
> > Aborted
> >
> >
> >
> >
> > /tmp/foo.pdf DOES get created, however it is a
> zero
> > length file unable
> > to be read by Acrobat reader. The test doc is a
> > simple one sentence Word
> > document.
> >
> > Thank you for any help,
> >
> > Sc Jun 6 20:40:26 2006
This archive was generated by hypermail 2.1.8 : Tue Jun 06 2006 - 20:40:26 CEST | http://www.abisource.com/mailinglists/abiword-user/2006/Jun/0009.html | CC-MAIN-2013-20 | en | refinedweb |
25 February 2011 18:43 [Source: ICIS news]
LONDON (ICIS)--Lubricants demand in India, which is expected to overtake China as the worldβs fastest growing major economy, could expand by more than 19% from 2009 to 2.23m tonnes in five years, said an industry expert on Friday.
Industrial lubricants are likely to be the fastest growing segment, followed by the consumer and commercial sectors, said Kline & Coβs Geeta Agashe.
Agashe spoke at the 15th ICIS World Base Oils & Lubricants Conference in ?xml:namespace>
Industrial oils and fluids, which accounted for slightly over half of Indiaβs total lubricants demand in 2009, was projected to grow at 4.5% per year to 1.18m tonnes in 2014, according to Agashe. The countryβs total lubricants consumption was at an estimated 1.86m tonnes in 2009.
A sizeable portion of the growth in industrial lubricants demand would come from the power generation plants, as well as the automotive and auto-component industries, she added.
Consumer lubricants consumption, driven mainly by rising car and motorcycle population, could expand to 214,000 tonnes by 2014, based on a projected annual growth rate of 3.3% per year, Agashe said.
The market is also expected to shift towards better quality and lighter viscosity engine oils, partly because of higher emission standards and stricter requirements by the original equipment manufacturers (OEM).
By 2014, 5W and 0W lower viscosity engine oils are expected to make up around 10% of the market in
Growth in the commercial automotive lubricants sector, which includes heavy duty engine oil for buses and trucks, as well as lubricants for agricultural equipment such as tractors, is expected to increase at a yearly rate of 2.6% to 834,000 tonnes in 2014, she said.. | http://www.icis.com/Articles/2011/02/25/9439042/indias-lubricants-demand-predicted-to-see-strong-growth.html | CC-MAIN-2013-20 | en | refinedweb |
Coding Tutorials
This comprehensive dataset consists of 500,000 documents, summing up to around 1.5 billion tokens. Predominantly composed of coding tutorials, it has been meticulously compiled from various web crawl datasets like RefinedWeb, OSCAR, and Escorpius. The selection process involved a stringent filtering of files using regular expressions to ensure the inclusion of content that contains programming code (most of them).
These tutorials offer more than mere code snippets. They provide an extensive context, including the rationale behind the code, the problem being addressed, and detailed step-by-step instructions. This layered context is helpful for training a code-LM model, enabling it to discern the user intent behind a piece of code and thus facilitating more contextually relevant assistance.
Programming Language Distribution
cpp β 39% βββββββββββββββββββββββββ
python β 25% ββββββββββββββββ
java β 16% ββββββββββ
csharp β 3% ββ
javascript β 1% β
kotlin β 1% β
other β 14% βββββββββ
Natural language distribution
en β 80% βββββββββββββββββββββββββ
ru β 16% βββββ
zh β 2% β
es β 2% β
- Downloads last month
- 209