text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
24801/how-can-define-multidimensional-array-in-python-using-ctype
Here's one quick-and-dirty method:
>>> A = ((ctypes.c_float * 10) * 10)
>>> a = A()
>>> a[5][5]
0.0
In Logic 1, try if i<int(length/2): instead of if i<int((length/2+1)):
In ...READ MORE
Hi, it is pretty simple, to be ...READ MORE
Good question. I actually was stuck with ...READ MORE
def add(a,b):
return a + b
#when i call ...READ MORE
suppose you have a string with a ...READ MORE
You can also use the random library's ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
can you give an example using a ...READ MORE
Use os.rename(src, dst) to rename or move a file ...READ MORE
The datetime class has a method strftime. strftime() ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/24801/how-can-define-multidimensional-array-in-python-using-ctype?show=24803 | CC-MAIN-2020-29 | refinedweb | 147 | 80.88 |
Wincv.exe (Windows Forms Class Viewer)
The Windows Forms Class Viewer allows you to quickly look up information about a class or series of classes, based on a search pattern. The class viewer displays information by reflecting on the type using the common language runtime reflection API.
The Windows Forms Class Viewer only ships with the .NET Framework SDK version 1.0 and 1.1.
The following table describes the options available.
Start Wincv.exe from the command line and type all or part of a type name in the text box at the top of the form. The list box on the left side of the form displays a list of all the types that Wincv.exe finds, based on the name you entered. The System namespace is implied on the class names. Therefore, type "Object" is displayed in the list of class names instead of "System.Object". When you select a type from the list, the type definition appears in the area on the right. The type definition is displayed using a C# like syntax. Note, however, that not all type definitions will compile in the C# compiler exactly as they are shown in the viewer. The following example demonstrates how to look up information on the ButtonBase class.
To locate a type definition using Wincv.exe
Type wincv at the command prompt. This loads the default assemblies and displays the Class Viewer.
Type Button in the text box at the top of the form.
Select the ButtonBase class name in the System.Windows.Forms namespace from the types displayed in the list box on the left side of the form.
The definition of System.Windows.Forms.ButtonBase appears in the area on the right.
The following command runs Wincv.exe and loads myApp.exe and the default assemblies for browsing.. | https://msdn.microsoft.com/en-US/library/sbey26hw(v=vs.110).aspx | CC-MAIN-2016-07 | refinedweb | 303 | 77.13 |
I am using CP model of OPL.This is the program that I have written
using CP;
int n=...;
range R=1..n;
dvar int x[R] in 1..n*n;
minimize x10;
subject to
{
forall(i in 1..n)
forall(j in i..n)
forall(k in j+1..n)
x[k]-x[j]-x[i]!=0;
forall(i in 1..n)
forall(j in i+1..n)
forall(k in j..n)
forall(l in k+1..n)
x[l]+x[i]-x[j]-x[k]!=0;
forall(i in 1..n)
forall(j in i..n)
forall(k in j..n)
forall(l in k+1..n)
x[l]-x[i]-x[j]-x[k]!=0;
forall(i in 1..n-1)
{
0<x[i];
x[i]<xi+1;
xi+1<=n*n;
}
}
for n=10 it does not produces its optimal value in more than 10 hours.So if I want to get the values of decision variable at a particular time after aborting the execution of program. what should I do?Please help me.
I have working on COP a problem that has multiple solution for obtaining multiple solution I am doing it by converting it to a CSP problem and getting the value.After running the program it produces identical solution of many sets. What should I do to avoid this. I am using CP model in OPL.
Topic
anshu.iitv 270005RQVQ
3 Posts
Pinned topic getting values of decision variable at time of aborting the run
2012-10-16T15:12:58Z |
Updated on 2012-10-16T16:50:48Z at 2012-10-16T16:50:48Z by ChrisBr
Re: getting values of decision variable at time of aborting the run2012-10-16T16:50:48Z
This is the accepted answer. This is the accepted answer.Hello,
Try to set a time limit.
For example:
execute { cp.param.timeLimit = 5*60*60; }
You can notice also, that because you have defined the domain of your variables
dvar int x[R] in 1..n*n;
it is not necessary to set the following constraints:
forall(i in 1..n-1) { 0<x[i]; x[i+1]<=n*n; }
I hope this helps,
Chris. | https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014898411 | CC-MAIN-2016-50 | refinedweb | 365 | 79.56 |
The ElementTree iterparse Function
The new iterparse interface allows you to track changes to the tree while it is being built. This interface was first added in the cElementTree library, and is also available in ElementTree 1.2.5 and later.
Recent versions of lxml.etree also supports this API.
Usage #
To use iterparse, just call the method and iterate over the object it returns. The result is an iterable that returns a stream of (event, element) tuples.
for event, elem in iterparse(source): ... elem is complete; process it ...
for event, elem in iterparse(source, events=("start", "end")): if event == "start": ... elem was just added to the tree ... else: ... elem is complete; process it ...
The events option specify what events you want to see (available events in this release are “start”, “end”, “start-ns”, and “end-ns”, where the “ns” events are used to get detailed namespace information). If the option is omitted, only “end” events are returned.
Note: The tree builder and the event generator are not necessarily synchronized; the latter usually lags behind a bit. This means that when you get a “start” event for an element, the builder may already have filled that element with content. You cannot rely on this, though — a “start” event can only be used to inspect the attributes, not the element content. For more details, see this message.
Incremental Parsing #
Note that iterparse still builds a tree, just like parse, but you can safely rearrange or remove parts of the tree while parsing. For example, to parse large files, you can get rid of elements as soon as you’ve processed them:
for event, elem in iterparse(source): if elem.tag == "record": ... process record elements ... elem.clear()
The above pattern has one drawback; it does not clear the root element, so you will end up with a single element with lots of empty child elements. If your files are huge, rather than just large, this might be a problem. To work around this, you need to get your hands on the root element. The easiest way to do this is to enable start events, and save a reference to the first element in a variable:
# get an iterable context = iterparse(source, events=("start", "end")) # turn it into an iterator context = iter(context) # get the root element event, root = context.next() for event, elem in context: if event == "end" and elem.tag == "record": ... process record elements ... root.clear()
(future releases will make it easier to access the root element from within the loop)
Namespace Events #
The namespace events contain information about namespace scopes in the source document. This can be used to keep track of active namespace prefixes, which are otherwise discarded by the parser. Here’s how you can emulate the namespaces attribute in the FancyTreeBuilder class:
events = ("end", "start-ns", "end-ns") namespaces = [] for event, elem in iterparse(source, events=events): if event == "start-ns": namespaces.insert(0, elem) elif event == "end-ns": namespaces.pop(0) else: ...
The namespaces variable in this example will contain a stack of (prefix, uri) tuples.
(Note how iterparse lets you replace instance variables with local variables. The code is not only easier to write, it is also a lot more efficient.)
For better performance, you can append and remove items at the right end of the list instead, and loop backwards when looking for prefix mappings.
Incremental Decoding #
Here’s a rather efficient and almost complete XML-RPC decoder (just add fault handling). This implementation is 3 to 4 times faster than the 170-line version I wrote for Python’s xmlrpclib library…
from cElementTree import iterparse from cStringIO import StringIO import datetime, time def make_datetime(text): return datetime.datetime( *time.strptime(text, "%Y%m%dT%H:%M:%S")[:6] ) unmarshallers = { "int": lambda x: int(x.text), "i4": lambda x: int(x.text), "boolean": lambda x: x.text == "1", "string": lambda x: x.text or "", "double": lambda x: float(x.text), "dateTime.iso8601": lambda x: make_datetime(x.text), "array": lambda x: [v.text for v in x], "struct": lambda x: dict((k.text or "", v.text) for k, v in x), "base64": lambda x: decodestring(x.text or ""), "value": lambda x: x[0].text, } def loads(data): params = method = None for action, elem in iterparse(StringIO(data)): unmarshal = unmarshallers.get(elem.tag) if unmarshal: data = unmarshal(elem) elem.clear() elem.text = data elif elem.tag == "methodCall": method = elem.text elif elem.tag == "params": params = tuple(v.text for v in elem) return params, method
Note that code uses the text attribute to temporarily hold unmarshalled Python objects. All standard ElementTree implementations support this, but some alternative implementations may not support non-text attribute values.
The same approach can be used to read Apple’s plist format:
try: import cElementTree as ET except ImportError: import elementtree.ElementTree as ET
To round this off, here’s the obligatory RSS-reader-in-less-than-eight-lines example:
from urllib import urlopen from cElementTree import iterparse for event, elem in iterparse(urlopen("")): if elem.tag == "item": print elem.findtext("link"), "-", elem.findtext("title") elem.clear() # won't need the children any more
Comment:
Here is an alternative method for grabbing the root element for iterparse:
context = iterparse(source, events=("start", "end")) root = None for event, elem in context: if event == "start" and root is None: root = elem # the first element is root if event == "end" and elem.tag == "record": ... process record elements ... root.clear()
This has the added advantage that you can also capture namespace events that occur before the first "start" if needed for the application, which doesn't work using the sample code in the article.
Posted by Russell (2006-11-27)
Comment:
Suggested links for the plist section:
The same approach can be used to read Apple's XML plist format (though not its ASCII or binary plist formats):
Posted by Simon (via mail) (2006-10-24) | http://www.effbot.org/zone/element-iterparse.htm | crawl-001 | refinedweb | 981 | 65.83 |
With all the excitement of releasing the first public EAP build of Rider last week, we didn’t post about ReSharper Ultimate 2016.3 EAP 9. And now we’ve released EAP 10, so let’s get caught up!
Visual Studio 2017 RC
ReSharper Ultimate products now have initial support for Visual Studio 2017 RC, including the new .csproj based .NET Core projects. It’s important to note, however, that even though VS2017 is marked as “RC”, there are a number of features and architectural changes that are currently marked as “preview”. As such, we are still working on support for some of these new Visual Studio features, such as lightweight solution load and opening from folder.
Similarly, the new .csproj based .NET Core project system is marked as “alpha”, and while we support loading projects in this format, there are what we can euphemistically call “rough edges”. One such example is unit testing, which is no longer compatible with how it was run in the project.json world. Existing project.json based testing is of course still working.
A much more serious issue is that changes to the project model means that ReSharper C++ doesn’t currently work with VS2017 RC, at all. We currently recommend against updating to VS2017 RC if you wish to continue using ReSharper C++.
dotCover
Improved highlighting in Continuous Testing sessions
The other big news is that we are now introducing a much requested feature for Continuous Testing — improved highlighting!
ReSharper Ultimate users can enable Continuous Testing to run only the tests that are affected by your current code changes, based on dotCover coverage data (and don’t forget ReSharper Build to speed up the build cycle!). Our previous highlighting left a little to be desired, so we’ve updated it.
We now display a marker in the text editor showing red if any tests related to this change are failing, green if all tests are passing and grey if there are no tests covering this line of code. And when a result is outdated, because the test, or a line of code related to that test has changed, the markers are shown faded.
Hovering over the marker highlights the associated region of code and gives a quick summary of the state of change. Clicking on the marker shows a popup with the list of tests that affect the current line. It also includes a small toolbar to rerun all associated tests, only dirty tests, and to run or debug any selected tests. Even better, you can insert a break point and start debugging with a single click.
Double clicking a test in the list will navigate to the test in the results window, and clicking the arrow to the right of a failing test will open a flyout window with failure and exception details, all clickable, of course.
(Note that there appears to be a high DPI issue here. If you have DPI set to 200%, then the list of tests doesn’t appear. We’re investigating, and will get it fixed in a future EAP build.)
Revised filtering settings
This build of dotCover also introduces a new Filtering options page that allows easy selection of what code should be covered – all assemblies, everything except System and dotCover assemblies or only solution assemblies, without dependencies. It also allows hiding auto properties from coverage results, and allows editing filters based on assembly name, namespace, typename or attribute.
ReSharper
Transform Parameters refactoring
C# support gets a new refactoring, Transform Parameters, which takes existing two refactorings – Transform Out Parameter and Extract Class from Parameters – and merges and improves them. The new Transform Parameters refactoring can be invoked on a method declaration and will rewrite the method’s parameters, changing incoming parameters to a new class, or a tuple, and optionally creating a new class for return value and any out parameters.
Quick-fixes to introduce fields and properties
Next, we have a new quick-fix to introduce fields and auto properties from all unused parameters. This is an extension to the existing quick-fix that will introduce a field from a single constructor parameter, but if you extend the Alt+Enter menu item, it will now apply to all unused parameters at once.
The Introduce property quick-fix also includes a Configure default menu item, which will set what kind of property is generated by default – get only, mutable, with private setter, etc.
More new and updated code actions
C# gets another couple of small updates. Firstly, the Generate constructor action gets a small update with an option to check parameters for null. If checked, it will generate guard code that throws ArgumentNullException in the constructor.
And secondly, a new context action on fields of type Lazy<T> will introduce a property to encapsulate fieldname.Value.
TypeScript
TypeScript support gets code completion for literal types, as well as a number of formatting fixes for JSX/TSX files.
To-do item colors
And finally, we’ve fixed a minor irritation: to-do items displayed in one colour in the editor, and a different colour in the To-do Explorer! Now each to-do pattern can have a category – “Normal”, “Edit”, “Error”, “Question” or “Warning”, and each category can have its own colour, which is reflected in the To-do Explorer, the editor and can be configured in Visual Studio’s Fonts and Colors options page.
ReSharper C++
Postfix templates
ReSharper C++ gets some postfix template goodness, with new templates for if, else, while, do, return, switch and foreach. If you’re not familiar with postfix templates, the idea is that they allow you to focus on your data, rather than the syntax.
Typedef refactorings
This build also introduces a couple of new refactorings: Introduce typedef and Inline typedef. Simply highlight a typename and select Introduce typedef from the Refactor this menu (or use Ctrl+R, I) to introduce a typedef. The Inline typedef refactoring will do the inverse – replace an existing typedef with the actual type.
Finally for C++, there’s a small fix to automatically update unit tests when a file is changed externally to the IDE, such as updating from source control.
dotTrace
Events and subsystems in Timeline Viewer
dotTrace’s Timeline view has had a fairly major update with the introduction of subsystems, and the reworking of some of the filter categories.
Firstly, the Interval Filters and Analysis Subject filter groups have been merged into a new Events group, which allows filtering by time, memory allocation, debug output (new to this build), garbage collection, file operations, SQL queries and so on.
And secondly, we’ve introduced Subsystems as a set of filters, which you may be familiar with from dotTrace’s other profiling views. Subsystems group methods by namespace and assembly, to categorise code such as WPF, string handling or collections. We’ve extended this to also include time spent in file operations, JIT, garbage collection, SQL queries and so on, to allow a very flexible way of categorising a filter.
This is a really helpful way of classifying where time is being spent, giving you an immediate view on what areas require attention: for example, you could see that your code needs to improve string handling, or is spending too long working with collections.
Call Stack view updates
We’ve also made some subtle but really useful changes to the Call Stack view. The methods pane now also shows what proportion of time is spent in various subsystems. Clicking on the subsystem name will enable the equivalent subsystem in the Filters pane, updating the visible methods and call stack to show the methods which end up calling into the subsystem.
The methods pane now has a new toolbar which includes a button to follow the selection in the call tree, filtering the list of top methods. There is also a button to toggle showing system functions as separate items, rather than rolling the time spent into the calling method. And finally, there is a button to toggle sorting, by either top method based on own or total time.
Download
Please download the latest ReSharper Ultimate 2016.3 EAP build, and if you come across any problems with this build, please let us know.
Is ReSharper RTM planned before the end of this year or in 2017?
It’s planned for mid-December this year.
I am loving the new dotCover highlights… the previous was simply too distracting… planning to subscribe to dotCover once it is released…
Pingback: Dew Drop - November 30, 2016 (#2373) - Morning Dew
For some reason my MainViewmodel.cs file doesn’t offer any of the “cleanup” or Quick Fix tips to the code, while on my other ViewModel files Resharper works correctly.
MainViewModel and ViewModelLocator are both omitted from ReSharper analysis.(Perhaps because they were added automatically as part of the MVVM Light NuGet package?) The fix is to right-click the “Pause” icon at the top of the vertical scrollbar and “Enable analysis” for the file. Click again and “Resume”
Renaming the file to TMainViewModel.cs fixes the problem. Something in EAP 10 is disabling Resharper on files named MainViewModel.cs.
Samething with me, but I renamed the folder, to MyViewModels instead ViewModel, and it fixed for me
Is there a way to turn on the previous code coverage highlighting? The new markers are great showing pass/fail on individual lines, however, I have lost the instant visual of clicking on a unit test and being able to actually see the coverage from that test (or test group). So basically, except for the markers, I cannot see the visual of coverage without physically hovering over individual lines with my mouse…not so good for productivity when testing IMHO
It was useful to be able to quickly see what was covered/not covered and turn it on/off in the code coverage session window, and would be equally nice to be able to configure this behavior in Resharper/DotCover for those of us who used it that way.
Thanks
+1
Hi Jeff,
Unfortunately, in EAP09-10, ‘Show coverage for selected tests’ doesn’t work with highlighting (only tree is updated). It’s a bug that will be fixed in the release.
Considering “old” highlighting – not in 2016.3, sorry. Nevertheless, you can disable the option “ReSharper | Options | dotCover | Consider test results in highlighting color”. This will turn on “old” highlighting logic (but it’s still be shown with markeres) where test results are not taken into account. Red – not covered, green – covered.
Is it hard to make always lines highlighting without mouse hovering (as option)?
Will be option to run tests without saving? Like Continous Tests/NCrunch/New VS 2017 feature?
So I’ve been using the EAP builds, and been regularly submitting exceptions.
What concerns me is that those exception reports (apart from the DotCover one) appear to have been completely ignored. Is anyone actually triaging these at all? Doesn’t really inspire confidence that 2016.3 is going to be a solid improvement at the moment.
Here’s the ones I’ve reported directly:
(That doesn’t count the ones I’ve reported that were first reported by someone else)
Not to mention the fact that the Exception Reporter itself always forgets between Visual Studio restarts that it has already reported exceptions. That’s super-annoying.
David
Really pleased about “Transform Parameters refactoring”. Its been a long time coming, but it will save me lots of time. The response object pattern is one we use very commonly (in unit tests as much as anywhere), and being able to create it easily from out parameters is a real time saver.
Pingback: Auf dem Weg zu ReSharper Ultimate 2016.3 - entwickler.de | https://blog.jetbrains.com/dotnet/2016/11/29/resharper-ultimate-2016-3-eap-9-and-10/?replytocom=481205 | CC-MAIN-2020-10 | refinedweb | 1,952 | 50.67 |
Implementing A Simple Text Display Widget
Fredrik Lundh | September 2004 | Originally posted to online.effbot.org
Time for some WCK programming. The following snippet implements a simple text widget, which can display a single paragraph of text:
from WCK import Widget, FONT, FOREGROUND class SimpleTextView(Widget): ui_option_text = "" ui_option_width = 200 ui_option_height = 100 ui_option_font = FONT ui_option_foreground = FOREGROUND def ui_handle_config(self): self.font = self.ui_font( self.ui_option_foreground, self.ui_option_font ) return int(self.ui_option_width), int(self.ui_option_height) def ui_handle_repair(self, draw, x0, y0, x1, y1): space = draw.textsize(" ", self.font)[0] words = self.ui_option_text.split() x = y = 0 for word in words: # check size of this word w, h = draw.textsize(word, self.font) # figure out where to draw it if x: x += space if x + w > x1: # new line x = 0 y += h draw.text((x, y), word, self.font) x += w
The repair code treats the text as a single paragraph, consisting of one long list of words. Note that the code always draws words that start at the left margin, even if they won’t fit on the line.. | http://sandbox.effbot.org/zone/wck-simpletext.htm | crawl-003 | refinedweb | 178 | 57.37 |
User:FvdP
From Wikipedia, the free encyclopedia
Watch this self-regulated driver, and his car hedged by ESC and other goodies. He drives fast in straight lanes and curves, never meeting any hint of losing control. So he can drive faster, and indeed drives faster and faster. Until one day, in one curve, the tires of his vehicle suddenly loose grip and he leaves the road, to meet his end on a tree.
That's called a crash.
One life!
Nothing is certain, much is possible.
Ha ! And you thought it would be easy ?
I'm a French-speaking Belgian who lives in Brussels, active on the French- and English-speaking Wikipedias. (And very occasionally active on other Wikipedias for maintenance purposes.)
Among my interests:
- mathematics
- computer science, programming
- science in general (astronomy, physics, biology, psychology) - "how is all this working ?"
- "Is there any God" and related questions - materialism
- visual arts (mostly painting & sculpture)
- literature, painting, photography, ...
- ...and of course, consult my [user contributions] for more...
Incomplete list of articles I started:
- Thalys ...nothing to do with any of the above interests ;-)
- Bruges just a stub, shamelessly inspired by Ghent.
- ...
Incomplete list of articles I significantly contributed content (or at least a significant twist):
- Carmichael number (higher-order Carmichael numbers)
- freethought
- ...
I contributed also translations from here to the French Wikipedia.
[edit] Interesting articles
(written by others ! This list is also pretty random.)
[edit] Odd subjects
- IP over Avian Carriers. They did it !
[edit] To-do list
Articles I might work on in the future (but don't rely on my doing it !):
- Pisot-Vijayaraghavan numbers, to link from Fibonacci number and Phi.
- John Constable, Léon Spilliaert
[edit] A few links (mainly) for my own convenience
- Technical help
- Help:Table : wiki-tables
- Guidelines
- Cooling down - no personal attacks
- Edit wars, vandalism and other editorial problems:
- Misc. Wikipedia:List_of_articles_in_Wikipedia:_namespace
- Personal subpages:
Recent changes: | http://ornacle.com/wiki/User:FvdP | crawl-002 | refinedweb | 313 | 58.79 |
Default Parameter Values in Python
Fredrik Lundh | July 17, 2008 | based on a comp.lang.python post
Python’s handling of default parameter values is one of a few things that tends to trip up most new Python programmers (but usually only once).
What causes the confusion is the behaviour you get when you use a “mutable” object as a default value; that is, a value that can be modified in place, like a list or a dictionary.
An example:
>>> def function(data=[]): ... data.append(1) ... return data ... >>> function() [1] >>> function() [1, 1] >>> function() [1, 1, 1]
As you can see, the list keeps getting longer and longer. If you look at the list identity, you’ll see that the function keeps returning the same object:
>>> id(function()) 12516768 >>> id(function()) 12516768 >>> id(function()) 12516768
The reason is simple: the function keeps using the same object, in each call. The modifications we make are “sticky”.
Why does this happen? #
Default parameter values are always evaluated when, and only when, the “def” statement they belong to is executed; see:
for the relevant section in the Language Reference.
Also note that “def” is an executable statement in Python, and that default arguments are evaluated in the “def” statement’s environment. If you execute “def” multiple times, it’ll create a new function object (with freshly calculated default values) each time. We’ll see examples of this below.
What to do instead? #
The workaround is, as others have mentioned, to use a placeholder value instead of modifying the default value. None is a common value:
def myfunc(value=None): if value is None: value = [] # modify value here
If you need to handle arbitrary objects (including None), you can use a sentinel object:
sentinel = object() def myfunc(value=sentinel): if value is sentinel: value = expression # use/modify value here
In older code, written before “object” was introduced, you sometimes see things like
sentinel = ['placeholder']
used to create a non-false object with a unique identity; [] creates a new list every time it is evaluated.
Valid uses for mutable defaults #
Finally, it should be noted that more advanced Python code often uses this mechanism to its advantage; for example, if you create a bunch of UI buttons in a loop, you might try something like:
for i in range(10): def callback(): print "clicked button", i UI.Button("button %s" % i, callback)
only to find that all callbacks print the same value (most likely 9, in this case). The reason for this is that Python’s nested scopes bind to variables, not object values, so all callback instances will see the current (=last) value of the “i” variable. To fix this, use explicit binding:
for i in range(10): def callback(i=i): print "clicked button", i UI.Button("button %s" % i, callback)
The “i=i” part binds the parameter “i” (a local variable) to the current value of the outer variable “i”.
Two other uses are local caches/memoization; e.g.
def calculate(a, b, c, memo={}): try: value = memo[a, b, c] # return already calculated value except KeyError: value = heavy_calculation(a, b, c) memo[a, b, c] = value # update the memo dictionary return value
(this is especially nice for certain kinds of recursive algorithms)
and, for highly optimized code, local rebinding of global names:
import math def this_one_must_be_fast(x, sin=math.sin, cos=math.cos): ...
How does this work, in detail? #
When Python executes a “def” statement, it takes some ready-made pieces (including the compiled code for the function body and the current namespace), and creates a new function object. When it does this, it also evaluates the default values.
The various components are available as attributes on the function object; using the function we used above:
>>> function.func_name 'function' >>> function.func_code <code object function at 00BEC770, file "<stdin>", line 1> >>> function.func_defaults ([1, 1, 1],) >>> function.func_globals {'function': <function function at 0x00BF1C30>, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None}
Since you can access the defaults, you can also modify them:
>>> function.func_defaults[0][:] = [] >>> function() [1] >>> function.func_defaults ([1],)
However, this is not exactly something I’d recommend for regular use…
Another way to reset the defaults is to simply re-execute the same “def” statement. Python will then create a new binding to the code object, evaluate the defaults, and assign the function object to the same variable as before. But again, only do that if you know exactly what you’re doing.
And yes, if you happen to have the pieces but not the function, you can use the function class in the new module to create your own function object.
[comment on/vote for this article] | http://effbot.org/zone/default-values.htm | crawl-002 | refinedweb | 779 | 50.97 |
Written by
Frank Nimphius (
Twitter), Oracle Corporation
June, 01 2010
The use case covered in this ADF Code Corner article is best explained by a series of screen shots showing the final runtime beavior. The Oracle JDeveloper 11.1.1.3 workspace for this example is provided for download at the end of this article.
1. To bulk update selected table rows, the application user selects an editable table cell to copy the value from
2. With the right mouse button pressed, a context menu opens to copy the cell value. The context menu is defined using ADF Faces components and JavaScript. It cancels the context menu action to suppress the browser native functionality. The table cell renderer components are af:inputText components with an af:clientListener defined to open the menu.
Hint: Alternatively to using the context menu, the user can press ctrl+shift+c to copy the cell content. The implementation for this is through another af:clientListener that looks at the keyboard code and the key modifiers pressed using the ADF Faces client side APIs.
3. Now the user can ress the ctrl key and click on all the rows rows he or she want to copy the values to. The implementation is such that when copying the cell value, the column is remembered as well, so that when pasting it to other rows, values are added to the right column.
Hint: The functionality can be easily extended to copy and paste the values of multiple columns. All you need to do on the page source is to add additional column names (atributes) to the colname af:clientAttribute tag, which we explore in a minute
4. To paste the values, the user opens the context menu with the right mouse button and chooses the paste option.
Hint: Instead of the context menu, the user could use the ctrl+shift+v keyboard combination to paste the value to the selected table rows.
5. As shown in the image below, the cell value is copied to the selected table rows. But there is more than what meets the eyes. The logic of copying the data is implemented on the server side, with the help of an af:serverListener component. The server side implementation updates the ADF binding layer for the selected rows and - optionally - can be used to update the business service as well, which especially in non-ADF Business Components cases require an extra function to be called.
At the end, the table is PPR'ed to show the copied values in the selected table rows. Of course, the implementation could have been client side only, but this would go with a lot more JavaScript coding. Because tables in ADF Faces are stamped its in fact easier to perform the value operations on teh server and accept the little twinkle when refreshing the table.
Note:Though JavaScript is mainstream with Ajax, I recommend to use it by exception and only in small doses. In traditional web developments, JavaScript has proven as a silver bullet. However, if you want to play it safe, prefer mature, solid and typed Java programming interfaces whenever you can to ensure browser and upgrade compatibility for your applications. And if you use JavaScript, as I do in this example, play by the rules and stick with the public APIs the ADF Faces component framework exposes.
Here's a list of topics you learn about if you continue reading this article:
af:clientListener, af:serverListener usage
how to detect which table a user selected
using JavaScript callbacks in af:clientListener to pass additional arguments
how to create keyboard shortcuts (ctrl+shift+c and ctrl+shift+v), optionally overriding the browser defaults
The use of DCDataRow vs. oracle.jbo.Row
Note: In a previous article, I explained pagination in POJO based DataControls. This sample too uses pagination to not fetch all data at once.
Note: I added comments to the source code printed in this article and contained in the sample workspace. Make sure you read the comments for a better understanding of what is going on.
Users select a table cell to copy the value from. The ADF Faces table is stamped, which means that a cell is not an object that one can ask for what column and table row it belongs to. So to get this information at runtime, a little trick using an af:clientAttribute is needed to provide this information at design time . The af:clientAttribute component allows developers to enhance ADF Faces component instences with additional - custom defined - properties. The table in the example has two af:clientAttribute tags, one for the column name (the attribute name it represents, not the column label) and one for the row number (the row index).
As you see in the image above, the client attributes are defined as a child of the af:inputText components that make the cell renderer. The client attribute for the column name is called "colname" (a name I came up with) and references the binding layer through the " tableRow" variable. The "tableRow" variable is defined on the table and is used to temporarily hold the current rendered table row when iterating over the CollectionModel to print the table. By default the variable name is set to "row". I changed it to "tableRow" to make it more explicit what the role of this is.
The "colname" value is read from the ADF binding layer, through the tableRow variable. By accessing the binding layer for the column name, I make the page sources independent from the business service accessed by the binding. On the client side, from JavaScript, the client attribute value can be accessed by <component>.getProperty('colname').
The client listeners on the Input Text components are used to respond to the right mouse button click and the keyboard. When the user clicks on a text field using the right mouse button, a popup dialog is opened and aligned with the selected table cell. You can't do this alignment with the af:showPopupBehavior tag, which is why a pure JavaScript approach is taken. The keyboard listener calls a JavaScript function for each key pressed. The JavaScript function then checks if the pressed key is "c" or "v" in combination with ctrl+shift. If any other keyboard key or key combination is pressed, the JavaScript function doesn't do anything and lets the event bubble up for the browser to handle. If the key ctrl+shift+c or ctrl+shift+v is detected, then the JavaScript function cancels the event and copies or pastes the cell value.
Important: For ADF Faces components to be come accessible in JavaScript on the client, the clientComponent property must be set to "true" or an af:clientListener tag must be added. Otherwise, most likely, the component renders in HTML in which case it is "invisible" for the client side ADF Faces framework. But wait ! Before you set clientComponent="true" for all components on a page, keep in mind that the decision not to generate JavaScript objects for all components on a page is by design and for better performance. So please, curve your enthusiasm and think twice before enabling this option. However, forgetting to set clientComponent to true is the most common mistake developers do when using the client side AD Faces JavaScript framework.
Below is the page source of a table column, which is configured for copy and paste support. The interesting code lines are highlighted in bold. Please notice the use of the "status" variable that is the value of the table varStatus attribute. The "status" variable is used to display row numbers in front of the table but also as the value of the "rowKey" client attribute to identify the row a selected table cell component is in.
<af:table
<!-- the rows below are commented out from the table definition to allow multiple
table row selection. The ADF binding layer can only have a single current
row and therefore would reset multiple row selection on table refresh.
selectedRowKeys="#{bindings.allEmployees.collectionModel.selectedRow}"
selectionListener="#{bindings.allEmployees.collectionModel.makeCurrent}"
-->
<af:column
<af:outputText
</af:column>
<af:column
<af:inputText
<f:validator
<af:convertNumber
<af:clientListener
<af:clientListener
<af:clientAttribute
<af:clientAttribute
<!-- popup is in PanelCollection 'pc1' with an ID of 'p1' -->
</af:inputText>
</af:column>
...
With this table configuration, a JavaScript function is called when the right mouse button is used on a table cell and when users press a keyboard key. The client attributes provide information about the "where in the table" users clicked into. Note that the client listener methods have string arguments that define the name of the af:serverListener component to call a managed bean method and the client id of the popup component to launch.
At a first glance, the JavaScript below looks like a lot of code to write for a little functionality. However, as you will see when I go through it, most of what you see are comments I added for you to get a better understanding of what a specific code line is doing.
The JavaScript source is referenced from the ADF Faces page using the af:resource component, as shown below
." --- (from the tag documentation)
The JavaScript has two global variable defined, which are used as a temporary memory scope for the selected table cell content. The globalFieldCopy variable holds the inputText component instance of the table cell to copy from. The globalLastVisitedField variable keeps track of the last visited table cell component. This variable is copied into the globalFieldCopy variable whenever the user selected context menu action is COPY.
The openPopup(popupId) function uses a JavaScript callback mechanism to receive a user defined argument, the id of the popup to lookup and open, as well as the ADF Faces event object. JavaScript callbacks are a great help when the goal is to write reusable code that could be saved in a JavaScript library. Similar to ADFUtils and ADFFacesUtils, the two helper classes used within Oracle sample applications like Fusion Order Demo (FOD) , you could build a JSUtils as well. The popup is opened in response to a context menu event, which also allows access to the table cell component. This component reference is copied into the globalLastVisitedField variable. The popup then reads the clientId of the table component, which is the absolute component locator id (kind of the address a component has in the rendered table), to then provide this as the alignId for the context menu to open next to the selected table cell.
The copyFromKeyboard method handle the ctrl+shift+c and ctrl+shift+v keyboard short cuts to copy and paste the selected cell value. As an additional argument, it needs the id of the af:serverListener and the component Id of the component that owns the server listener. Interesting for you to read in this function is the way the ADF Faces client side framework supports developers to detect keyboard strokes and the pressed keyboard modifiers through its AdfKeyStroke class..
The copyFromMenu function is called when a user clicks the "Copy" menu option and copies the value held by the globalLastVisitedField into the globalFieldCopy variable.
The pasteFromMenu function is called when the user selects the "Paste" option from the context menu and calls, like copyFromKeyboard in the "Paste" case, calls the copyValueToSelectedRows function.
The copyValueToSelectedRows function is called from both "Paste" functions (the menu and the keyboard) and uses the af:serverListener to queue a custom event to the server. The information that is passed from the client to the server contains the column name and the rowkey of the table cell to copy the value from. Another information that may be useful on the server is the clientId of the cell renderer component that you can get by calling getClientId() on the JavaScript component handle. A use case for passing the clientId is to explicitly set the focus back on the selected component, which is not required in the sample provided with this article.
/*
* A global variable that holds the cell handler of the table cell that
* we want to copy to other rows
*/
var globalFieldCopy = null;
var globalLastVisitedField = null;
/*
* Function is called to open a context menu dialog next to the
* selected table cell. It also saves the selected text field
* component reference for later use when pasting the value to
* selected table rows
*/
function openPopup(popupId){
return function(evt){
evt.cancel();
//get the field reference to copy value from
txtField = evt.getSource();
//just temporarily remember the field that had focus
//when the popup menu opened. This is to ensure that
//fields are only copied when the Copy context menu
//option is used
globalLastVisitedField = txtField;
//the context popup menu should be launched in the table next
//to the selected table cell. For this we need to get the cell
//handler component's clientId
var clientId = txtField.getClientId();
//search popup from page root
var popup = AdfPage.PAGE.findComponentByAbsoluteId(popupId);
//align popup so it renders after the textfield
var hints = {align:"end_before", alignId:clientId};
popup.show(hints);
}
}
/*
* As an alternative - and probably more convenient option to copy and paste
* cell values to other rows - we provide a keyboard option to use instead of
* the context menu.
*
* ctrl+shift+c copies the field to copy the value from.
* ctrl+shift+v copies the saved value to all selected fields
*
* The serverListenerId argument is the name of the af:serverListener component. The
* serverListenerOwnerComponentId is the ID of the UI component that has the server listener
* defined as a child component.
*/
function copyFromKeyboard(serverListenerId, serverListenerOwnerComponentId){
return function(evt){
//the keyboard event gives us the keycode and the modifier keys the
// user pressed
var keyPressed = evt.getKeyCode();
var modifier = evt.getKeyModifiers();
//copy if ctrl+shift key is pressed together with the c-key
var shiftCtrlKeyPressed = AdfKeyStroke.SHIFT_MASK | AdfKeyStroke.CTRL_MASK;
if (modifier == shiftCtrlKeyPressed){
if(keyPressed == AdfKeyStroke.C_KEY){
//copy the selected field to paste values from
globalFieldCopy= evt.getSource();
//cancel keyboard event
evt.cancel();
}
//paste
else if(keyPressed == AdfKeyStroke.V_KEY){
if(globalFieldCopy == null){
//no value copied
alert("No value copied. Please copy value first: Use ctrl+shift+c");
evt.cancel();
}
else{
//handle paste
copyValueToSelectedRows(serverListenerId, serverListenerOwnerComponentId);
evt.cancel();
}
}
}
}
}
//Function referenced from the clientListener on the copy menu option
function copyFromMenu(evt){
//copy the last visited field to the variable used to copy values from. This
//step is required to ensure the field is available when copy is invoked from
//popup
if(globalLastVisitedField != null){
globalFieldCopy = globalLastVisitedField;
}
else{
alert("Problem: No field could be identified to be in focus");
}
//cancel keyboard event
evt.cancel();
}
//Function referenced from the clientListener on the copy menu option
function pasteFromMenu(serverListenerId, serverListenerOwnerComponentId){
return function(evt){
if(globalFieldCopy == null){
//no value copied
alert("No value copied. Please copy value first");
evt.cancel();
}
else{
//handle paste
copyValueToSelectedRows(serverListenerId, serverListenerOwnerComponentId);
evt.cancel();
}
}
}
/*
* Function that queues a custom event to be handled by a managed bean on the server
* side. Note that having the copy and paste action handled on the server is more
* robust than doing the same on the client.
*/
function copyValueToSelectedRows(serverListenerId, serverListenerOwnerComponentId) {
var txtField = globalFieldCopy;
//get the name of the column which row cell to read and write to
var column = txtField.getProperty('colname');
//get the index of the row to copy values from
var rowKeyIndx = txtField.getProperty('rwKeyIndx');
var submittedValue = txtField.getSubmittedValue();
var serverListenerHolder = AdfPage.PAGE.findComponentByAbsoluteId(serverListenerOwnerComponentId);
AdfCustomEvent.queue(
//reference the component that has the server listener
//defined.
serverListenerHolder,
//specify server listener to invoke
serverListenerId,
// Send two parameters. The format of this message is
//a JSON map, which on the server side Java code becomes
//a java.util.Map object
{column:column, fieldValue:submittedValue, rowKeyIndex:rowKeyIndx},
// Make it "immediate" on the server
true);
//reset field value
globalFieldCopy = null;
}
Hint: A useful tool when programming JavaScript is the Firebug plugin in Firefox, which is a rock star when it comes to debugging. Even if you are deploying on IE for production, Firefox is a must have during development just for Firebug.
The server listener component allows developers to call server side Java from JavaScript on the client. In this example, the server listener calls the copyValueToSelectedRows method, passing the rowkey and the column name of the table cell to copy from. The method then reads the table cell value from the ADF Faces table to then iterate over the selected table rows to update the row attribute with the copied value. Optionally, and only when the business service is not ADF Business Components, you may call a merge or persist function to save the value changes in the business service.
The real work, the update of the table rows, is done in the private updateSelectedTableRows method. At the end of the method, a partial refresh is executed to show the updated table rows. Note that tables in ADF Faces are stamped so there is no way to just refresh the updated table rows. Interesting in the updateSelectedTableRows method is the use of DCDataRow, which may look strange for the ADF Business Components developers among the readers, because they are used to cast the ADF iterator rows to oracle.jbo.Row. DCDataRow is the implementation independent alternative and can be used with any DataControl, which is a benefit if you develop application code that is for reuse on other projects, which may not use ADF Business Components as a business service. Both, oracle,jbo.Row and DCDataRow extend RowImpl and expose the same set of common methods.
import java.util.Iterator;
import java.util.List;
import oracle.adf.model.BindingContext;
import oracle.adf.model.bean.DCDataRow;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.render.ClientEvent;
import oracle.binding.OperationBinding;
import oracle.jbo.uicli.binding.JUCtrlHierNodeBinding;
import org.apache.myfaces.trinidad.model.RowKeySet;
/**
* Bean that handles the POJO model update
*/
public class EmployeesPageBean {
private RichTable employeeTable1;
public EmployeesPageBean() {
}
public void setEmployeeTable1(RichTable employeeTable1) {
this.employeeTable1 = employeeTable1;
}
public RichTable getEmployeeTable1() {
return employeeTable1;
}
/**
* Method called from the serverListener on the page. The values that are passed
* by the ClientEvent object is customizable and in this sample include the row
* index and the cell attribute name to copy and paste values from. You could also
* pass the component clientId so that the managed bean e.g. could set the focus
* back if needed
* @param ce - Event object passed from the client to the server through the af:serverListener. The event object
* contains the message payload and a reference to the source invoking the server listener.
*/
public void copyValueToSelectedRows(ClientEvent ce){
String columnToUpdate = (String) ce.getParameters().get("column");
RichTable table = this.getEmployeeTable1();
//important: to avoid an exception in the RowChangeManager, you need to copy the current row key
//and keep it in a local variable
Object oldKey = table.getRowKey();
try {
//get the row index of the table cell to copy from
int rowKeyIndex = ((Double)ce.getParameters().get("rowKeyIndex")).intValue();
//call a private method to update the selected rows
updateSelectedTableRows(columnToUpdate, rowKeyIndex);
}
catch(Exception e){
e.printStackTrace();
}
finally {
//whatever happened, set the current row back to the copied rowkey. This is needed for the
//RowManager to work in ADF Faces tables
table.setRowKey(oldKey);
}
}
/**
* Method that identifies the table row to copy the cell value from to then copy
* the value to all selected table rows. Optionally, at the end of ths method you
* then update the POJO model (which is an action not required if you use ADF BC
* because the binding layer is updated and within the next submit automatically
* updates the ADF BC model. However, this sample uses a POJO model and as such
* we perform the update
* @param column The attribute name to copy the values from and paste them to
* @param rowKeyIndex the row index of the ADF binding row to copy from. This is used
* if you want to copy the values from the ADF binding layer and not
* use the value from the browser client. Its also the default in this
* sample.
*/
private void updateSelectedTableRows(String column, int rowKeyIndex){
RichTable table = this.getEmployeeTable1();
/*
* 1. Get access to the copied cell data. This information can be accessed directly
* on the ADF Faces table or through the binding layer.
*/
//set current table row to copy source
table.setRowIndex(rowKeyIndex);
JUCtrlHierNodeBinding rowBinding = (JUCtrlHierNodeBinding) table.getRowData();
/* DCDataRow extends ViewRowImpl, which extends RowImpl that is used with ADF
* BC View Objects and Entity Objects. This means that DCDataRow is the class
* to use if your code needs to run with ADF BC and non-ADF BC business services
*/
DCDataRow rowToCopyFrom = (DCDataRow) rowBinding.getRow();
Object copyValue = rowToCopyFrom.getAttribute(column);
//* END OF OPTIONAl
/*
* 2. Copy the data to the selected table rows. Here we have two options: paste
* the value to the ADF Faces table or access the ADF binding layer (iterator).
*/
RowKeySet selectedRowKeySet = table.getSelectedRowKeys();
Iterator selectedRowKeySetIter = selectedRowKeySet.iterator();
while (selectedRowKeySetIter.hasNext()){
List key = (List) selectedRowKeySetIter.next();
//make row current in table
table.setRowKey(key);
JUCtrlHierNodeBinding selectedRowBinding = (JUCtrlHierNodeBinding) table.getRowData();
DCDataRow rowToUpdate = (DCDataRow) selectedRowBinding.getRow();
//copy the value from one attribute to the current selected
rowToUpdate.setAttribute(column, copyValue);
/*
* 3. So far we did update the ADF iterator, which is sufficient if you
* use ADF BC because of its active data model. Other business services
* expose methods to persist changes, which needs to be explicitly called.
*
* Note that you can only persist rows that are complete and don't miss
* required values. In this sample, we update existing rows only so that
* it is safe to update.
*/
BindingContext bctx = BindingContext.getCurrent();
DCBindingContainer bindings = (DCBindingContainer) bctx.getCurrentBindingsEntry();
//method to update the POJO model. Note that for Pojo, EJB and WS models,
//you need to explicity calls a method to merge (update) or persist (commit)
//objects
OperationBinding mergeOperation = bindings.getOperationBinding("mergeEmployee");
//Since we use POJOs we need to pass the "real" object, which we get from the
//DataProvider of the row. The same is required for Web Services, EJB/JPA etc.
mergeOperation.getParamsMap().put("emp", rowToUpdate.getDataProvider());
//execute the method for update
mergeOperation.execute();
//any errors ?
if(mergeOperation.getErrors().size() > 0){
//print first error message
System.out.println("An Error occured when updating row: " +
mergeOperation.getErrors().get(0));
}
}
//PPR the table to display copied values
AdfFacesContext adffctx = AdfFacesContext.getCurrentInstance();
adffctx.addPartialTarget(table);
}
}
You can download the Oracle JDeveloper 11g (11.1.1.3, also known as PS1 R2) sample workspace
from here. No configuration is required as the model is POJO based and all data is contained in the model classes. When the table is rendered, use the context menu or the keyboard combination ctrl+shift+c to copy a value and the context menu or ctrl+shift.p to paste the value.
false ,,,,,,,,,,,,,,,false ,,,,,,,,,,,,,,, | http://www.oracle.com/technetwork/developer-tools/jdev/index-096506.html | CC-MAIN-2016-26 | refinedweb | 3,769 | 54.22 |
Hello all,
I'm a new member and relatively new to Java; I took two years in high school but that was about four years ago. I'm making a turn based strategy game based on Final Fantasy Tactics and I'm trying to make a system that will read in the speeds for each character and then (for the time being) just spit it back out, with hopes that I might eventually have it process the speeds and create a fluid and variable system that allows for applying multipliers like haste/slow/stop and such.
Right now, though, the issue is that when you input a value in the main argument (the for loop after I instantiate "print") it reads several lines at a time and then outputs numbers that have nothing to do with those input. If that's not a good explanation, running it and throwing in some junk numbers will make the problem quickly apparent. My code looks solid to my atrophied debugging skills and I can't for the life of me figure out why the input is so broken... the code is below and anyone who can offer me any pointers (related to the specific problem or not) would make my day in doing so.
Code :
import java.io.*; public class turnOrder { public static int[] speeds = new int[14]; //the values for the speed of each character public static int[] ct = new int[14]; //how close each character is to getting a turn public static String[] names = {"Red Hume","Red Moogle", "Red Viera", "Red NuMou", "Red Bangaa", "Red Seeq", "Red Summon", "Blue Hume", "Blue Moogle", "Blue Viera", "Blue Scamron" ,"Blue NuMou", "Blue Bangaa", "Blue Seeq", "Blue Summon"}; public static void main(String[] args) throws IOException { int print; //for loop for (print=0;print<12;print++){ System.out.println("Input speed for "+ names[print]); speeds[print]=System.in.read();} //requests and reads in all the speeds for each character speeds[12]=0; //this space reserved for beastmaster class summons speeds[13]=0; //this space reserved for beastmaster class summons for (print=0;print<12;print++) System.out.println("Speed for "+ names[print] + " is " + speeds[print]); } public void haste (int multiplier, int index) { speeds[index]*=multiplier; //needs a way to make the haste count down automatically? Perhaps instantiate a count variable and implement a for or while loop // keep track of how many turns haste has left, and as long as haste has at least a turn left, keep the speeds[index]*=multiplier up /* * int count; * while (count > 0){ * if (count = 0) * xxxx * } */ } public void turns() { int a; //for loop int turnindex=-1; //set to a positive when a unit reaches 1000CT, otherwise stays -1 for (a=0; a<15; a++) { //loop cycles through the indexes of ct and adds the corresponding speed values, just once ct[a]+=speeds[a]; //will likely need to run 10-12 times before anyone gets a turn System.out.println("Turn has ended"); if (ct[a]>999) //at the end of each run, if nothing printed (such as a unit getting a turn) run again turnindex=a; //once a unit gets a turn, break and wait for a prompt to continue or to set a character's speed or CT } if (turnindex>0){ System.out.println(names[turnindex]+" gets a turn!"); ct[turnindex]=0; turnindex=-1;} } public void summon(int speed, boolean blueteam) { int x=0; if (blueteam = true) x+=1; ct[12+x]=0; //resets the summoned monster's CT speeds[12+x]=speed; //sets index 12 or 13 to the given speed depending on summoned monster's allegiance } public void setSpeed(int speed, int index) { //reads from console to set one character's speed } public void setCT (int index) { ct[index]=0; } } | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/34770-help-broken-loop-printingthethread.html | CC-MAIN-2015-11 | refinedweb | 624 | 51.45 |
Flask. While Flask can be used for building complex, database-driven websites, starting with mostly static pages will be useful to introduce a workflow, which we can then generalize to make more complex pages in the future. Upon completion, you'll be able to use this sequence of steps to jumpstart your next Flask app.
Installing Flask
Before getting started, we need to install Flask. Because systems vary, things can sporadically go wrong during these steps. If they do, like we all do, just Google the error message or leave a comment describing the problem.
Install virtualenv
Virtualenv is a useful tool that creates isolated Python development environments where you can do all your development work.
We'll use virtualenv to install Flask. Virtualenv is a useful tool that creates isolated Python development environments where you can do all your development work. Suppose you come across a new Python library that you'd like to try. If you install it system-wide, there is the risk of messing up other libraries that you might have installed. Instead, use virtualenv to create a sandbox, where you can install and use the library without affecting the rest of your system. You can keep using this sandbox for ongoing development work, or you can simply delete it once you've finished using it. Either way, your system remains organized and clutter-free.
It's possible that your system already has virtualenv. Refer to the command line, and try running:
$ virtualenv --version
If you see a version number, you're good to go and you can skip to this "Install Flask" section. If the command was not found, use
easy_install or
pip to install virtualenv. If running Linux or Mac OS X, one of the following should work for you:
$ sudo easy_install virtualenv
or:
$ sudo pip install virtualenv
or:
$ sudo apt-get install python-virtualenv
If you don't have either of these commands installed, there are several tutorials online, which will show you how to install it on your system. If you're running Windows, follow the "Installation Instructions" on this page to get
easy_install up and running on your computer.
Install Flask
After installing
virtualenv, you can create a new isolated development environment, like so:
$ virtualenv flaskapp
Here,
virtualenv creates a folder, flaskapp/, and sets up a clean copy of Python inside for you to use. It also installs the handy package manager,
pip.
Enter your newly created development environment and activate it so you can begin working within it.
$ cd flaskapp $ . bin/activate
Now, you can safely install Flask:
$ pip install Flask
Setting up the Project Structure
Let's create a couple of folders and files within flaskapp/ to keep our web app organized.
. . ├── app │ ├── static │ │ ├── css │ │ ├── img │ │ └── js │ ├── templates │ ├── routes.py │ └── README.md
Within flaskapp/, create a folder, app/, to contain all your files. Inside app/, create a folder static/; this is where we'll put our web app's images, CSS, and JavaScript files, so create folders for each of those, as demonstrated above. Additionally, create another folder, templates/, to store the app's web templates. Create an empty Python file routes.py for the application logic, such as URL routing.
And no project is complete without a helpful description, so create a README.md file as well.
Now, we know where to put our project's assets, but how does everything connect together? Let's take a look at "Fig. 1" below to see the big picture:
Fig. 1
- A user issues a request for a domain's root URL
/to go to its home page
- routes.py maps the URL
/to a Python function
- The Python function finds a web template living in the templates/ folder.
- A web template will look in the static/ folder for any images, CSS, or JavaScript files it needs as it renders to HTML
- Rendered HTML is sent back to routes.py
- routes.py sends the HTML back to the browser
We start with a request issued from a web browser. A user types a URL into the address bar. The request hits routes.py, which has code that maps the URL to a function. The function finds a template in the templates/ folder, renders it to HTML, and sends it back to the browser. The function can optionally fetch records from a database and then pass that information on to a web template, but since we're dealing with mostly static pages in this article, we'll skip interacting with a database for now.
Now that we know our way around the project structure we set up, let's get started with making a home page for our web app.
Creating a Home Page
When you write a web app with a couple of pages, it quickly becomes annoying to write the same HTML boilerplate over and over again for each page. Furthermore, what if you need to add a new element to your app, such as a new CSS file? You would have to go into every single page and add it in. This is time consuming and error prone. Wouldn't it be nice if, instead of repeatedly writing the same HTML boilerplate, you could define your page layout just once, and then use that layout to make new pages with their own content? This is exactly what web templates do!
Web templates are simply text files that contain variables and control flow statements (
if..else,
for, etc), and end with an
.htmlor
.xmlextension.
The variables are replaced with your content, when the web template is evaluated. Web templates remove repetition, separate content from design, and make your application easier to maintain. In other, simpler words, web templates are awesome and you should use them! Flask uses the Jinja2 template engine; let's see how to use it.
As a first step, we'll define our page layout in a skeleton HTML document layout.html and put it inside the templates/ folder:
app/templates/layout.html
<!DOCTYPE html> <html> <head> <title>Flask App</title> </head> <body> <header> <div class="container"> <h1 class="logo">Flask App</h1> </div> </header> <div class="container"> {% block content %} {% endblock %} </div> </body> </html>
This is simply a regular HTML file...but what's going on with the
{% block content %}{% endblock %} part? To answer this, let's create another file home.html:
app/templates/home.html
{% extends "layout.html" %} {% block content %} <div class="jumbo"> <h2>Welcome to the Flask app<h2> <h3>This is the home page for the Flask app<h3> </div> {% endblock %}
The file layout.html defines an empty block, named
content, that a child template can fill in. The file home.html is a child template that inherits the markup from layout.html and fills in the "content" block with its own text. In other words, layout.html defines all of the common elements of your site, while each child template customizes it with its own content.
This all sounds cool, but how do we actually see this page? How can we type a URL in the browser and "visit" home.html? Let's refer back to Fig. 1. We just created the template home.html and placed it in the templates/ folder. Now, we need to map a URL to it so we can view it in the browser. Let's open up routes.py and do this:
app/routes.py
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') if __name__ == '__main__': app.run(debug=True)
That's it for
routes.py. What did we do?
- First. we imported the Flask class and a function
render_template.
- Next, we created a new instance of the Flask class.
- We then mapped the URL
/to the function
home(). Now, when someone visits this URL, the function
home()will execute.
- The function
home()uses the Flask function
render_template()to render the home.html template we just created from the templates/ folder to the browser.
- Finally, we use
run()to run our app on a local server. We'll set the
debugflag to
true, so we can view any applicable error messages if something goes wrong, and so that the local server automatically reloads after we've made changes to the code.
We're finally ready to see the fruits of our labor. Return to the command line, and type:
$ python routes.py
Visit in your favorite web browser.
When we visited, routes.py had code in it, which mapped the URL
/ to the Python function
home() found the web template home.html in the templates/ folder, rendered it to HTML, and sent it back to the browser, giving us the screen above.
Pretty neat, but this home page is a bit boring, isn't it? Let's make it look better by adding some CSS. Create a file, main.css, within static/css/, and add these rules:
static/css/main.css
body { margin: 0; padding: 0; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #444; } /* * Create dark grey header with a white logo */ header { background-color: #2B2B2B; height: 35px; width: 100%; opacity: .9; margin-bottom: 10px; } header h1.logo { margin: 0; font-size: 1.7em; color: #fff; text-transform: uppercase; float: left; } header h1.logo:hover { color: #fff; text-decoration: none; } /* * Center the body content */ .container { width: 940px; margin: 0 auto; } div.jumbo { padding: 10px 0 30px 0; background-color: #eeeeee; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } h2 { font-size: 3em; margin-top: 40px; text-align: center; letter-spacing: -2px; } h3 { font-size: 1.7em; font-weight: 100; margin-top: 30px; text-align: center; letter-spacing: -1px; color: #999; }
Add this stylesheet to the skeleton file layout.html so that the styling applies to all of its child templates by adding this line to its <head> element:
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">;
We're using the Flask function,
url_for, to generate a URL path for main.css from the static folder. After adding this line in, layout.html should now look like:
app/templates/layout.html
<!DOCTYPE html> <html> <head> <title>Flask</title> <strong><link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"></strong> </head> <body> <header> <div class="container"> <h1 class="logo">Flask App</h1> </div> </header> <div class="container"> {% block content %} {% endblock %} </div> </body> </html>
Let's switch back to the browser and refresh the page to view the result of the CSS.
That's more like it! Now, when we visit, routes.py still maps the URL
/ to the Python function
home(), and
home() still finds the web template home.html in the templates/ folder. But, since we added the CSS file main.css, the web template home.html looks in static/ to find this asset, before rendering to HTML and being sent back to the browser.
We've achieved a lot so far. We started with Fig. 1 by understanding how Flask works, and now we've seen how it all plays out, by creating a home page for our web app. Let's move on and create an About page.
Creating an About Page
In the previous section, we created a web template home.html by extending the skeleton file layout.html. We then mapped the URL
/ to home.html in routes.py so we could visit it in the browser. We finished things up by adding some styling to make it look pretty. Let's repeat that process again to create an about page for our web app.
We'll begin by creating a web template, about.html, and putting it inside the templates/ folder.
app/templates/about.html
{% extends "layout.html" %} {% block content %} <h2>About</h2> <p>This is an About page for the Intro to Flask article. Don't I look good? Oh stop, you're making me blush.</p> {% endblock %}
Just like before with home.html, we extend from layout.html, and then fill the
content block with our custom content.
In order to visit this page in the browser, we need to map a URL to it. Open up routes.py and add another mapping:
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/about') def about(): return render_template('about.html') if __name__ == '__main__': app.run(debug=True)
We mapped the URL
/about to the function
about(). Now we can open up the browser and go to and check out our newly created page.
Adding Navigation
Most websites have links to their main pages within the header or footer of the document. These links are usually visible across all pages of a website. Let's open up the skeleton file, layout.html. and add these links so they show up in all of the child templates. Specifically, let's add a <nav> element inside the <header> element:
app/templates/layout.html
... <header> <div class="container"> <h1 class="logo">Flask App</h1> <strong><nav> <ul class="menu"> <li><a href="{{ url_for('home') }}">Home</a></li> <li><a href="{{ url_for('about') }}">About</a></li> </ul> </nav></strong> </div> </header> ...
Once again, we use the Flask function
url_for to generate URLs.
Next, add some more style rules to main.css to make these new navigation elements look good:
app/static/css/main.css
... /* * Display navigation links inline */ .menu { float: right; margin-top: 8px; } .menu li { display: inline; } .menu li + li { margin-left: 35px; } .menu li a { color: #999; text-decoration: none; }
Finally, open up the browser and refresh to see our newly added navigation links.
Conclusion
Over the course of this article, we built a simple web app with two, mostly static, pages. In doing so, we learned a workflow that can be used to create more complex websites with dynamic content. Flask is a simple, but powerful framework that enables you to efficiently build web apps. Go ahead - check it out!
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://code.tutsplus.com/tutorials/an-introduction-to-pythons-flask-framework--net-28822 | CC-MAIN-2018-22 | refinedweb | 2,332 | 75.71 |
Ngl.betainc
Evaluates the incomplete beta function.
Available in version 1.3.0 or later.
Prototype
alpha = Ngl.betainc(x, a, b)
Argumentsx
Numpy or masked array representing upper limit of integration. x must be [0,1].a
First beta distribution parameter; must be > 0.0, and the same dimensionality as x.b
Second beta distribution parameter; must be > 0.0, and the same dimensionality as x.
Return valuealpha
An numpy or masked array is returned (depending on type of x), of the same size as x. If x is a masked array, then alpha will contain missing values in the same locations.
Description
Ngl.betainc calculates the incomplete beta function. The incomplete beta function ratio is the probability that a random variable from a beta distribution having parameters a and b will be less than or equal to x. The code used is from SLATEC (). This returns the same answers as the Numerical Recipes [Cambridge Univ. Press, 1986] function betai.
This function is often used to determine probabilities.
Examples
Example 1
import Ngl a = 0.5 b = 5.0 x = 0.2 alpha = Ngl.betainc(x,a,b) print "alpha(x,a,b) = ",alpha x = 0.5 alpha = Ngl.betainc(x,a,b) print "alpha(x,a,b) = ",alphaThe result is:
alpha(x,a,b) = [ 0.85507239] alpha(x,a,b) = [ 0.98988044]Example 2
Say a calculation has been made where the degrees-of-freedom (df=20) and a Student-t value of 2.08 has been determined. A significance level may be determined via:
import Ngl df = 20. tval = 2.09 prob = Ngl.betainc( df/(df+tval**2), df/2.0, 0.5) print "prob = ",probThe result is prob = 0.04959886, meaning the test is significant at the one-sided 5% (two-sided 2.5%) level. For plotting, users often prefer to plot the quantity:
prob = (1.-Ngl.betainc(x,a,b))*100. # probability in % | http://www.pyngl.ucar.edu/Functions/Ngl.betainc.shtml | crawl-001 | refinedweb | 318 | 55.3 |
Data migration utilities
Project description
Data migration in Python
Example
Odo migrates data between different containers
>>> from odo import odo >>> odo((1, 2, 3), list) [1, 2, 3]
It operates on small, in-memory containers (as above) and large, out-of-core containers (as below)
>>> odo('myfile.hdf5::/data', 'postgresql://user:pass@host::my-table') Table('my-table', MetaData(bind=Engine(postgresql://user:****@host)), ...)
Odo leverages the existing Python ecosystem. The example above uses sqlalchemy for SQL interation and h5py for HDF5 interaction.
Method
Odo migrates data using network of small data conversion functions between type pairs. That network is below:
Each node is a container type (like pandas.DataFrame or sqlalchemy.Table) and each directed edge is a function that transforms or appends one container into or onto another. We annotate these functions/edges with relative costs.
This network approach allows odo to select the shortest path between any two types (thank you networkx). For performance reasons these functions often leverage non-Pythonic systems like NumPy arrays or native CSV->SQL loading functions. Odo is not dependent on only Python iterators.
This network approach is also robust. When libraries go missing or runtime errors occur odo can work around these holes and find new paths.
This network approach is extensible. It is easy to write small functions and register them to the overall graph. In the following example showing how we convert from pandas.DataFrame to a numpy.ndarray.
from odo import convert @convert.register(np.ndarray, pd.DataFrame, cost=1.0) def dataframe_to_numpy(df, **kwargs): return df.to_records(index=False)
We decorate convert functions with the target and source types as well as a relative cost. This decoration establishes a contract that the underlying function must fulfill, in this case with the fast DataFrame.to_records method. Similar functions exist for append, to add to existing data, and resource for URI resolution.
- convert: Transform dataset into new container
- append: Add dataset onto existing container
- resource: Given a URI find the appropriate data resource
- odo: Call one of the above based on inputs. E.g. odo((1, 2, 3), list) -> convert(list, (1, 2, 3)) while L = []; odo((1, 2, 3), L) -> append(L, (1, 2, 3))
Finally, odo is also aware of which containers must reside in memory and which do not. In the graph above the red-colored nodes are robust to larger-than-memory datasets. Transformations between two out-of-core datasets operate only on the subgraph of the red nodes.
LICENSE
New BSD. See License File.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/odo/0.5.0/ | CC-MAIN-2021-10 | refinedweb | 443 | 58.58 |
Microsoft Office Tutorials and References
In Depth Information
Table 26-4. The XPath Object’s Properties and Methods
Name
Description
Property
Map
A read-only property that returns the XmlMap object that
represents the schema assigned to the XPath object.
Repeating
A read-only Boolean value that returns True if the XPath object is
assigned to a list, or returns False if the object is assigned to a
single cell.
Value
Returns a string that represents the XPath for the object.
Method
Clear
Clears the schema mapping from the cell or cells mapped to the
specified XPath .
SetValue(Map, XPath,
SelectionNamespace,
Repeating)
The Map argument (required) is an XmlMap variable representing
the schema map into which you’ll import your XML data; XPath
(required) is a valid XPath statement; SelectionNamespace (an
optional variant) specifies any namespace prefixes (you can
leave this argument out if you put the full XPath in the XPath
argument); Repeating (an optional Boolean) indicates whether
the XPath object should be mapped to a single cell ( False ) or to a
column in the list ( True ).
For more (and very technical) information on the XML Path language, visit the official XPath Web site at .
The XPath object’s SetValue method is the most important method in the bunch—it lets you
map a schema element directly to a cell or range. The following procedure defines the data
file that contains the XML data, assigns the schema to be used in the SetValue method calls to
the myMap object variable, and maps the elements to specific ranges. The result of the pro
cedure is shown in Figure 26-7.
Warning This procedure will only run correctly if you have previously mapped the
MySuppliers.xsd schema to the active workbook. You can do so by running the ApplySchema
procedure from the “Mapping a Schema to a Worksheet Programmatically” section found
earlier in this chapter or by mapping the schema to your workbook manually.
Sub AssignElementsToRanges()
Dim myMap As XmlMap
Dim strXPath As String
Dim strSelNS As String
Dim xMapName As String
Dim xDataFile As String
Search JabSto ::
Custom Search | http://jabsto.com/Tutorial/topic-110/Microsoft-Office-Excel-2003-Programming-582.html | CC-MAIN-2018-51 | refinedweb | 349 | 55.37 |
Introduction
Hello again! As you may know, I always endeavour to write about topics that are interesting and fun. As you may also know: I love games—in another life, I would have been a game developer, but so much has changed since I have tried getting into the gaming development environment.
If you have been following my articles (or at least some!), you would know that I have written about a lot of games, mostly games involving logic. Lately, I have been writing about card games, because, well, there are only so many other games I can cover and remember. Today's topic also covers a card game known as Card Wars.
Card Wars.
If the cards shown are of the same value, a little face-off or a mini-war happens. The players should then place their next cards face down and then another card face-up. The player with the highest card wins the war and takes the other player's card. When a player runs out of cards, he or she loses.
Our Project
The little application that you will create today is very basic, which is the best way to learn game logic. If you do not understand how certain games work in the background and the logic to make it work, programming any game is difficult. We'll make this a two-player game, for simplicity's sake.
Open Visual Studio and create a Console application in either VB.NET or C#.
In the Main method of your application, create the following variables:
C#
int intUCard; int intCCard; int intUTot = 0; int intCTot = 0; int intSuit; int intCount = 0; string strUSuit; string strCSuit; string strUCard; string strCCard; string strResult = "";
VB.NET
Dim intUCard As Integer Dim intCCard As Integer Dim intUTot As Integer = 0 Dim intCTot As Integer = 0 Dim intSuit As Integer Dim intCount As Integer = 0 Dim strUSuit As String Dim strCSuit As String Dim strUCard As String Dim strCCard As String Dim strResult As String = ""
Here, I created objects to hold the User's and Computer's chosen cards and totals. The other variables include the chosen suit and result. Still in the Main method, add the last few variables.
C#
string[] strCardNames = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" }; string[] strCardSuits = { "Clubs", "Diamonds", "Hearts", "Spades" }; string[] strDrawnCards = new string[52]; int[] intDeck = new int[52];
VB.NET
Dim strCardNames As String() = {"Ace", "2", "3", "4", "5", _ "6", "7", "8", "9", "10", "Jack", "Queen", "King"} Dim strCardSuits As String() = {"Clubs", "Diamonds", _ "Hearts", "Spades"} Dim strDrawnCards As String() = New String(51) {} Dim intDeck As Integer() = New Integer(51) {}
The last few variables contain the card names, suit, a Deck object, and a variable to host the drawn cards. Add the following line of code inside your Main method:
C#
Shuffle(ref intDeck);
VB.NET
Shuffle(intDeck)
This line calls the procedure named Shuffle. Let's add it now.
C#
private static void Shuffle(ref int[] Deck) { int c; Random rndCards = new Random(); for (c = 0; c < 52; c++) { Deck[c] = rndCards.Next(1, 52); } }
VB.NET
Private Sub Shuffle(ByRef Deck As Integer()) Dim c As Integer Dim rndCards As Random = New Random() For c = 0 To 52 - 1 Deck(c) = rndCards.[Next](1, 52) Next End Sub
Aptly named, the Shuffle sub procedure stores the cards inside the deck at randomly generated locations. Back in the Main method, add the next For loop underneath the call to the Shuffle procedure.
C#
for (int x = 0; x < 26; x++) { intUCard = ChooseCard(intDeck, ref intCount, out intSuit); strUSuit = strCardSuits[intSuit]; strUCard = strCardNames[intUCard]; intCCard = ChooseCard(intDeck, ref intCount, out intSuit); strCSuit = strCardSuits[intSuit]; strCCard = strCardNames[intCCard]; if (intUCard > intCCard) { intUTot += 1; strResult = "User wins."; } else if (intUCard < intCCard) { intCTot += 1; strResult = "Computer wins."; } else if (intUCard == intCCard) { intUTot += 1; intCTot += 1; strResult = "Tie."; }(); }
VB.NET
For x As Integer = 0 To 25 intUCard = ChooseCard(intDeck, intCount, intSuit) strUSuit = strCardSuits(intSuit) strUCard = strCardNames(intUCard) intCCard = ChooseCard(intDeck, intCount, intSuit) strCSuit = strCardSuits(intSuit) strCCard = strCardNames(intCCard) If intUCard > intCCard Then intUTot += 1 strResult = "User wins." ElseIf intUCard < intCCard Then intCTot += 1 strResult = "Computer wins." ElseIf intUCard = intCCard Then intUTot += 1 intCTot += 1 strResult = "Tie." End If() Next
The loop loops 26 times, which is 52 divided by 2. Each player (you and the computer) has 26 cards. With the help of the ChooseCard method, a card gets chosen for each player and then the score gets calculated based on the parameters I mentioned earlier. The result of the game gets displayed after each hand. Add the ChooseCard method now.
C#
private static int ChooseCard(int[] Deck, ref int count, out int Suit) { int Card; Card = Deck[count]; count++; Suit = (Card - 1) % 4; return (Card - 1) / 4 + 1; }
VB.NET
Private Function ChooseCard(ByVal Deck As Integer(), ByRef _ count As Integer, <Out> ByRef Suit As Integer) _ As Integer Dim Card As Integer Card = Deck(count) count += 1 Suit = (Card - 1) Mod 4 Return (Card - 1) / 4 + 1 End Function
The ChooseCard method also technically generates a random number based on a calculation that the player will receive.
Running the application will result in what's shown in Figure 1.
Figure 1: Running the game
Conclusion
Each card game has the same components; how you use and manipulate them depends on the logic that goes with the game. Be on the lookout for another game coming soon. Until then, happy coding! | https://mobile.codeguru.com/csharp/.net/net_general/creating-a-card-wars-game-in-.net.html | CC-MAIN-2018-47 | refinedweb | 914 | 61.26 |
bt.If operator/function
Is there a version of
bt.Iffunction that only returns the True value? (instead of the True value or False value)
and
can an indexed value be used within
bt.If?
and
would I be able to call previous occurrences of function result with [-1], [-2], for a strategy?
From the documentation:
class MyStrategy(bt.Strategy): def __init__(self): sma1 = btind.SMA(self.data.close, period=15) high_or_low = bt.If(sma1 > self.data.close, self.data.low, self.data.high)# returns Low if True, High if False sma2 = btind.SMA(high_or_low, period=15)
I would like to use the function/operator like this:
class MyStrategy(bt.Strategy): def __init__(self): sma1 = btind.SMA(self.data.close, period=15) only_low = bt.If(sma1[-2] > self.data.close[-1], self.data.low) # if sma1[-2]>close[-1] then return just the Low value sma2 = btind.SMA(high_or_low, period=15)
and then use it in strategy like this:
def next(self): if only_low[-1]>only_low[-2]: self.buy() # enter long
If
bt.Ifcannot do this, which other function/operator would be able to?
or how would I modify
bt.Ifto do this?
I tried to filter out 2nd result with below, but it does not work:
class MyStrategy(bt.Strategy): def __init__(self): sma1 = btind.SMA(self.data.close, period=15) low_or_9000 = bt.If(sma1[-2] > self.data.close[-1], self.data.low, 9000.0) # if sma1>close ture then return Low, false returns 9000.0 sma2 = btind.SMA(high_or_low, period=15) self.data.only_low = low_or_9000 < 9000.0
@kam-dorra I think this should work in
__init()__:
low_or_9000 = bt.If(sma1(-2) > self.data.close(-1), self.data.low, 9000.0)
- backtrader administrators last edited by
@kam-dorra said in bt.If operator/function:
I tried to filter out 2nd result with below, but it does not work:
Why? You probably want to use what @ab_trader has suggested.
@ab_trader said in bt.If operator/function:
low_or_9000 = bt.If(sma1(-2) > self.data.close(-1), self.data.low, 9000.0)
Wouldn't that create a "line" with the value "9000" in it still?
I would like to create a line from function/operator result without "9000" and a line with only "self.data.low".
You can create the line with only
self.data.lowelements only like this:
self.lows = self.data.low
If you have certain conditions and only part of the new line elements should be equal to
self.data.lowelements, then you need to define a placeholder for missing elements.
Also if you want to pass variables between class methods, then these variables should be defined as
self.variable, but not
variableas in the script above.
And other question on this:
if only_low[-1]>only_low[-2]: self.buy() # enter long
Say element [-2] has no
lowvalue (condition didn't meet) and element[-1] has
lowvalue. What do you expect from the script?
@ab_trader
I have no coding experience at all, everything i've posted here is just what I took from the documentation, so if you have time; could you show me how to only have the
self.data.lowresults in the line?
- how to define a placeholder for 9000?
- how and where do I create a
self.variablethat represents only the True return of a function/operator? in
def __init__(self):?
if only_low[-1]>only_low[-2]: self.buy() # enter long
"Say element [-2] has no low value (condition didn't meet) and element[-1] has low value. What do you expect from the script?"
That statement was just to show I wanted to use the most recent previous low value and the one before that for trading logic; it already assumes I have created a line without the false value (9000)return.
thanks for you help.
- backtrader administrators last edited by backtrader
@kam-dorra said in bt.If operator/function:
I have no coding experience at all
The problem is not there (that's another problem), the problem is understanding why
bt.Ifdelivers two values.
bt.Ifreturns a line. This is just like, for example,
self.data.close.
Which means that for each tick (call iteration if you wish) it has to have a value.
@kam-dorra said in bt.If operator/function:
could you show me how to only have the self.data.low results in the line?
@ab_trader cannot show you that, neither can anyone else, because you cannot have a line that sometimes has values and some other times doesn't. You have something similar if you don't fill the value (which is often done when developing an indicator), because if you skip setting a value, the default value is filled in for you, with the default value bein
NaN(aka "Not a Number" or a default representation in the IEEE Floating Point Standard to indicate that it doesn't represent an actual value)
The thing with
NaNis that it may actually be what you need or it may not. Because, not being a number, arithmetic and logic operations won't work the way you expect them to (they will work, but the result may not match your expectations, which in fact means ... it doesn't work)
Use a well defined floating point value such as
Infor
-Infis better in order to have well defined operations and results. If your problem is the
low, what seems plausible is:
low_or_inf = bt.If(sma1(-2) > self.data.close(-1), self.data.low, float('Inf'))
One can be sure that the
lowwill always be less than
Inf.
Later in your code you can do the following
if low_or_inf[0] < float('Inf') do_something_here()
With that logic implying that if something is less than infinitum ... it has to be
low
Given that your initial statement gave an example
@kam-dorra said in bt.If operator/function:
def next(self): if only_low[-1]>only_low[-2]: self.buy() # enter long
the obvious thing would be
def next(self): if low_or_inf[0] < float('Inf'): if low_or_inf[-1] > low_or_inf[-2]: # this may also be pre-calculated as a line self.buy() # enter long
To pack everything as a line
low_or_inf = bt.If(sma1(-2) > self.data.close(-1), self.data.low, float('Inf')) low_signal = bt.If(low_or_inf < float('Inf'), low_or_inf(-1) > low_or_inf(-2), False)
Later in the code
def next(self): if low_signal[0]: self.buy()
@backtrader
thank you very much for your time and assistance, you have been very helpful. | https://community.backtrader.com/topic/2113/bt-if-operator-function | CC-MAIN-2020-10 | refinedweb | 1,070 | 59.7 |
Intro to Svelte.js
In this tutorial, we are going to learn about a basic introduction to svelte.js.
What is Svelte ?
Svelte is a javascript framework which is used to build fast web applications. Similar to React or Vue but in svelte we don’t need any dependencies in runtime like react or vue takes some time to interpret our code it means in svelte we can get pure JavaScript.
Getting started
Let’s create our first svelte app by running the following commands in your terminal.
npx degit sveltejs/template my-svelte-app && $_
This above command will download the svelte app inside
my-svelte-app folder and change your current working directory to
my-svelte-app
Now we need to install the dependencies by running the below command.
npm install
Let’s run the development server by using the following command.
npm run dev
Now, open your
my-svelte-app folder in your favorite code editor and navigate to src folder where you can see two files
main.js and
App.svelte.
main.js : This is root file which helps us to inject our svelte app into the dom.
import App from './App.svelte'; const app = new App({ target: document.body,}); export default app;
App.svelte : This is root component of the svelte app.
Remove everything inside
App.svelte file and add the below code.
<script> // JavaScript goes here let name = "Hello svelte";</script> <style> //css goes here </style> // markup <div> <h1>This is my first svelte app</h1> //interpolation <p>{name}</p> </div>
In Svelte each component consists of
script,
style and HTML markup.
script: In the script tag, we need to write JavaScript code related to that component
style: In style tag, we need to write CSS code related to that component(styles are scoped by default in svelte).
To interpolate the JavaScript in markup we need to use single curly brace
{name} in svelte.
We can also write JavaScript methods inside the curly brace like
{name.toUpperCase()}. | https://reactgo.com/sveltejs-intro-tutorial/ | CC-MAIN-2019-51 | refinedweb | 333 | 73.68 |
getpass - read a string of characters without echo (LEGACY)
#include <unistd.h> char *getpass(const char *prompt);
The getpass() function opens the process' controlling terminal, writes to that device the null-terminated string prompt, disables echoing, reads a string of characters up to the next newline character or EOF, restores the terminal state and closes the terminal.
This interface need not be reentrant.
Upon successful completion, getpass() returns a pointer to a null-terminated string of at most {PASS_MAX} bytes that were read from the terminal device. If an error is encountered, the terminal state is restored and a null pointer is returned.
The getpass() function may fail if:
- [EINTR]
- The getpass() function was interrupted by a signal.
- [EIO]
- The process is a member of a background process attempting to read from its controlling terminal, the process is ignoring or blocking the SIGTTIN signal or the process group is orphaned. This error may also be generated for implementation-dependent reasons.
- [EMFILE]
- {OPEN_MAX} file descriptors are currently open in the calling process.
- [ENFILE]
- The maximum allowable number of files is currently open in the system.
- [ENXIO]
- The process does not have a controlling terminal.
None.
The return value points to static data whose content may be overwritten by each call.
This function was marked LEGACY since it provides no functionality which a user could not easily implement, and its name is misleading.
None.
<limits.h>, <unistd.h>.
Derived from System V Release 2.0. | http://pubs.opengroup.org/onlinepubs/7990989775/xsh/getpass.html | CC-MAIN-2016-36 | refinedweb | 243 | 54.42 |
By mswatcher
via codeproject.com
Submitted: May 10 / 03:21
I have been playing with LINQ to SQL for a bit, it is great and easy to use along with the designer that ships with VS.NET 2008. so i wanted to create a FACADE layer that integrates with LINQ to SQL classes, the old school way is to create a public class (Manager) and this class calls your Database mappers to get/set the required info, now LINQ TO SQL replaces those mapper classes and the way to do your operations is to open the dataContext and start defining queries to perform such operations. | http://www.dzone.com/links/linq_to_sql_all_common_operations_insertupdatedel.html | crawl-001 | refinedweb | 105 | 54.19 |
The python client for Meilisearch API.
Project description
Meilisearch Python
Meilisearch | Documentation | Slack | Roadmap | Website | FAQ
⚡ The Meilisearch API client written for Python 🐍
Meilisearch Python is the Meilisearch API client for Python developers.
Meilisearch is an open-source search engine. Discover what Meilisearch is!
Table of Contents
- 📖 Documentation
- 🔧 Installation
- 🚀 Getting Started
- 🤖 Compatibility with Meilisearch
- 💡 Learn More
- ⚙️ Development Workflow and Contributing
📖 Documentation
See our Documentation or our API References.
🔧 Installation
Note: Python 3.6+ is required.
With
pip3 in command line:
pip3 install meilisearch
Run Meilisearch
There are many easy ways to download and run a Meilisearch instance.
For example, using the
curl command in your Terminal:
# Install Meilisearch curl -L | sh # Launch Meilisearch ./meilisearch --master-key=masterKey
NB: you can also download Meilisearch from Homebrew or APT or even run it using Docker.
🚀 Getting Started
Add Documents
import meilisearch client = meilisearch.Client('', 'masterKey') # An index is where the documents are stored. index = client.index('movies') documents = [ { 'id': 1, 'title': 'Carol', 'genres': ['Romance', 'Drama'] }, { 'id': 2, 'title': 'Wonder Woman', 'genres': ['Action', 'Adventure'] }, { 'id': 3, 'title': 'Life of Pi', 'genres': ['Adventure', 'Drama'] }, { 'id': 4, 'title': 'Mad Max: Fury Road', 'genres': ['Adventure', 'Science Fiction'] }, { 'id': 5, 'title': 'Moana', 'genres': ['Fantasy', 'Action']}, { 'id': 6, 'title': 'Philadelphia', 'genres': ['Drama'] }, ] # If the index 'movies' does not exist, Meilisearch creates it when you first add the documents. index.add_documents(documents) # => { "uid": 0 }
With the task
uid, you can check the status (
enqueued,
processing,
succeeded or
failed) of your documents addition using the task.
Basic Search
# Meilisearch is typo-tolerant: index.search('caorl')
Output:
{ "hits": [ { "id": 1, "title": "Carol", "genre": ["Romance", "Drama"] } ], "offset": 0, "limit": 20, "processingTimeMs": 1, "query": "caorl" }
Custom Search
All the supported options are described in the search parameters section of the documentation.
index.search( 'phil', { 'attributesToHighlight': ['*'], } )
JSON output:
{ "hits": [ { "id": 6, "title": "Philadelphia", "_formatted": { "id": 6, "title": "<em>Phil</em>adelphia", "genre": ["Drama"] } } ], "offset": 0, "limit": 20, "processingTimeMs": 0, "query": "phil" }
Custom Search With Filters
If you want to enable filtering, you must add your attributes to the
filterableAttributes index setting.
index.update_filterable_attributes([ 'id', 'genres' ])
You only need to perform this operation once.
Note that Meilisearch will rebuild your index whenever you update
filterableAttributes. Depending on the size of your dataset, this might take time. You can track the process using the task.
Then, you can perform the search:
index.search( 'wonder', { filter: ['id > 1 AND genres = Action'] } )
{ "hits": [ { "id": 2, "title": "Wonder Woman", "genres": ["Action","Adventure"] } ], "offset": 0, "limit": 20, "nbHits": 1, "processingTimeMs": 0, "query": "wonder" }
🤖 Compatibility with Meilisearch
This package only guarantees the compatibility with the version v0.27.0 of Meilisearch.
💡 Learn More
The following sections may interest you:
- Manipulate documents: see the API references or read more about documents.
- Search: see the API references or follow our guide on search parameters.
- Manage the indexes: see the API references or read more about indexes.
- Configure the index settings: see the API references or follow our guide on settings parameters.
⚙️ Development Workflow and Contributing
Any new contribution is more than welcome in this project!
If you want to know more about the development workflow or want to contribute, please visit our contributing guidelines for detailed instructions!
Meilisearch provides and maintains many SDKs and Integration tools like this one. We want to provide everyone with an amazing search experience for any kind of project. If you want to contribute, make suggestions, or just know what's going on right now, visit us in the integration-guides repository.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/meilisearch/0.18.3/ | CC-MAIN-2022-27 | refinedweb | 603 | 54.73 |
:
September17
This item is only available as the following downloads:
( PDF )
Full Text
PAGE 1
ERYNWORTHINGTON Staff writerAlocal businesswoman knows first hand how difficult it is for businesses to survive in a semi-rural community during hard economic times. However, she resists the urge to be defeated. New Concepts International Hair Salon owner Sharon Malm is a certified mentor for SCORE and utilizes her knowledge in maintaining her prosperous business. SCORE is a nonprofit association dedicated to helping small businesses get off the ground, grow and achieve their goals through education and mentorship. Malm shared her secrets of success with the Chronicle.CHRONICLE: Tell me about SCORE and what people may not be aware of. MALM: We partner together businesses in the marketplace doing current things with start-up businesses or those needing support. I think the most important thing is that whether it is a start-up business or an existing business that there is help here in Citrus County and it is free and confidential. Business owners might be embarrassed that they are struggling. Listen, all businesses go through struggles at some point in time, whatever the problems are social media, expanding, growth or funding. We also work with the county through the Economic Development Council with POLL SEPTEMBER 2, 2013Floridas Best Community Newspaper Serving Floridas Best CommunityVOL. 119 ISSUE 26 50 CITRUS COUNTYMLB: Struggles continue as Rays swept by As /B1 ONLINE POLL:Your choice?Are you sympathetic to fast-food workers calls to be paid $15 an hour? A.Yes, with huge profits being realized by senior executives, $15 an hour for workers is fair and would stimulate the economy. B.No. Itd put their employers out of business. C.Sort of $15 per hour is reasonable for those who have good evaluations after a year on the job. D.No. Thered be little incentive to advance ones skills if getting paid $15. To vote, visit www. chronicleonline.com. Click on the word Opinion in the menu to see the poll. Results will appear next Monday. Find last weeks online poll results./ Page A3 HIGH89LOW72Scattered storms; rain chance 40%.PAGE A4TODAY& next morning MONDAY 000FXB0 000FXB0 000FXB6 INDEX Blood Drives . . .Ax Classifieds . . . .B7 Comics . . . . .B6 Crossword . . . .B5 Editorial . . . . .A8 Entertainment . . .A4 Food Programs . .Ax Horoscope . . . .A4 Lottery Numbers . .B3 Lottery Payouts . .B3 Movies . . . . .B6 Obituaries . . . .A6 TV Listings . . . .B5 MondayCONVERSATION MONDAY CONVERSATION To hear Sharon Malms inter view, visit www. chronicleonline.com. Is it possible for us as a culture to stop building up celebrities such as Miley Cyrus only to turn on them and tear them down? QUESTION OF THE WEEK Kelley B. DeMaio There was a break in generational education and training when a generation decided that punishing our children was illegal and immoral. Those who agree that spanking is corporal punishment are the reason children and young adults are so out of control these days! ... Elysabeth Henick Its all a desperate cry for attention. Shes not getting it anymore and now everyone is talking about her again. Im sure it was her plan. Ashleigh Priest I think people are under the impression you do something bold, youll get noticed and remembered. I think people in general are taking it to an extreme thats beyond ridiculous. ... We need to stop fueling the fire by paying attention to their bold acts. Its like a toddler throwing a tantrum you ignore it. ... Society emphasizes on the wrong qualities and trends ... rather than focusing on things that truly matter. ... Chris Gangler Actually I blame the media for it with their slavish attention and devotion to all things celebrity. Ironically this question is just one more example of it. Contribute! Like us at facebook.com/ citruscounty chronicle and respond to our Question of the Week. BOCC shifts site for budget hearing CHRISVANORMER Staff writerINVERNESS Expecting a larger-than-capacity turnout to the next county budget hearing, commissioners moved it to the auditorium but the meeting must begin at the courthouse. As of right now that preliminary budget hearing is set for these chambers, said Commission Chairman Joe Meek, speaking at the last commission meeting. That may produce a larger crowd. To try to plan in advance of that, we need to have a discussion as to moving it to the auditorium. Drawing on the experience of the July 23 hearing regarding the proposed $60 annual fee for fire protection services, the Citrus County Board of County Commissioners (BOCC) wanted to be better prepared this time. Residents overwhelmed the courthouse for the fire fee hearing, which had to be recessed and moved to the county auditorium at the county fairgrounds. The auditorium was filled, scores of residents spoke against the amount of the fee and it was dropped to $54. Assistant County Attorney Kerry Parsons advised that auditorium use would ensure that residents would get due process, but Chamber Business Expo slated Saturday PATFAHERTY Staff writerThe Citrus County Chamber of Commerce Business Expo will take place from 9a.m. to 3p.m. Saturday at the Citrus County Auditorium and outside area at the fairgrounds in Inverness. The chamber is encouraging residents and visitors to come out and make a day of it. There will be more than 50 local vendors on hand and live radio broadcasts. Parking and admission are free. Up to 46 booths will be set up inside the auditorium, with additional displays and activities outside. Ten of the booths will be dedicated to local nonprofits that serve county residents. According to the chamber, the essence of the event is to provide a venue for the community to learn more about local resources and shop Citrus County businesses. Jeff Inglehart with the chamber is coordinating the event. He said there will be something for everybody and fun for all ages. This will be like a minifestival, more family oriented, Inglehart said. We will have food Leon McClellans barbecue a pet adoption area, Home Depot projects for kids and Xtreme Fun bounce houses. There will also be a cash money machine booth where a lucky visitor will get the opportunity to step inside and grab as much money as he or she can. The event is being sponsored by Bailey Electric, the Citrus County Chronicle, the Robert Boissoneault Oncology Institute, Suncoast Dermatology, Plantation on Crystal River, WWJB News Radio and Insight Credit Union. Sharon Malm keeping SCORE MATTHEW BECK/ChronicleSharon Malm runs her full-time business, New Concepts Hair Salon, while mentoring other local businesses through SCORE, Services Corps of Retired Executives, and showing how they are able to help grow a business. Businesswoman advocates for business development in Citrus County See MONDAY/ Page A5 WHAT: Citrus County pr eliminary budget hearing. WHEN: 5:30 p .m. Thursday, Sept. 12. WHERE: Citrus County A uditorium, 3610 S. Florida Ave., Inverness. ON THE NET: T he preliminary budget is available online at. See BUDGET/ Page A5
PAGE 2
JEFFBRYAN Riverland NewsIts been 37 years since the King of Rock n Roll died at the age of 42, and its been more than 50 years since Elvis Presley burst onto the music scene with his unique rockabilly sound and style. And while Presley might be gone, his legend and status as a musical icon lives on. Thats evident by the myriad of celebrations surrounding Presley, none more so than the vast array of Elvis Tribute Artists (ETA), including Dunnellons own Cote Deonath. The 16-year-old has long had a local following and is well known as Little Elvis, but the sophomore at Dunnellon High School is quickly gaining nationwide attention and hes not so little anymore. For the first time since beginning his career as an ETA at the age of 5, Deonath performed at the Mecca of all things Elvis Elvis Week, and in of all places, the home of Presley, Memphis, Tenn. The weeklong festival in midAugust coincided with Presleys death in 1977. The scene, Deonath said, was surreal as always, but performing for the first time at the event was mind-boggling. Its very busy, you really have to keep track of the schedule and pay close attention to whats going on around you, he said. And its tough, because its like nothing Ive experienced before since Ive been doing this. Deonath has experienced nerves, but nothing braced him for preparing under the tent in front of hundreds of screaming, adoring Presley fans. I was ready to throw up, he admitted. You come out on stage and the noise was just deafening. You could barely hear yourself over the crowd. And though he may only channel Presley and his moves and cover the Kings classic songs, the women still swoon. Oh my god, it was crazy, he said about the crowd. There were so many of them just going crazy, screaming as loud as they could. Ive never seen anything like it, and my ears never hurt so much. That would have included his grandmother, Joellyn Cote, Deonath said. She would have been the worst, he said jokingly. But he also knows it would have been his grandmother who would have been his biggest supporter during the weeklong event. After all, she was the person who hooked her grandson on the Kings classic songs and movies. And after her death in 2012, Deonath put his career as an ETA on hold for a short while. Shes with me every time Im on stage, he said. Before I go out, I always point skyward and say, Lets do this. I know shed be thrilled at how far Ive come, and how well Im doing. But for her, it was always important that I have fun doing this and Im having a blast. And having a blast is exactly what Deonath had during Elvis week while competing in the nonprofessional 1970s division. It didnt matter much to Deonath that he was the youngest competitor in that category, nor did it matter he brushed aside the advice given to him by fellow ETAs to participate in the 1950s division. I knew I had the moves to compete against them, he said. Theres a lot that goes into it, and I know I have (Elvis) moves down, plus you get to wear a lot of cool suits. A lot of them are older, and Ill be honest, its easier for me to do a lot of the moves than it is for them. Why, you might ask? They dont get up as easy as I do, he joked. Deonath finished third overall in his category, but won Fan Favorite, which encompassed all four divisions two professional categories and the two nonprofessional categories. I went there to prove people wrong, the ones who said I couldnt compete in the 1970s division and I was there to make an impact, he explained. I did both. After all of my performances, I received standing ovations. Being an ETA involves a lot of work, Deonath said. He spends two to three hours a night practicing Presleys moves, facial expressions and songs, which fill Deonaths musical selection on his iPhone. For Deonath, life as an ETA aint nothing but a hound dog. Anytime I get on stage, I just love it, I just love performing, Deonath said.A2MONDAY, SEPTEMBER2, 2013CITRUSCOUNTY(FL) CHRONICLELOCAL Call Now For FREE Hearing Test and Consultation SWITCH TO SEXY Hear better w/no clogging feeling and virtually invisible Introducing: The X-Micro Fits up to severe loss with pure comfort DONT DELAY BEFORE AFTER 000FY05 OPEN FIT TECHNOLOGY SAVE THOUSANDS OFF REGULA R RETAIL PRICES 3 Year Warranty Water Resistant Fully Digital 32 Channel Capability Up To Severe Hearing Loss Wireless & Bluetooth Rechargeable Capabilities 000FWIA Teenage heartthrob Riverland News fileCote Deonath reacts after earning a sixth-place finish at Ted McMullens eighth annual Tribute to Elvis Contest earlier this year at the Spirit of the Suwannee Music Park and Campground in Live Oak. Dunnellon youth competes at Elvis Fest, wins Fan Favorite For more photos, click on this story at online.com.
PAGE 3
POW/MIA tribute planned Sept. 21The citizens of Citrus County are invited to join in National POW/MIA Recognition Day ceremonies Sept.21. Hosted by Rolling Thunder Florida Chapter 7 and the Inverness Elks Lodge 2522, the event will begin at 11a.m. and run until 3 or 4p.m. That morning, participants will join with special guests ex-prisoners of war at the Citrus County Fairgrounds they will depart at 11 a.m. for a policeescorted ride through Inverness to the program site, Inverness Elks Lodge 2522 on Lake Hernando in Hernando. The program is expected to start at noon. Following speakers and patriotic fare, there will be a special rendition of The Missing Man Table Ceremony. The program should be over by 1 p.m. and immediately afterward there will be a cookout with refreshments. This is not a fund-raising event. It is designed for the citizens of Citrus County to have a special opportunity to say thank-you to a very special group of Americans. For information, call Ray Thompson at 813-230-0750 or email ultraray1997 @yahoo.com.Estuaries Day event Sept. 28The St. Martins Marsh Aquatic Preserve and the Citrus County School Districts Marine Science Station invite the public to celebrate National Estuaries Day from 9 a.m. until 1 p.m. Saturday, Sept. 28. This community event includes guided boat rides, childrens activities, a hike up a 60-foot estuary observation tower, as well as walking tours of waterfront educational and research facilities. Due to limited available parking, visitors must meet at the Crystal River Preserve State Park at 3266 North Sailboat Avenue, Crystal River, for vehicle parking. Guided boat rides will take visitors to the Marine Science Station and back to the Crystal River Preserve State Park throughout the duration of the event. If necessary, limited disabled access parking will be available at the Marine Science Station, 12646 W. Fort Island Trail, Crystal River. For information, contact Jamie Letendre at Jamie.Letendre@dep.state. fl.us or 352-563-0450. This event is free to the public and reservations are not required. From staff reports STATE& LOCAL Page A3MONDAY, SEPTEMBER 2, 2013 CITRUSCOUNTYCHRONICLE QUESTION: Has the country achieved Martin Luther King Jr.s dream of a colorblind society? For the most part, yes. 32 percent (110 votes) Only to the extent that laws no longer discriminate. 16 percent (55 votes) In certain parts of the country, yes, but not the whole nation. 23 percent (80 votes) Not even close. 28 percent (97 votes) Total votes: 342. ONLINE POLL RESULTS County BRIEFS Duck lovers seek help ERYNWORTHINGTON Staff writerHOMOSASSA A lot of quacking has attracted support from animal activists around the meadows of a community pond. Homeowners have received backing from the Animal Rights Foundation of Florida (ARFF) in supporting the populous Muscovy ducks of the deed-restricted Meadows community. ARFF is a 501(c)3 nonprofit organization that promotes and protects the rights of animals in Florida. On Aug. 8, Meadows of Citrus County Homeowners Association (HOA) held a semi-annual meeting to discuss and vote on the removal of Muscovy ducks from the Meadows. Board members, some homeowners and proxy votes concluded the ducks would be removed. Numerous homeowners are outraged and are seeking resolution before the removal begins. I am so sick over this, said homeowner Lisa Cocuzza.I see those harmless ducks out there and think any day they can be gone and killed.It is difficult since we know nothing from the HOA board and the ducks are here every day to look at and think about their future. Therefore, duck activists and homeowners sought ARFFs assistance, and the group responded. We urge the Meadows of Citrus County Homeowners Association not to kill or trap Muscovy ducks and to instead explore effective, non-lethal methods of controlling the duck population, ARFF wrote to Elizabeth Hoffman, president of the HOA. Cocuzza along with other homeowners recognizes the densely inhabited Muscovy ducks dwelling in the community. However, she is optimistic the issue can be humanely resolved by the community working jointly instead of disjointedly. Hopefully, the Meadows Homeowners Association will work with us and the ARFF to keep the ducks safe, control the population humanely with egg control and other steps toward not killing of these lovely creatures, Cocuzza said. ARFF recognizes that the birds pose unwelcome challenges. However, they have a recommendation of resolution. Our organization is frequently contacted by homeowner associations and municipalities seeking a solution to problems with Muscovy ducks, ARFF officials wrote. The most humane way to reduce a duck population, or to keep Muscovy ducks from reaching nuisance numbers, is to remove newly laid eggs. ARFF would be happy to work with the Meadows to institute an egg collection plan. Cocuzza said the Meadows HOA has not responded to the ARFF. HOA president Elizabeth Hoffman did not immediately return a call from the Chronicle. Group recommends egg removal Apply now for 2014 Leadership Citrus Special to the ChronicleApplications are now being accepted for the Leadership Citrus Class of 2014. To be considered for the Class of 2014 applications must be received by Nov. 8, 2013. As in prior years the Leadership Citrus Selection Committee is seeking: Persons who have demonstrated involvement/interest in community affairs. Leaders and potential leaders who are active in business, education, the arts, religion, government and community-based organizations and will reflect the diversity of Citrus County. A class that represents a cross-section of the county, both professionally and geographically. Class participants who are permanent residents of Citrus County. The cost is $495 for Citrus County Chamber of Commerce members; $595 for non-members. The Class of 2014 will start with orientation the evening of Jan.8, with the first class being Thursday, Jan.9. The schedule is every other Thursday (full days), until the end of May. Applicants will be notified and interviews will occur Nov.20 to 22. The Leadership Citrus Selection Committee seeks to identify those individuals most likely to utilize their leadership abilities for the long-term benefit of Citrus County. Participants will be chosen by the selection committee based upon information provided on the application and a personal interview with the interview panel. Applications are available on the Leadership Citrus website, citrus.com or at all Chamber offices. A limited number of applicants will be selected to participate in the program. Because the number of participants is limited, applicants who are not selected are encouraged to apply in subsequent years. Completed applications should be mailed to: Leadership Citrus, P.O. Box 2861, Inverness, FL 34451-2861. For information, call Tonya Caldwell at 352-3416631 or 352-212-5302. Bowhunter Jamboree STEPHEN E. LASKO/For the ChronicleBowhunter Tanner Norris lines up on his target Sunday at the 52nd annual Bowhunter Jamboree. The event, at Holder Mine Campground in Inverness, will draw nearly 600 competitors from around Florida and will end Monday with an awards ceremony. Inverness has been very good to us, said Director Richard Burkhart. The restaurants and hotels are very accommodating and th e people are really nice to work with. See more photos online at. Bowhunter Dallas Reed draws on his bucktail deer target at the 52nd annual Bowhunter Jamboree at Holder Mine Camp in Inverness. Sunday was the first of a two-day tournament, with 565 registered entries and more arriving, according to director Burkhart. Longtime bowhunter Lowe Morrison from Sarasota gets down low Sunday for a clear shot at his target at the 52nd annual Bowhunter Jamboree. With 560 competitors registered at noon Sunday, registration at the event surpassed the minimum goal for attendance with one more day of competition still to come. The most humane way to reduce a duck population, or to keep Muscovy ducks from reaching nuisance numbers, is to remove newly laid eggs. communication from Animal Rights Foundation of Florida (ARFF) Deadline Nov. 8 for annual series of classes about county
PAGE 4
Birthday You can get ahead if you work in conjunction with others in the coming months. Large institutions will help you parlay one of your skills into a successful venture. Helping others will improve your reputation and finances. Virgo (Aug. 23-Sept. 22) Go the distance. Take a journey that will help you assess up close a situation youve been viewing from afar. Libra (Sept. 23-Oct. 23) Your position may be endangered if you arent careful about whom you share personal information with. Being too nice will cost you. Play to win. Scorpio (Oct. 24-Nov. 22) Stick close to home and you may avoid a runin with authority figures. Keeping the peace will ultimately help you advance. Sagittarius (Nov. 23-Dec. 21) Being misor under-informed will be a danger today. Do your homework and make sure you have all the facts. Capricorn (Dec. 22-Jan. 19) Put your time and money into your own ideas and abilities. Dont let a lastminute change of plans disrupt your day. Follow through. Aquarius (Jan. 20-Feb. 19) A change in the way you handle your money or health will make a difference in the opportunities that come your way. Pisces (Feb. 20-March 20) Expand your friendships by getting involved in activities or events that attract people who share your interests. Aries (March 21-April 19) Get physical and test your strength, courage and ability to win. Activity that challenges you will also attract positive prospects. Taurus (April 20-May 20) Dont let emotional matters get you down or cause arguments with someone you need to deal with regularly. Use your intellect to lead you in the best direction. Gemini (May 21-June 20) Youll be quick to size up a situation, but dont be eager to share your thoughts. Give others a chance to explain, but their words with a grain of salt. Cancer (June 21-July 22) Youll have fabulous ideas that should be shared today. Checking out different cultures or philosophies will lead to some good ideas for living. Be open-minded yet firm at all times. Leo (July 23-Aug. 22) Dont let a friend or lover from your past cause problems. Protect your home and family from the temptation that someone offers. Change can be good, but the motives involved have to be genuine. TodaysHOROSCOPES Today is Monday, Sept. 2, the 245th day of 2013. There are 120 days left in the year. This is Labor Day. Todays Highlight in History: On Sept. 2, 1945, Japan formally surrendered in ceremonies aboard the USS Missouri in Tokyo Bay, ending World War II. On this date: In 1666, the Great Fire of London broke out. In 1789, the U.S. Treasury Department was established. In 1963, Alabama Gov. George C. Wallace prevented the integration of Tuskegee High School by encircling the building with state troopers. In 1993, the United States and Russia formally ended decades of competition in space by agreeing to a joint venture to build a space station. Ten years ago: extolled their own man, John McCain, as ready to lead the nation. Todays Birthdays: Dancer-actress Marge Champion is 94. Rhythm-and-blues singer Sam Gooden (The Impressions) is 74. Singer Joe Simon is 70. Actor Mark Harmon is 62. Actress Linda Purl is 58. Actor Keanu Reeves is 49. Actress Salma Hayek is 47. Actor Tuc Watkins is 47. Actor-comedian Katt Williams is 40. Actor Michael Lombardi is 39. Actress Tiffany Hines is 36. Actor Jonathan Kite is 34. Actress Allison Miller). Today inHISTORY CITRUSCOUNTY(FL) CHRONICLE HI LO PR 96 70 0.00 HI LO PR 94 73 0.00 HI LO PR 92 72 0.00 HI LO PR 90 71 0.00 HI LO PR NA NA NA HI LO PR 91 73 0.00 YESTERDAYS WEATHER Scattered storms, rain chance 40%THREE DAY OUTLOOK Scattered storms, rain chance 30% Scattered storms, rain chance 40%High: 89 Low: 72 High: 90 Low: 73 High: 91 Low: 73TODAY & TOMORROW MORNING TUESDAY & WEDNESDAY MORNING WEDNESDAY & THURSDAY MORNING Exclusive daily forecast by: TEMPERATURE* Sunday 91/72 Record 96/68 Normal 91/71 Mean temp. 82 Departure from mean +1 PRECIPITATION* Sunday 0.00 in. Total for the month 0.00 in. Total for the year 41.01 in. Normal for the year 39.06 in.*As of 7 p.m. at InvernessUV INDEX: 10 0-2 minimal, 3-4 low, 5-6 moderate, 7-9 high, 10+ very high BAROMETRIC PRESSURE Sunday at 3 p.m. 29.96 in. DEW POINT Sunday at 3 p.m. 71 HUMIDITY Sunday at 3 p.m. 57% POLLEN COUNT** Grasses and weeds were light and trees were absent.**Light only extreme allergic will show symptoms, moderate most allergic will experience symptoms, heavy all allergic will experience symptoms.AIR QUALITY Sunday was good with pollutants mainly ozone. ALMANAC CELESTIAL OUTLOOK SUNSET TONIGHT ............................7:50 P.M. SUNRISE TOMORROW .....................7:09 A.M. MOONRISE TODAY ...........................4:33 A.M. MOONSET TODAY ............................5:58 P.M. SEPT. 5SEPT. 12SEPT. 19SEPT. 26. 93 73 ts Ft. Lauderdale 90 79 ts Fort Myers 92 76 ts Gainesville 92 73 ts Homestead 92 77 ts Jacksonville 92 74 ts Key West 89 80 ts Lakeland 93 74 ts Melbourne 91 73 ts City H L Fcast Miami 91 79 ts Ocala 93 73 ts Orlando 93 74 ts Pensacola 90 76 ts Sarasota 90 75 ts Tallahassee 92 72 ts Tampa 90 77 ts Vero Beach 90 74 ts W. Palm Bch. 90 77 ts FLORIDA TEMPERATURESSouthwest winds around 10 knots. Seas 1 foot or less. Bay and inland waters will have a light chop. Chance of thunderstorms today. Gulf water temperature88 LAKE LEVELSLocation Sat. Sun. Full Withlacoochee at Holder 29.43 29.42 35.52 Tsala Apopka-Hernando 38.16 38.15 39.25 Tsala Apopka-Inverness 39.24 39.24 40.60 Tsala Apopka-Floral City 40.33 40.33 L L L L L 96/77 73/64 88/58 95/74 75/54 74/68 69/58 85/57 95/64 76/60 87/72 75/58 89/74 91/79 95/75 92/73 THE NATION Albany 84 69 ts 80 64 Albuquerque 94 71 ts 90 69 Asheville 85 66 .11 ts 83 64 Atlanta 90 73 trace ts 89 74 Atlantic City 88 73 .08 ts 88 73 Austin 100 73 pc 98 75 Baltimore 91 70 ts 91 70 Billings 87 53 pc 95 64 Birmingham 92 73 ts 94 74 Boise 94 62 ts 89 62 Boston 79 70 .38 ts 79 68 Buffalo 84 66 ts 78 58 Burlington, VT 86 68 ts 79 63 Charleston, SC 93 76 ts 91 76 Charleston, WV 83 68 ts 86 65 Charlotte 90 68 .13 ts 90 71 Chicago 85 65 s 73 64 Cincinnati 85 67 ts 86 60 Cleveland 84 71 ts 76 62 Columbia, SC 94 74 ts 93 73 Columbus, OH 86 71 ts 84 58 Concord, N.H. 85 65 ts 79 62 Dallas 104 80 pc 96 77 Denver 80 63 pc 88 58 Des Moines 86 70 .17 s 80 53 Detroit 82 69 pc 75 58 El Paso 98 73 pc 95 74 Evansville, IN 89 68 1.14 pc 87 60 Harrisburg 88 70 ts 88 67 Hartford 82 71 .16 ts 82 66 Houston 96 73 pc 95 75 Indianapolis 85 68 pc 85 56 Jackson 96 71 pc 95 73 Las Vegas 95 76 ts 97 81 Little Rock 98 77 pc 94 70 Los Angeles 78 69 pc 74 68 Louisville 88 70 .29 pc 88 62 Memphis 96 78 .03 pc 92 72 Milwaukee 85 63 s 70 59 Minneapolis 75 65 s 75 54 Mobile 92 74 trace pc 90 73 Montgomery 95 71 trace ts 94 73 Nashville 84 69 .36 ts 91 68 New Orleans 93 75 pc 90 77 New York City 84 75 ts 87 72 Norfolk 92 75 ts 90 74 Oklahoma City 96 73 pc 91 68 Omaha 85 69 .65 s 83 55 Palm Springs 107 84 ts 103 82 Philadelphia 89 74 ts 89 73 Phoenix 105 84 ts 105 84 Pittsburgh 80 71 .01 ts 81 62 Portland, ME 82 66 ts 75 62 Portland, Ore 85 63 sh 77 60 Providence, R.I. 82 70 .67 ts 79 67 Raleigh 91 72 .63 ts 93 72 Rapid City 84 51 pc 89 68 Reno 87 65 trace ts 87 61 Rochester, NY 81 67 ts 82 60 Sacramento 91 62 pc 88 63 St. Louis 91 72 .75 pc 85 65 St. Ste. Marie 69 61 .20 s 62 51 Salt Lake City 90 72 ts 89 71 San Antonio 101 78 pc 97 75 San Diego 80 73 pc 78 69 San Francisco 74 58 pc 73 59 Savannah 90 74 trace ts 91 75 Seattle 82 60 sh 76 60 Spokane 92 56 pc 84 59 Syracuse 84 67 ts 80 61 Topeka 89 72 .29 s 85 59 Washington 93 72 ts 92 73YESTERDAYS NATIONAL HIGH & LOW HIGH 107 Palm Springs, Calif. LOW 34 Stanley, Idaho MONDAY CITY H/L/SKY Acapulco 85/76/ts Amsterdam 66/60/c Athens 87/69/s Beijing 87/66/pc Berlin 61/61/r Bermuda 82/76/pc Cairo 97/69/pc Calgary 87/55/pc Havana 89/74/ts Hong Kong 86/79/sh Jerusalem 89/69/s Lisbon 89/66/s London 76/61/pc Madrid 89/61/s Mexico City 71/55/ts Montreal 70/66/ts Moscow 68/50/sh Paris 77/51/pc Rio 86/69/pc Rome 82/69/s Sydney 73/56/s Tokyo 90/73/sh Toronto 78/57/ts Warsaw 59/53/sh* 5:00 a/12:31 a 4:27 p/12:14 p 5:31 a/1:07 a 5:11 p/12:59 p Crystal River** 3:21 a/9:36 a 2:48 p/10:29 p 3:52 a/10:21 a 3:32 p/11:02 p Withlacoochee* 1:08 a/7:24 a 12:35 p/8:17 p 1:39 a/8:09 a 1:19 p/8:50 p Homosassa*** 4:10 a/11:13 a 3:37 p/ 4:41 a/12:06 a 4:21 p/11:58/2 MONDAY 3:41 9:52 4:04 10:15 9/3 TUESDAY 4:22 10:33 4:45 10:56 FORECAST FOR 3:00 P.M. MONDAY, grasses, chenopods Todays count: 4.7/12 Tuesdays count: 6.9 Wednesdays count: 7 Beetle Bailey creator turning 90Bloomberg, Dolly Parton and even Prince Albert II of Monaco. Walkers birthday is Sept. 3. He lives in Stamford, Conn. He told The Associated Press in 2010 as the comic strip marked its 60th anniversary that he would continue with his creation until hes no longer able. The comic strip featuring Beetle Bailey, Sarge and his dog, Otto, Gen. Amos Halftrack and Miss Buxley has more than 200 million readers in 52 countries.Lady Gaga performs at iTunes FestivalLONDON With flying pigs and wigs, Lady Gaga debuted her ARTPOP songs at the iTunes Festival. The pop star performed seven new songs, as she headlined the event at Londons Roundhouse Sunday night. It is Gagas first solo show since she had hip surgery in February. The concert started with her swinging over the audience in a cage and involved many onstage costume changes, elaborate wigs and dancers in hazard suits wearing pig masks, hanging from the ceiling. The songs included Jewels & Drugs a rap number featuring T.I. pop song Sex Dreams and ballad I Wanna Be With You. Also the title track of Gagas new album, ARTPOP, which is released Nov. 11. iTunes Festival continues throughout September with Elton John Justin Timberlake and Katy Perry on the lineup.Old comic helps fund daughters weddingCLEVELAND A Cleveland Heights dad was getting worried about the costs of his eldest daughters upcoming wedding. Then, Spider-Man to the rescue! The Plain Dealer of Cleveland reportedcondition copy would have sold for much more. But hes happy, and said the sale will help cover the catering costs for daughter Janes reception. From wire reports Associated PressMort Walker, the artist and author of the Beetle Bailey comic strip, speaks Aug. 16, 2010, about his decades of work and experiences at his studio in Stamford, Conn. Walker is getting accolades from top military brass and others as he celebrates his 90th birthday. Walker turns 90 on Sept. 3. A4MONDAY, SEPTEMBER2, 2013 000FUXL in Todays Citrus County Chronicle LEGAL NOTICES Meeting Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . B10 Lien Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B10 Foreclosure Sale/Action Notices . . . . . . . . . . . . . . B10 Notice to Creditors/Administration . . . . . . . . . . . . B10 Dissolution of Marriage Notices . . . . . . . . . . . . . . . B10 Termination of Parental Rights Notices . . . . . . . . . B10 Lady Gaga arrives Aug. 25 at the MTV Video Music Awards.
PAGE 5
DUI arrest Kevin McFadden, 20, of Phlox Drive, Palm Harbor, at 10:53p.m. Aug.31 on misdemeanor charges of driving under the influence, leaving the scene of an accident, and DUI with damage to property. According to his arrest affidavit, McFadden was part of a traffic accident on County Road 491 and left the scene after causing damage to another vehicle. McFadden was asked to perform field sobriety tests and did poorly. Tests of his breath showed his blood alcohol concentration was 0.244 percent and 0.247 percent. The legal limit is 0.08 percent. Bond $1,250.BUI arrests Robert Holmes, 56, of Northeast Third Avenue, Crystal River, at 6:24p.m. Aug.31 on a misdemeanor charge of boating under the influence. According to his arrest affidavit, Holmes was stopped in the Kings Bay area, near Buzzard Island for speeding in an idle zone. Holmes admitted to drinking apple pie moonshine, which he had made himself. He did poorly on field sobriety tests and refused tests of his blood alcohol level. Bond $500. Michael Nadeau, 40, of North Elkcam Boulevard, Citrus Springs, at 4:42p.m. Aug.31 on a misdemeanor charge of boating under the influence. According to his arrest affidavit, Nadeau was stopped in the Sandy Hook area, for being visibly impaired on a jet ski. He refused field sobriety tests and refused tests of his blood alcohol level. Bond $500. Eric Young, 34, of Northwest 265 Street, Lawtey, at 7:09p.m. Aug.31 on a misdemeanor charge of boating under the influence. According to his arrest affidavit, Young was stopped in Kings Bay, for a routine safety check. He appeared impaired falling when he walked, and did poorly on field sobriety tests. He refused tests of his blood alcohol level. Bond $500.Domestic battery arrest Dale Williams, 32, of Inverness, at 12:45a.m. Sept.1 on a misdemeanor charge of domestic battery. No bond.Other arrests Joseph Serra Jr., 26, of East Granger Street, Inverness, at 2:29a.m. Sept.1 on misdemeanor charges of possession of cannabis (less than 20 grams), drug paraphernalia, and resisting an officer without violence. According to his arrest affidavit, Serra was spotted riding a bicycle without lights, and failed to stop when approached by law enforcement, running into the Walgreens on South Apopka Avenue in Inverness. A search of his backpack turned up 19.6 grams of marijuana. Bond $1,500. Edwin Boyle, 23, of Eller Bee Road, Zephyrhills, at 9:36p.m. Aug.31 on misdemeanor charges of knowingly driving while license is suspended or revoked and resisting an officer without violence. According to his arrest affidavit, Boyle is accused of driving recklessly on Northwest U.S. 19. A background check on DAVID confirmed his license had been revoked for failing to comply with substance abuse testing, including an ignition lock device. Boyle became belligerent, using profanity and resisting arrest. Bond $10,500. Shazeeda Mills, 34, of Southeast U.S. 441, Summerfield, at 9:07p.m. Aug.31 on a misdemeanor charge of battery. According to her arrest affidavit, Mills is accused of striking a women in the head with her shoe, resulting in the victim needing stitches. The dispute was over the victim owing Mills $30. Bond $500. Sarah Canter, 22, of Homosassa, at 7:16p.m. Aug.31 on a misdemeanor charge of resisting an officer without violence. According to her arrest affidavit, Canter is accused of trespassing at MacRaes in Homosassa, and taking drinks from other patrons. Canter held on to a pillar and began screaming when confronted by law enforcement. Bond $500. Manny Souza, 43, of Bonneville Drive, New Port Richey, at 12:04p.m. Aug.31 on a misdemeanor charge of retail petit theft. According to his arrest affidavit, Souza is accused of stealing a pack of cigarettes and $13 in cash from Como RV Sales in Inverness. Bond $250. Benito Licciardello III, 27, of Southeast 53rd Avenue, Summerfield, at 10:33p.m. Aug.30 on a misdemeanor charge of trespassing after warning. According to his arrest affidavit Licciardello was harassing patrons at Crackers Bar and Grill. Bond $1,000. Kenneth Kirkland, 41, West Hawthorne Street, Crystal River, at 8:13 p.m. Aug. 30 on a misdemeanor charge of retail petit theft. According to his arrest affidavit, Kirkland is accused of shoplifting two DVDs valued at $30.98 from Kmart in Crystal River. Bond $250. Edward Breiner, 60, of Largo at 8:30p.m. Aug.30 on a misdemeanor charge of aggravated battery with intent to cause great bodily harm or permanent disability. No bond. Kyle Bennett, 35, of West Country Club Drive, Homosassa at 12:14p.m. Aug.30 on outstanding warrants on violation of probation, stemming from felony charges of failing to report name or residence as a sex offender, and lewd and lascivious molestation of a victim. Bennett turned himself in at the Citrus County Sheriffs office. Bond was denied. Christine Adams, 31, of South Adams Street, Beverly Hills at 10:40a.m. Aug.30 on misdemeanor charges of falsely identifying self to law enforcement officer, and no drivers license. According to her arrest affidavit, Adams is accused of striking a vehicle while pulling onto Forest Ridge Boulevard. She did not have proper identification and provided a false name. A search on DAVID showed she had no legal driving license. Bond $1,000. the hearing already has been legally noticed to use the commission chamber in the courthouse as a venue. You still need to open up your meeting here, but you can move the remainder of it over there, Parsons said. Parsons also explained that, as the session would include only the preliminary budget hearing and no other county business, it could be concluded at the auditorium. On July 23, commissioners had to finish their meeting back at the courthouse because the hearing for the fire protection services fee was on a regular board meeting agenda. Meek said he understood the preliminary budget hearing would need to start at the courthouse to be a legal meeting because the courthouse was the location identified for the hearing in the TRIM (Truth In Millage) notices that were mailed Aug. 12. Youd have to re-notify absolutely everyone who got a TRIM notice, Parsons replied to Commissioner Scott Adams, who asked why the hearing could not begin in the auditorium. We feel that its important to give the public the right to speak, said County Administrator Brad Thorpe. If they are out in the hallway, they cant speak. Residents who want to attend the hearing should go directly to the auditorium. Commissioners will open the hearing in the courthouse, but only cover roll call before recessing the hearing and reconvening it at 5:30 p.m. at the auditorium. County Administrator Brad Thorpe and Cathy Taylor, director of the Management and Budget Department, will present the Fiscal Year 2013-14 proposed budget. The board will review and discuss a motion to adopt thetentative millage rates for Fiscal Year 2013-14. The tentative property tax rate of 9.2387 mills is a 30percent increase from the current rate of 7.1033 mills. These are the suggested millage rates: General Countywide 7.0922 mills, Road and Bridge 0.8806 mills, Health Department 0.1011 mills, Library Services 0.3333 mills, Fire Rescue 0.7315 mills and stormwater management, a new federal mandate 0.1000 mills, for a combined rate of 9.2387 mills. One mill equals $1 for every $1,000 of assessed property value. The tax rate of 9.2387 mills is the maximum figure for calculating taxes for the fiscal year that begins Oct. 1. Commissioners could lower the rate before the new budget is finalized, but cant raise it. There also will be a motion to authorize the chairman to execute the resolution adopting the tentative millage rates and to execute a resolution adopting the tentative budget as proposed for fiscal year 2013-14. Residents will have the opportunity at the auditorium to comment after the budget presentation. The final budget public hearing is expected at 5:01 p.m. Tuesday, Sept. 24, at the courthouse in Inverness.Contact Chronicle reporter Chris Van Ormer at 352-564-2916 or cvanormer@chronicleonline. com. their microloan programs. People dont know that that money is available. It is money given to businesses that may not have the best credit. It is through our local banks. They give money to the Economic Development Council through these micro loans up to $10,000 to help businesses grow, expand through struggling times. You have to have a SCORE mentor. SCORE is not the deciding factor, but you have to have a mentor. We talk to them and say Yeah, this is probably a business that we would recommend. Right now, there is $30,000 to $40,000 sitting in an account. That is money that we can be giving to our businesses and people dont even know it is there. CHRONICLE: Technology is evolving and social media has become crucial to a lot of businesses. How are SCORE and the Speakers Bureau displaying this? MALM: With being a business owner and working a lot of hours, when I meet with someone about social media needs, its a pretty quick thing. Its not like writing a business plan and that kind of thing. Through the Speakers Bureau, we talk about social media and how important it is. If you are not on the social media bandwagon, you have to get on. Theres so many social media mediums out there that it is impossible for any business to be in all of them. Its a full-time job to be in a few. Each business has probably four or five social media mediums that through minimal research you can find out what works in your area. Whether its a restaurant or printing company, theres ways to hit those targeted areas and how to run those things. It could be through Hoop Sweep, which is a free service. You sit down on Sunday morning, have a cup of coffee and your social media runs for you. There are companies out there that will run your social media. You can involve your team members in doing it. You have to be in the arenas that work in your industry, otherwise you are just spinning your wheels. Every business has to get into the social media arena. CHRONICLE: What does the Speakers Bureau do? MALM: The Speakers Bureau is multifaceted. One is to tell people what SCORE is and let people know about the micro loans. I think we have right now probably 30 SCORE counselors. We will come and talk to anyone anywhere. We are the people that are in and out of businesses everyday. We speak to a lot of groups with retired people. They ask, Why do you want to come and talk to us? Guess what? They are the people that are out there in those businesses. They are the people that are hearing the business owners or employees talk about their struggles. The more people that we can tell that we are here, its free and confidential and funding could be available, then we have all of those eyes and ears out there for us to say, Hey, there is help. There is free help for you right here in Citrus County. The more people that we can get out there knowing who we are and what we do (the better it is). Through the Speakers Bureau, we also look for other mentors. We get about 10 new clients a week. It gets overwhelming for the people that have to spend a lot of time writing business plans. So we are always looking for additional mentors, business people or retired people. When you hear someone talking about their problem, send them our way. Contact Chronicle reporter Eryn Worthington at 352-563-5660, ext. 1334, or eworthington@ chronicleonline.com. LOCALCITRUSCOUNTY(FL) CHRONICLEMONDAY, SEPTEMBER2, 2013 A5 000FXJG September 10-12 Crystal River Mall Accessories next to Cosmetics Buying Hours 10am-5pm No appointment necessary 000FXOG NEW LIFE FOR OLD BATHROOMS Bathtub Reglazing Porcelain, Fiberglass & Tile Match or change any color Chip repairs in Tubs Fiberglass Tub & Shower bottom repairs AFTER AFTER AFTER BEFORE BEFORE BEFORE Home Safety In Baths Non-Skid surface in Tubs & Showers Safety Bar installation Tub to Shower Conversions SOMETHING FOR EVERY BUDGET Jerry and Anne Black, Owners (352) 637-2299 About Baths All Serving Citrus County Since 1989 000FSEA Lawn Sprinkler Not Working? Well Fix It $10 Off with ad 746-4451 2013 2013 2013 2013 MONDAY CONVERSATION The Chronicles Monday Conversation feature sits down prominent members of the community for a short chat about their jobs and their lives. To recommend someone, email Managing Editor Charlie Brennan at newsdesk@chronicleonline.com or phone the newsroom at 352-563-5660. MONDAYContinued from Page A1 BUDGETContinued from Page A1 For theRECORDa.m. daily in the administration building. Annie Johnson Senior & Family 8a.m. to 3p.m. Monday through Friday, 1991 W. Test Court, Dunnellon, is open to Citrus County residents. 352-4898021. The Salvation Army 9 to 11a.m. and 195-8668. Citrus United Basket (CUB) 9a.m. to 2:30p.m. Monday through Friday, 103Mill Ave., Inverness, to assist Citrus County residents facing temporary hardship. Call CUB at352-3442242 or citrusunitedbasket.org. First Baptist Church of Crystal River 10a.m. to 1p.m. Monday, Wednesday and Thursday, 700 N. Citrus Ave. 352-795-3367. Our Lady of Fatima 10a.m. to2p.m. Monday through Friday, 604 U.S. 41 S., open to needy residents of Floral City, Hernando and Inverness. 352-726-1707. Our Lady of Grace Catholic Church 9 to 10a.m. the third Tuesday monthly, 6 Roosevelt Blvd. 352-5272381 or 352-746-2 352-527-4537. Nature Coast Ministries 10a.m. to 2p.m. Tuesdays and Thursdays, 999 State Road 44, Crystal River. 352-5631860. We Care Food Pantry must be a Homosassa or Homosassa Springs resident. 352-228-4921. Beverly Hills Community Church 11a.m. to noon and 6 to 7p.m. the last Tuesday monthly, 82 Civic Circle, open to Beverly Hills residents. 352-7463620. Suncoast Baptist Church food pantry open for bread distribution from 9 to 10:30a.m. Wednesdays, and the second Wednesday monthly is distribution of bagged canned goods, dry goods and meat from 9 (SOS) 8:30 to 11:30a.m. Thursdays at Good Shepherd Lutheran Church, 439 E. Norvell Bryant Highway, Hernando. Crystal River United Methodist Church 9a.m. to 1p.m. the second and fourth Thursdays monthly, 4801 N. Citrus Ave., Crystal River. 352-795-3148 or. Calvary Church 10a.m. to 2p.m. Thursdays, 2728 E. Harley St., Inverness, open to Citrus County residents. 352-637-5100 or calvary.com. First Baptist Church of Beverly Hills Helping Hands Food Pantry 9 to 11a.m. the third Saturday monthly, 4950 N. Lecanto Highway, Beverly Hills. Serving Beverly Hills, Lecanto and Citrus Springs. 352-746-2970. FREE MEALS First United Methodist Church of Inverness Gods Kitchen 11:30a.m. to noon Mondays, 3896 S. Pleasant Grove Road. 352-726-2522. Floral City United Methodist Church 7 to 9a.m. Tuesdays in Hilton Hall, 8478 E. Marvin St. 352-3441771. St. Margarets Episcopal Churchs Feed My Sheep outreach 11:30a.m. Wednesdays. 352-726-3153. Salvation Army Canteen 5 to 6p.m. Wednesdays at the Homosassa Lions Club, one-half mile east of U.S. 19 on Homosassa Trail. 352-513-4960. Calvary Chapel of Inverness Feed the Hungry, noon to 1p.m. Thursdays, soup kitchen from 11:30a.m. to 1p.m. Tuesdays, 960 S. U.S. 41. 352-726-1480. Our Fathers Table 11:30a.m. to 12:30p.m. Saturdays at St. Annes Anglican Church, one mile west of the Plantation Inn on West Fort Island Trail. 352-795-2176. Inverness Church of God 10:30a.m. the first and third Sunday monthly, 416 U.S. 41 S., Inverness. 352-726-4524.GIVEAWAYS The New Church Without Walls gives food boxes away at 5pa.m. the following Saturday. El-Shaddai food ministries brown bag of food distribution is from 10a.m. to 1pa.m. to noon the second and fourth Tuesdays monthly. Call 352-212-5159. Associated PressL worlds most powerful and famous, including virtually every British prime minister and U.S. president of his time. He also was a gifted entertainer, a born TV host, and his amiable and charming personality was often described as the key to his success as an interviewer. Frost, 74, died of a heart attack on Saturday night aboard the Queen Elizabeth cruise ship, where he was due to give a speech, his family said. The BBC said it received the statement from Frosts family saying it was devastated and asking for privacy at this difficult time. The cruise company Cunard said its vessel left the English port of Southampton on Saturday for a 10day cruise in the Mediterranean. Frost was born April 7, 1939, in Kent, England, the son of a Methodist preacher. Frost, who wrote about a dozen books, won numerous awards and was knighted in 1993. Most recently he was hosting programs for Al-Jazeera English, where he had worked since its launch several years ago. He is survived by his wife, Carina, and their three sons.A6MONDAY, SEPTEMBER2, 2013CITRUSCOUNTY(FL) CHRONICLE 1624 N Meadowcrest Blvd., Crystal River 000FVXT Play against other local football fans. Local prize winner every week. Register Today! FREE EASY FUN 000FVXT Chance to WIN the Grand Prize a Trip to HAWAII HAWAII HAWAII 2013 Closing time for placing ad is 4 business days prior to run date. There are advanced deadlines for holidays. To Place Your In Memory ad, Candy Phillips 563-3206 cphillips@chronicleonline.com 000FX8G / 000FXJL AUDIOLOGY Crystal River Inverness Call For A Free Consultation (352) 795-5700 Our Patients Are Super Hearos Conquer Your Hearing Loss! For Information and costs,call 726-8323 Burial Shipping CremationFuneral HomeWith Crematory000EHVX Obituaries DeathELSEWHERE FoodPROGRAMS Virginia Curtis, 90CRYSTAL RIVERVirginia D. Curtis, 90, of Crystal River, passed away Friday, Aug.30, 2013, at Cypress Cove Care Center. A native of Lookout, W.Va., she was born April4, 1923, to Clarence and Geneva (Hicks) Houchins, the eldest of four children. A lifelong homemaker and waitress, she moved to Citrus County permanently in 1995 from New York, but had been a seasonal resident since 1978 and also lived in St. Petersburg. Virginia is survived by her children: Jean Ann Campbell (husband Dean) Horseheads, N.Y.; Kathy Curtis Cahill (husband Lawrence Morrison), Glendale, Calif., and Douglas Curtis (wife Joyce), Shade, Ohio; sister Imogene Browning, Homosassa; seven grandchildren; and 11 great-grandchildren. Virginia was preceded in death by her husband of 54 years, Kenneth Curtis (1995); son Kenneth Curtis Jr., (2013); and siblings Marshall Houchins and Margaret Brooks. Interment is private. Wilder Funeral Home, Homosassa. funeral.comRoberta Stoughton, 65HERNANDORoberta F. Stoughton, 65, of Hernando, Fla., died Friday, Aug.30, 2013. Memorial Service of Remembrance is at noon Wednesday, Sept.11, 2013, at Calvary Church, 2728 E. Harley St., Inverness, FL 34453. Arrangements are entrusted to Fero Funeral Home. Kathleen McGrath, 72HERNANDOKathleen P. McGrath, 72, of Hernando, Fla., died Sunday, Sept. 1, 2013, at home under the loving care of her family and Hospice of Citrus County. Kathleen was born Nov. 11, 1940, in Elizabeth, N.J., the daughter of Clarence and Theresa Doty. She worked for Liberty Mutual Life Insurance Company, where she was a clerical manager. Kathleen moved to Hernando, Fla., from South Plainfield, N.J., in 2001. She was a member of Our Lady of Fatima Catholic Church in Inverness and the Citrus Hills Womens Club. Survivors include her husband of 49 years, John McGrath of Hernando, Fla.; three sons, Patrick McGrath and his wife Heidi of Spencerport, N.Y., Michael McGrath of Hernando, Fla., and Kevin McGrath of Metuchen, N.J.; daughter Tara McCarthy and her husband Shawn of Inverness, Fla.; sister Elaine Schiller and brother-in-law Frederick of Harpersfield, N.Y.; sister-in-law Joan Hochreiner of South Plainfield, N.J.; four grandchildren, Molly, James, Kellen and Julianne; and many nieces and nephews. A Mass of Christian Burial will be at 11 a.m. Tuesday, Sept. 3, 2013, at Our Lady of Fatima Catholic Church in Inverness, Fla. Interment will follow at Florida National Cemetery in Bushnell, Fla. Heinz Funeral Home & Cremation, Inverness, Fla. Sign the guest book at. David Frost dies at 74.
PAGE 7
Police: Mother shot child, herselfSARASOTA Sarasota police say a mother shot her 1-year-old daughter and then turned the gun on herself. Police say they responded to the murder-suicide Sunday morning. Spokeswoman Genevieve Judge said 35year-old Sarah Harnish died at the scene. Josephine Boice, who was 17 months old, was taken to the hospital and later died. A police statement said the childs father returned home from a scooter ride before 10a.m., heard shots fired and called 911. No one else was inside the home when it happened. Police said a report wont be available until Tuesday.Funeral for boy with rare infectionLABELLE Nearly 1,000 people gathered for the funeral of a Florida boy who was infected by a rare and deadly brain-eating amoeba. The public visitation and service was Saturday for 12year-old Zachary Reyna at the LaBelle Middle School Gym. The burial service was.Grave excavation continues at siteMARIANNA.Nyad swims closer to Fla. from CubaKEY WEST U.S. endurance simmer Diana Nyads representatives say shes. Its her fourth attempt in the last three years. If shes successful this time, she expects to take about 80 hours to reach the Florida Keys.Ocala ticket shares Fantasy 5 TALLAHASSEE 4-6-21-28-31. Special to the ChronicleThe next session of the Citrus County Sheriffs Office Citizens Academy a 10-week educational program offered free of charge to all Citrus County residents begins Thursday, Sept. 5. Since its inception in June 1997, more than 2,000 people including students, elected officials, businesspeople, journalists, retirees and volunteers have taken the time to learn more about the Citrus County Sheriffs Office. The academy was designed to provide a better understanding of the sheriffs office and its functions. The underlying objective is to build a strong partnership between law enforcement officers and the people they serve. Lt. Chris Evan, who works with the agencys accreditation process and special projects, is the Citizens Academy director. Sheriffs office professionals serve as classroom instructors, and each hands-on, interactive session focuses on specific segments of the agency. The program agenda includes instruction and demonstrations in road patrol, criminal investigations, vice and narcotics, intelligence analysis, the Emergency Operations Center/911, Sheriffs Fire Rescue Division, traffic, aviation, marine, the Sheriffs Special Weapons and Tactics Team (SWAT), K-9 teams, identification and evidence, crime prevention and more. There is no cost to attend the academy, and classes meet Thursdays at the Sheriffs Emergency Operations Center in Lecanto. Participants may choose between 1 to 4p.m. classes and 6 to 9p.m. classes. There are scheduled field trips that give participants a chance to interact directly with deputies and communications officers. There are also interactive demonstrations. To apply for the academy, fill out the form online at citrus.org/pdfviewer.aspx?doc= CitizensAcademyApp (search for citizens academy from the home page of) or call 352-341-3457., Sept. 9, West Citrus Government Building, 1540 N. Meadowcrest Blvd., Crystal River.. 4 to 7:30 p.m. Wednesday, Sept. 18, First Baptist Church of Crystal River, 700 Citrus Ave. Noon to 3 p.m. Wednesday, Sept. 18, Walmart Supercenter, 1936 N. Lecanto Highway, Lecanto. Noon to 6 p.m. Thursday, Sept. 19, Walmart Supercenter, 1936 N. Lecanto Highway, Lecanto. 11 a.m. to 5 p.m. Friday, Sept. 20, Lowes, 2301 E. Gulf-to-Lake Highway, Inverness. 10 a.m. to 5 p.m. Saturday, Sept. 21, Love Motorsports, 2021 S. Suncoast Blvd., Homosassa. 10 a.m. to 5 p.m. Sunday, Sept. 22, Walmart Supercenter, 2461 W. Gulf-to-Lake Highway, Inverness..LOCAL& STATECITRUSCOUNTY(FL) CHRONICLEMONDAY, SEPTEMBER2, 2013 A7 Call today to advertise your business here 563-320) 000FSDD TEXT . CITRUS + Your Tip to 274637 (CRIMES) CLICK . CALL . 1-888-ANY-TIPS (1-888-269-8477) Funded by the Office of the Attorney General, Crime Stoppers Trust Fund of Citrus County, Inc. YOU COULD RECEIVE A REWARD UP TO $ 1,000 Blackshears II Aluminum 795-9722 Free Estimates Licensed & Insured RR 0042388 Years As Your Hometown Dealer 000FWND HWY. 44 CRYSTAL RIVER 2013 2013 2013 2013 Rescreen Seamless Gutters Garage Screens New Screen Room Glass Room Conversions, Sept. 2nd only. $ 10 FOR 20 GAMES Win $ 50 to $ 250 $ 1150 In Prizes Every Bingo Game Bring Ad in: Buy 1 Bonanza, Get 1 FREE 000FW8U The Friendliest Bingo in T own! B 10 I 19 For a Day or Night of Fun and to Meet New Friends. Come and Play! To place your Bingo ads, call 563-5592 9203147 9301 W. Fort Island Trail, Crystal River 352-795-4211 Wednesday 1/2 Price Bottle of Wine with purchase of any appetizer or entree 000FZ04 Thursday Night $5 Specialty Martinis F LORAL C ITY L IONS B INGO F LORAL C ITY L IONS B INGO at the Community Building 726-5107 Every Wednesday 6:30pm 25 cent games at 4pm 20 games Bonanza4 speed games and 18 regular games with Jackpot $24 in door prizes 000FZC5 BloodDRIVES Apply for Citizens Academy StateBRIEFS From wire reports
PAGE 8
OPINION Page A8MONDAY, SEPTEMBER 2, 2013 What faith will doI know its commonly believed that faith can move mountains, but I doubt that anyone has actually ever done it. First of all, such a colossal undertaking would require an engineer to plan all the stages of work. Then, a labor crew must be assembled. Many thousands of young men with strong arms and backs to do the heavy lifting and pulling will be required. A committee will have to decide where to stack the dirt and rocks. The only place I can think of thats big enough is the Pacific Ocean. And finally, some genius will have to figure out where the water displaced by the debris will be stored. I am, myself, a practical man and I have drawn up a short list of things that faith wont do for you. It wont stop your neighbors dog from barking at three oclock in the morning. It wont stop the roof from leaking every time it rains. It wont cook you a hot meal on a cold winter evening when your wife has gone bowling. But there is someone who will gladly do all of these things for you. You are already pretty-well acquainted with him. Im referring, of course, to that fellow smiling back at you every morning in the bathroom mirror. If you rely on him youll always have three hot meals every day and a warm bed to sleep in at night. Folks, heres something you can put your faith in: An honest days work wont make you rich and famous, but it will put enough money in your pocket so you wont have to beg for food and youll never have to kowtow to anybody on earth. When a man is concentrating on his work, he is doing two things at once. He is doing something useful for his employer and at the same time he is supporting his family. When a man and a woman work together they form a bond stronger than steel. The march of time will turn their hair silver, but their eyes will sparkle like stars in the sky.Franklin G. Aretz Beverly HillsThe Butler and the GOPRecently my wife and I went to a matinee called The Butler. It was an outstanding production that spanned from the 1920s to the election of President Barack Obama. Oprah Winfrey and Forest Whitaker were the lead actors. The character of Cecil Gaines, played by Whitaker, saw his mother raped at a young age and his father shot in the head by a white man who owned a Georgia cotton field where the Gaines family worked. Young Cecil is trained to wait on people by the matriarch whose son raped and shot the Gaines family. As Cecil develops his skills to wait on people, he strikes out and heads north, landing a job in large hotel in Washington. He is then put in a position where race, politics and social class make him aware that he can never be on the same level as whites. However, a black man comes to his house and starts interviewing him to be a butler at the White House. The interviewer tells Cecil that a high-level employee at the White House observed Cecil working at the hotel and recommended him to be a butler at the White House. Cecil begins his new job during the Eisenhower administration. He serves as butler for eight presidents and into the Obama era. This film is a tearjerker during the last half. Even though nothing is said about todays racial conditions, my wife and I couldnt help feeling about todays Republican issues concerning blacks. Unfortunately, they are trying to go back to the 1950s where blacks in the South couldnt vote. Two states in particular, Texas and North Carolina, which rule by draconian methods, are nothing more than hate mongers, and they dont make any bones about it. Where is the compassion, empathy and scruples of the Republican Party today?L.M. Eastman Lecanto DOUGLASCOHN ANDELEANORCLIFTWASHINGTONFollowing the First Gulf War in 1991, the U.S. imposed a no-fly zone over Kurdistan in northern Iraq, effectively establishing an autonomous region for the Kurds who had been subjected to the worst abuses of Saddam Hussein, including his use of chemical weapons that killed thousands. Syria poses other problems, specifically the fact that the U.S. has two enemies there: the brutal Assad regime and al Qaeda rebels. Still, the Kurdistan solution provides a roadmap for a Syrian solution. Recognizing the existence of two enemies is crucial in defining the objective. It defies logic to strike one enemy if it benefits another enemy, which is what would happen if the U.S. and its allies attack military targets loyal to Assad. True, moderate rebel forces would benefit, but so would al Qaeda, an enemy America has been fighting even before 9/11, when its operatives turned American commercial airliners into devastating missiles. Two enemies require a twoenemy solution. Following the Kurdistan example, the U.S. and its allies should carve out an area of Syria already under rebel control and establish it as a no-fly zone. This could be accomplished with significantly less risk than trying to create a countrywide no-fly regimen that would subject coalition forces to Assads substantial anti-aircraft defenses. Further, such a countrywide regimen would benefit moderate and al Qaeda rebels alike. The second stage of the twoenemy plan would include providing arms, food, housing and medical care for the moderate rebels and their families. The more difficult, but essential, part of the plan would entail the expulsion of al Qaeda rebels from the no-fly sanctuary. Most recently, this concept was employed in rebel-held eastern Libya, which led to the toppling of another brutal dictator, Muammar Gaddafi. There, the cleansing of the area of al Qaeda rebels was less successful, and Libya has paid an ongoing price for that lapse. However, the Libyan campaign proved what could be accomplished without inserting U.S. ground forces. By defining the objective the defeat of both enemies in Syria and applying the lessons of Kurdistan and Libya, the U.S. and its allies have an opportunity to achieve a remarkable victory while saving thousands of Syrian lives at the least risk to U.S. and coalition lives. It is important to fully define that victory. It would not simply be the establishment of a moderate regime in Syria. Such a victory would be a major setback to Assads allies, Iran and its terrorist minions in Hezbollah. This, in turn, would help stabilize neighboring Lebanon and significantly contribute to a lasting peace between Israel and the surrounding Arab countries, including Syria. There are great stakes and a fleeting opportunity at play, and recent history provides a solution, a two-enemy solution. Douglas Cohn and Eleanor Clift author the Washington Merry-Go-Round column, founded in 1932 by Drew Pearson. Small wars are always teetering on the brink of becoming big ones.Max Lerner, 1962 The two-enemy solution A NEW CHAPTER County losing talent with Wesch departure With County Attorney Richard Wesch having been selected as the county attorney for Lee County, it appears the longtime Citrus County professional will be leaving county government. While we wish him well in his new endeavors, we also recognize the county is losing the deep knowledge that Wesch brought to county government of the county and its issues. Born in Long Island, N.Y., Wesch came to Citrus County as a boy. He grew up in Inverness, graduated from Citrus High School, and attended what was then Central Florida Community College before graduating from the University of Florida and the University of Florida law school. Wesch worked his way through school in Citrus County by bagging groceries at the Kash n Karry in Inverness. After finishing law school, he returned to the county to set up a private law practice. He became the general counsel with Citrus Hills Investment Properties prior to joining Citrus County government as an assistant county attorney in 1991. He served in this capacity until becoming assistant county manager in 2000. In 2001, he was named county manager, replacing Gary Kuhl, who had taken a job in Hillsborough County. He served as county manager until 2006, when he was fired on a 32 vote of the commission. After leaving the county manager job, Wesch joined the Citrus County Sheriffs Office as general counsel. He served in this job until accepting the county attorney position in April, 2010, replacing retiring county attorney Robert Butch Battista. Since becoming county attorney, Wesch has provided legal advice to the county commission on a number of issues that created public interest. Some of these include changes in county alcohol sales regulations, the creation of Port Citrus, formation of the Ottawa Avenue/Otis Avenue connector, placing fire services in the sheriffs office, and formation of the fire services MSBU. While his relationship with the county commission has generally been amicable, there have been a few rough spots. Earlier this year, newly-elected commissioner Scott Adams made a motion to fire Wesch. The motion failed for lack of a second. Wesch was also involved in a 2011 controversy when one of the assistant attorneys resigned and sent a letter to commissioners accusing Wesch of fostering a hostile employment environment. Overall, Weschs public actions indicate someone with both an understanding of and affection for the community. His understanding of the community will be missed as the commission moves forward with a replacement to provide legal guidance to its decisions. As Richard Wesch moves forward in his career, we wish him and his family the best in this new assignment. THE ISSUE:County Attorney selected as Lee County Attorney.OUR OPINION:Best Wishes, but a loss of local talent. Questions about landfill Recent articles in the Sound Off have brought attention to the questions regarding the new fire protection MSBU, questions regarding its legality and questions regarding whether its legal to form such an MSBU for an entire county. I would like to also question that if concerns like this apply to the newly formed MSBU that applies to our fire protection, wouldnt those same questions also apply to the MSBU that we pay for for our county landfill on our tax bills every year?No parkway at C.R. 495Regarding the Suncoast Parkway: There is no good reason to put an exit on (County Road) 495. Its a narrow two-lane with houses close to the road. Very expensive to do. They will want to widen the road and buy these houses. There will be an exit on (State Road) 44 with four lanes to Crystal River, four lanes to Inverness. (County Road) 491 will soon be four-laned both north to Beverly Hills and south to Brooksville and (County Road) 490 to Homosassa. The same is true for Cardinal Lane. Then there will be extra manpower at these exits 24 hours a day. Stop and think about it. Take care of kittiesI read this paper every day and I just moved here three years ago and I am so tired of reading about these feral cats that everybody is griping about. People have dumped these cats and thats why theyre here and theyre multiplying and theyre multiplying and theyre multiplying. If people would do what theyre supposed to do and take care of their animals, we wouldnt have them. So instead of complaining, we need to figure out a way to help the animals. And I just dont understand how everybody is griping about them, because animals are just like babies; they need someone to take care of them, cats and dogs. Theyre not supposed to be a wild animal. Theyre not a big bobcat or a mountain lion. Theyre kitt OtherVOICES
PAGE 9
Nobel Prize for Manning?Petitions are being signed by hundreds of Americans for their support for Bradley Manning. He is the United States soldier who was convicted of espionage, leaking military secret files to WikiLeaks. His supporters have petitioned the Oslo Nobel Committee that the Peace Prize should be given to Manning in October. He embarrassed this country by revealing heinous acts committed in secret against other countries and people over these past 50 years. Unfortunately, Manning is being used as scapegoat in order to stop other whistleblowers from doing the same thing. Manning was held for nine months in solitary confinement at Quantico, Va. According to The Nation magazine, he was prohibited from lying down and had to stand at attention every night in the nude. The trial judge presiding over Mannings court-martial ruled that his treatment was illegal. Even the United Nations special committee on torture stated Manning was being treated inhumane and degrading. Since then Manning has been released into the medium-security general population. Presently, there are more than 1.4 million people who have top secret security clearances. Some analysts estimate that more than 2 million Americans have classified information that must remain secret. No one in Washington has a list of the people in charge of secret files. This in itself is a big joke about national security. How can an agency keep track of the huge number of people who are in charge of classified documents? What was contained in the secret files that Manning sent to WikiLeaks? Some national reporters say, That no evidence occurs that a single U.S. soldier or civilian has been harmed as a result of his leaks. A military spokes man has admitted that no casualties in Afghanistan have been traced to Manning, or WikiLeaks. What then is our government really afraid of? Since the 1950s to the present, Washington has been involved in coups that overthrew duly elected presidents and governments; from Central Asia (Iran) to Central America and South America. Our government has become the muscle for American corporations such as sugar, clothing, and big pharmaceutical firms that operate in third world countries. Lobbyists in Washington want our government to keep the minimum wage down in Haiti for the drug companies. Will Washington intervene and help the lobbyists probably. In 2009, President Barack Obama was given the Nobel Peace Prize, who in turn intensified the war in Afghanistan. Thus, embarrassing the Norwegian (Oslo) Nobel Committee. A large number of citizens urged Obama to return the award. He avoided the critics and kept the money. If Obama accepted the Nobel, then why not Manning? All Manning hoped for with his leaks was to open up a dialogue and a debate about the direction our government was heading.L.M. Eastman LecantoMissed opportunity Aug. 29 should have been a day of great celebration, especially for the black community. Fifty years ago, in many states, Florida included, black people could not even walk on the same side of the street as white people. Schools were segregated and drinking fountains had signs for white only on them. When resistance arose in the black community, many blacks were severely beaten and jailed because they tried to exercise rights granted to them by the Civil War. Many politicians in power during the Civil Rights movement fought hard against any further integration. How many remember which political party fought so hard to retain segregation? It was the Democrat party. When they saw that they could no longer control the blacks with segregation, they changed tactics. Today they champion the destruction of the black family and make every effort to keep the blacks locked in poverty. At the same time, somehow the Democrats have convinced those same blacks that giving them just enough to maintain themselves at a poverty level and blaming it on conservatives makes them heroes. How in the world can so many people be fooled by such tactics? In Washington, D.C., speeches made by radical blacks (none of whom are locked in the poverty cycle they claim to decry) spoke out against the lack of progress in the black community. Is there any record of any of them going into those communities to help raise the living standards? If the people who spoke really cared, they would have been reviewing all the gains I mentioned in my first paragraph. That is the real legacy of Martin Luther Kings life dream. There are so many examples of advancement among members of the black community in recent years that should have been celebrated. Many blacks hold elective office in Washington and in statehouses and municipalities all over our nation. In major businesses and educational institutions all over our country, blacks are now respected as leaders. Even our president could not speak to the audience without throwing in his highly partisan political views. He finally did get around to mentioning some personal responsibility. However, the main thrust of his speech was to condemn successful people and blame them for the failings of those who fall behind. It would have been more uplifting for him to encourage everyone to try to do better instead of driving a wedge between the haves and the have-nots. As far as the problems in the black community go, only a real honest effort can reverse the problem. It must begin with those who have the biggest soapbox. They must start encouraging moral responsibility within the black community and promote real families. In todays economy, financially and socially, a two-parent household is without a doubt one of the major keys to moving out of poverty. In addition, young black males need a new type of guidance. All too often, when so many get into trouble, it becomes difficult for the rest of them to avoid suspicion. Yet, every day we meet blacks of all ages who have proven themselves and are living a successful life within our general population. It is time to build up all of our citizens instead of pitting race against race and wealthy against poor. A major step would be to put God back in the Democrat platform and even add His guidance in all our lives. Beginning now we must stop the divisiveness and promote real community spirit. Bob Hagaman HomosassaWatching out for the little guyPlease, please tell me, whos looking out for the little guy? The Public Service Commission sides with Duke (Energy) to recover $175 million for a plant Duke just said they arent going to build in Levy County. So whos looking out for the little guy? Duke donates $495,000 to charity. Why not just pay your taxes and we can all benefit? Oh wait ... I just remembered, to donate to a registered charity is tax deductable. Is this a setup for next years taxes? Whos looking out for the little guy? The sheriff says if you let me take over animal control, fire and whatever, it will lead to lesser operational costs. So where did this fire tax come from? The public meeting was all smoke and mirrors. The thing was decided in advance! And to have the sheriff flood the meeting with his people as to not let the little guy have room. Whos looking out for the little guy? And do we really need to get into Citrus Memorials issues? I read full-page newspaper ads about who is the good guy, but nobody is saying how all this mess is helping to improve the services to the little guy. The county doesnt have the money to provide services, yet we have money for consultants on a port and to build a port. Whos looking out for the little guy? This newspaper is charged with looking out for the little guy in reporting facts that happen, not to select just the stories that dont upset the powerfully influential politician. Is it you ... who watches out for the little guy?Chuck Shinsky InvernessOPINIONCITRUSCOUNTY(FL) CHRONICLEMONDAY, SEPTEMBER2, 2013 A9 (352) 563-6698 (866) 860-BUGS 406 N.E. 1ST ST., CRYSTAL RIVER SERVICE TO FIT ANY BUDGET: ONCE A YEAR QUARTERLY MONTHLY. QUARTERLY PEST CONTROL SERVICE INTRODUCTORY 1ST SERVICE STARTING AT BUY 3, GET 1 GUARANTEED TO BEAT OUR COMPETITORS PRICES LICENSED & INSURED #8688 000FY0E A+ RATING 2013 2013 2013 2013 Expires 9/30/13 Are you tired of getting a cheap come on price, only to be told that your hearing loss is too bad for the sale priced hearing aid to work? Its loss and have worn devices for over 40 years. If you want a cheap come on, see our competitors, if you want real, quality solutions for your hearing, give us a call. Youll be glad you did, and youll Hear Better Now GUARANTEED! Denny Dingler, HAS Audioprosthologist 211 S. Apopka Ave., Inverness 726-4327 Sin ce 1983 Professional Hearing Centers 000FYTU We Can Sell You a Cheap Hearing Aid Like Our Competitors Offer... But Wed Rather Help You With Something That Will Work! 000FVD2 CALL TODAY FOR A FREE QUOTE! Accidents Bad Driving Record DUI Youthful Drivers Canceled SR 22, SR 22 S, FR 44 720 N.E. Highway 19, Crystal River (352) 563-1590 Letters to THE EDITOR Yes to no manThis is in response to the person who said Adams is just a no man. Some of the things that he has talked about include eliminating takehome vehicles, reducing the administrative staff, pay cuts, combining human resources office duties with all constitutional officers and reducing the use of outside labor. All those things were turned down by the rest of the commissioners. What else do you want the man to do?Dawsys domainCitrus County most people call it Circus County. It has now become Sheriff (Jeff) Dawsys domain. He has built a realm for himself and his buddies.Hospital workingResponse to Sell hospital now: Apparently that person hasnt really been paying attention for four years or he and the people that he talks to would know which board has been causing the most problems. Why didnt these people all get upset before it came to this? Why not when the board of trustees took their tax money and never released it to the hospital to run it like it was supposed to be used for? I didnt read or hear about any of you ever acting like you cared about that when all of us should have been speaking out then. The full-page ads are to let small-minded people see that the hospital is still here working and keeping the people of Citrus County healthy no matter what the board of trustees has done to them.Patrol memorialCant Sheriff (Jeff) Dawsy post patrolmen up there at the Vietnam memorials during the weekends in Homosassa so that the people dont sit there and park their cars with their fishing boats and everything around there? I think its disgraceful and I think he ought to do something about it.Cant afford countyPoliticians are supposed to represent the people. Well, with my tax rate rising all the time because of the county commissioners, I cant afford to live in this county any longer. As soon as I can, Im going to sell my house and get out of here. This is ridiculous. I wish they would represent the people sometimes, but they just dont. Were Nature CoastRegarding the naming of outdoor tourist concept. If the countys going to adopt Outdoor Adventure, why not incorporate Nature Coast? Ubiquitously we have pretty much been known as the Nature Coast and I dont see why we should give that up. The other thing is, way back a few years back, Robert Commons came up with the name Where Man and Manatee Play. Maybe that could be recycled or given some consideration. But Outdoor Adventure to cover Crystal River and the county, or rather the term Outdoor Adventure, that doesnt quite get it for a tourist attraction.Stop the bottlingWhy so many sinkholes? Stop these watering bottling companies drawing so many thousands of (gallons of) water every day for their income bonanza. If I recall correctly, they pay a really ridiculously low amount for this great privilege. Put a stop to it. It sure would help us. Sound OFF
PAGE 10
Associated PressA member of the Bureau of Land Management Silver State Hotshot crew from Elko, Nev., stands by a burn operation Friday on the southern flank of the Rim Fire near Yosemite National Park in California. The wildfire has become the fourthlargest conflagration in California history. Associated PressY states twothirds of the land burned since then is located there as well. In Yosemite, 94 square miles have burned. The cause remains under investigation, Baltimore said. Either way, if it was lightning or humancaused, they have not released any findings and we are not sure if and when that will be released, she said. Meanwhile, the dense smoke that obscured Yosemitesornias largest wildfires. The Rim Fire has claimed 111 structures, 11 of them homes, but no lives. NATION& WORLD Page A10MONDAY, SEPTEMBER 2, 2013 CITRUSCOUNTYCHRONICLE Funeral Associated PressBahraini youths masked and wearing headbands with Arabic that reads Al-Mehdi Soldiers participate in a funeral procession Sunday for an anti-government activist in Sehla, Bahrain. Clashes erupted after the funeral for Sadeq Sabt, 22, who died Sunday of injuries sustained a month ago during a protest. Egypts Morsi to be tried for inciting violenceCAIRO Egypts state news agency said the countrys. Hes been held incommunicado since. Prosecutors have accused him of conspiring with foreign groups to break out of prison during the chaos of the countrys 2011 uprising. Sundays decision however is the first referral to trial. Morsi will be tried, along with 14 members of his Muslim Brotherhood, in a criminal court for allegedly committing acts of violence, inciting the killing of at least 10. No date was announced for the trial.Meeting with Israeli lawmakers is delayedJER. Officials on both sides said Sunday that the meeting had been delayed. An Israeli spokeswoman cited the crisis in nearby Syria and high-level Palestinian meetings Abbas is holding this week. She said the meeting is expected to take place in the coming weeks.Bomb kills nine soldiers in NW Pakistan. Two senior army officials said the bombing killed nine soldiers. They spoke on condition of anonymity in line with regulations. No one immediately claimed responsibility for the blast, which happened in a region home to a mix of local Pakistani, Afghan and al-Qaida-linked foreign militants. World BRIEFS From wire reports Mandela returns to his home Discharged from hospital, will still receive care Associatedold leader of the antiapartheidumelas daughters, Makaziwe Mandela, told The Associated Press as she left her fathers home that the family was happy that he is home. Another Mandela family member, grandson Mandla Mandela, said the former presidents return home was a day of celebration. The African National Congress, South Africas ruling party, welcomed the hospital discharge of its former leader. We believe that receiving treatment at home will afford him continuous support from his family and loved ones, it said in a statement. Mandela has been particularly vulnerable to respiratory problems since contracting tuberculosis during his 27-year imprisonment. The bulk of that period was spent on Robben Island, a prison off the coast of Cape Town where Mandela and other apartheidera prisoners spent part of the time toiling in a limestone quarry. Nelson Mandeladischarged from hospital. Associated PressWASHINGTONs top diplomat said. Members of Congress, deadlocked on just about everything these days and still on summer break, expressed sharply divergent opinions about whether to give President Barack Obama the goahead he requested to retaliate with military force against the Assad regime, and what turning down the commander in chief could mean for Americas reputation. Presenting Obamasrisads 1/2 years and dragged in terrorist groups on both sides of the battlefield. Only France is firmly on board among the major military powers. Britains Parliament rejected the use of force in a vote last week. The United Nations on Sunday asked the head of its chemical weapons inspection team to expedite the analysis of tests from samples it collected from Syria last week. Assads government, which has denied allegations of chemical weapons use, reveled in Obamas. Kerry confidently predicted that lawmakers would back limited military strikes. The stakes are just really too high here, he said. Associated PressRepublican Rep. Scott Rigell, R-Va., talks with media Sunday before entering a classified members-only briefing on Syria on Capitol Hill in Washington. The Obama administration on Sunday confidently predicted congressional backing for limited action in Syria. Senior administration officials briefed members of Congress in private Sunday. Further classified meetings would be held over the next three days, said the Secretary of State John Kerry. Citing sarin use, US seeks Congress OK for action Sierra wildfire now fourthlargest in California
PAGE 11
Baseball/ B2 Scoreboard/B3 Golf/B3 Sports briefs/ B3 College football/B4 Puzzles/ B5 Comics/ B6 Classifieds/ B7 Red Sox wrap up sweep of White Sox./B2 SPORTSSection BMONDAY, SEPTEMBER 2, 2013 CITRUSCOUNTYCHRONICLE Crisp, Vogt hit homers as As sweep Rays Associated PressOAKLAND, Calif. Coco Crisp and Stephen Vogt homered, A.J. Griffin struck out seven in seven innings, and the Oakland Athletics completed a three-game sweep of fellow playoff contender Tampa Bay with a 5-1 victory Sunday. The As pulled off a pair of one-run wins before Sundaysgame series with the As starting today.. Vogt then connected for his third home run in the bottom of the seventh, against the club that traded him to the As on April 5. Tampa Bay missed another chance in the eighth. Pinch-hitter Kelly Johnson led off with double, but fresh September additions Luke Scott and Delmon Young failed to deliver against Sean Doolittle. The Rays swept the As in April, then Oakland returned the favor to leave the season series even meaning a possible tiebreaker for the wild card would next go to intra-division records. Rays manager Joe Maddon chose to go with Jamey Wright as a spot starter over lefty Roberto Hernandez against the As left-heavy lineup. Wright went 1 2/3 innings in his first start since 2007 with Texas, leaving with the game tied at 1 in the second. He allowed five of his nine batters to reach base. C.J. RISAK CorrespondentThe new school year has delivered an abundance of change for one of Citrus Countys premier athletes. Alexis Zachar, entering her senior year at Seven Rivers Christian, must refocus. First, shes playing for the first time without older sister Andrea at her side. Its kind of weird, Alexis said shortly after her Warrior volleyball team dispatched of Lecanto in straight sets on Aug. 29. We always played together. Twin towers they called us that since I was little. I cried so hard when she graduated. Its hard to imagine Alexis (who is about 6-foot 4), or Andrea for that matter (6-foot 2), being thought of as little. But theyve always played together, in volleyball and basketball. Andrea is now at the University of Central Florida, and at present the only sports shes playing are the intramural variety. As for Alexis, her sports choices have changed, too. Her considerations for her athletic future have shifted, from the sport that was always at the top of her list basketball to volleyball. The reason is tracheobronchial malacia, a problem Zachar was born with that can severely affect her breathing. And shortness of breath would limit her ability when trying to play at a higher level of basketball. Since volleyball doesnt require as much aerobic ability, Zachar has found her collegiate athletic hopes are now STEPHEN E. LASKO/For the ChronicleAlexis Zachar of Seven Rivers Christian goes up for a kill attempt Thursday against Lecanto. Zachar, the Chronicle s girls basketball player of the year last season, is now focused on playing volleyball in college. See ZACHAR/ Page B3 Kyle Busch locks up spot in Chase Associated PressHAM.Elliott wrecks Dillon to win Truck race. Williams ousts Stephens Associated PressNEWall in the first set Sunday. Thats theres any chance of a letdown after getting past Stephens, Williams replied: Absolutely not. I mean, Ive been at this for a long time, so for me in my career, there are no letdowns. Associated PressTampa Bays Wil Myers tries to avoid the tag Sunday of Oakland catcher Stephen Vogt in the seventh inning in Oakland, Calif. Myers, was called out on the play. Associated PressLleyton Hewitt reacts Sunday after defeating Evgeny Donskoy during the third round of the 2013 U.S. Open in New York. See US OPEN/ Page B3 Kyle Busch Zachar of Seven Rivers adjusting to life on the court without sister
PAGE 12
Associated PressBOSTON could.American League Orioles 7, Yankees 3. Shut out on three singles Saturday, the Orioles were blanked by Andy Pettitte for six innings before their sevenrunys shot against Shawn Kelley (4-2) glanced off the glove of right fielder Curtis Granderson and put the Orioles ahead 4-3. After reliever Boone Logan gave up a bunt single and walk, Jones homer to dead center field came against Joba Chamberlain.Royals 5, Blue Jays 0TORONTO James Shields pitched seven innings of three-hit ball to win his fourth straight decision, Eric Hosmer drove in two runs and the Kansas City Royals beat the Toronto Blue Jays 5-0 to avoid a three-game sweep. The Royals, who entered play 6 1/2 games behind Tampa Bay in the race for the second AL wild-card berth, won for the sixth time in eight games. Shields (10-8) improved to 4-0 with a 1.53 ERA in his past five starts. The right-hander walked one and matched a season-high with nine strikeouts.Indians 4, Tigers 0DETROIT Mike Aviles hit a grand slam in the ninth inning that lifted the Cleveland Indians to a 4-0 win over the Detroit Tigers. The AL Central-leading Tigers had won seven straight against secondplace Cleveland. The Tigers won the season series 15-4, a string of success that gives them a 7 1/2-game cushion in the division with a month left in the regular season. Joe Smith (6-2) got the win after giving up one hit and one walk in the eighth inning, keeping Detroit scoreless after Danny Salazars strong start.Astros 2, Mariners 0HOUSTON Rookie Brett Oberholtzer pitched a four-hitter and Jason Castro hit an RBI double in the eighth inning to lift the Houston Astros to a 2-0 win over the Seattle Mariners. The 24-year-old Oberholtzer struck out five and walked one. He did not allow an extra-base hit in his sixth career start and ninth appearance to lower his ERA to 2.79. Twins 4, Rangers 2ARLINGTON, Texas Kevin Correia pitched seven strong innings and the Minnesota.National League Marlins 7, Braves 0ATLANTA Nathan Eovaldi combined with Steve Cishek on an eighthit shutout, Jeff Mathis homered and drove in three runs, and the Miami Marlins beat the Atlanta Braves 7-0 to end their six-game losing streak. Ed Lucas had a two-run single and Mathis added a two-run double in the Marlins five-run third inning. Eovaldi (3-5) halted Miam.Cardinals 7, Pirates 2PITTSBURGH Matt Holliday and David Freese drove in two runs apiece, and the St. Louis Cardinals beat the Pittsburgh Pirates 7.Cubs 7, Phillies 1CHICAGO Jake Arrieta allowed three hits and a run while pitching into the seventh inning and catcher Welington Castillo drove in two runs to lead the Chicago Cubs over the Philadelphia Phillies 7-1. Arrieta (2-1) retired eight of the first nine batters he faced. Only two Phillies advanced beyond second base in his 6 1/3 innings. Three Cubs relievers combined for 2 1/3 shutout innings. The victory gave the Cubs their first consecutive home wins since a stretch of three straight July 6-9.Dodgers 2, Padres 1LOS ANGELES Zack Greinke allowed one run over seven innings, Yasiel Puig homered in the sixth and the Los Angeles Dodgers beat the San Diego Padres 2-1 to complete a three-game sweep. The NL West leaders earned their 10th sweep of the season and first against San Diego. They extended their roll from August, when the Dodgers went 23-6 for their most successful.Giants 8, Diamondbacks 2PHOENIX Yusmeiro Pet.Rockies 7, Reds 4DENVER Todd Helton doubled for his 2,500th career hit, Michael Cuddyer homered among his four hits and the Colorado Rockies overcame the loss of starting pitcher Tyler Chatwood to beat the Cincinnati Reds 7-4. Helton became the 96th player in major league history to reach 2,500 hits. Shin-Soo Choo homered and had three hits, and Chris Heisey had four hits for the Reds.Interleague Angels 5, Brewers 3MILWAUKEE J.B. Shuck hit a three-run double in the seventh inning to rally the Los Angeles Angels past the Milwaukee Brewers 5-3 for a threegame sweep of their interleague series. Mike Trout tripled and doubled among his three hits to help the Angels finish an 8-1 road trip. C.J. Wilson (14-6) gave up three runs and three hits over six innings, improving to 10-1 in his last 15 starts. AL Associated PressBostons Jarrod Saltalamacchia scores Sunday as Chicago White Sox catcher Tyler Flowers tries to make the play in the second inning at Fenway Park, in Boston. Red Sox complete sweep Big seventh inning lifts Orioles past Yankees 7-3 AMERICAN LEAGUESund.NATIONAL LEAGUESund N.Y. Mets at Washington, late (Zito 4-10). Athletics 5, Rays 1Tampa BayOakland abrhbiabrhbi DeJess lf2010Crisp cf4111 DYong ph1000Dnldsn 3b3000 Fuld lf0000Lowrie ss4120 Zobrist 2b-ss4000Moss rf2111 Longori 3b4000Cespds lf4120 Joyce dh4000Callasp dh4000 Loney 1b4121Barton 1b4021 WMyrs rf4010Sogard 2b2001 DJnngs cf3010Vogt c4111 JMolin c2000 KJhnsn ph1010 YEscor ss2010 Scott ph1000 Loaton c0000 Totals321 71Totals31595 Tampa Bay0100000001 Oakland10100012x5 ELongoria (9), De.Jennings (3). DPTampa Bay 2, Oakland 1. LOBTampa Bay 5, Oakland 7. 2BDeJesus (3), W.Myers (11), Ke.Johnson (11), Lowrie (41). HRLoney (11), Crisp (16), Vogt (3). SSogard. IPHRERBBSO Tampa Bay J.Wright12/331121 Al.Torres L,4-131/331010 B.Gomes2/300001 W.Wright1/300001 McGee2/311100 Lueke2/312211 C.Ramos2/310000 Oakland Griffin W,12-9751117 Otero010000 Doolittle H,22100001 Cook110002 Otero pitched to 1 batter in the 8th. T:58. A,639 (35,067).Orioles 7, Yankees 3Baltimore New York abrhbi abrhbi Markks rf4100Gardnr cf4121 Machd 3b5010Jeter dh4001 A.Jones cf5123Cano 2b5000 C.Davis 1b4000ASorin lf4011 Morse lf4120ARdrgz 3b3000 McLoth lf0000V.Wells rf2000 Valenci dh4120Grndrs ph-rf1000 Wieters c4111MrRynl 1b2100 Hardy ss4123Overay ph-1b1010 BRorts 2b4120Nunez ss4120 CStwrt c2000 ISuzuki ph1010 AuRmn c0000 Totals387127Totals33373 Baltimore0000007007 New York0012000003 DPNew York 1. LOBBaltimore 5, New York 10. 2BGardner 2 (29), Nunez (11). HR A.Jones (28), Hardy (24). SFJeter. IPHRERBBSO Baltimore W.Chen 443355 Gausman W,2-3210013 Fr.Rodriguez100002 Tom.Hunter120001 ODay 100001 New York Pettitte 672203 Kelley L,4-2 BS,1-1022200 Logan 012210 Chamberlain211102 Huff 2/300000 Betances 1/310001 Pettitte pitched to 2 batters in the 7th. Kelley pitched to 2 batters in the 7th. Logan pitched to 2 batters in the 7th. T:30. A,361 (50,291).Red Sox 7, White Sox 6Chicago Boston abrhbi abrhbi De Aza cf4000Ellsury cf4212 LeGarc 2b5010Berry cf0000 AlRmrz ss5230Victorn rf3100 Konerk dh4121JGoms lf1000 AGarci rf3110Pedroia 2b4120 Kppngr 1b3001D.Ortiz dh3023 Viciedo lf4111Nava lf-rf3000 Gillaspi 3b4012Carp 1b3110 Flowrs c4121Sltlmch c2100 Drew ss4111 Bogarts 3b4010 Totals366116Totals31786 Chicago0004100106 Boston04120000x7 EGillaspie (11). DPChicago 1. LOB Chicago 7, Boston 8. 2BViciedo (19), D.Ortiz (29). HRFlowers (10), Drew (11). SBLe.Garcia (3), Al.Ramirez 2 (29), Ellsbury (51), Saltalamacchia (1). CSA.Garcia (3). SFKeppinger. IPHRERBBSO Chicago Rienzo L,1-1355543 Leesman 41/332140 N.Jones 2/300000 Boston Doubront 32/374414 Workman W,4-211/321111 F.Morales H,211/310001 Tazawa H,212/300011 Breslow H,12111100 Uehara S,16-19100001 PBFlowers. T:39. A,053 (37,071).Royals 5, Blue Jays 0Kansas CityToronto abrhbiabrhbi AGordn lf5111Reyes ss4000 Bonifac 2b4221Goins 2b4000 Hosmer 1b5023Encrnc dh4010 BButler dh4000Lind 1b3010 S.Perez c3010Lawrie 3b3000 Mostks 3b4000Arencii c3000 Maxwll rf3000RDavis rf-lf3010 JDyson cf4120Gose cf3000 AEscor ss4110Pillar lf2000 Kawsk ph1000 Sierra rf0000 Totals365 95Totals30030 Kansas City1040000005 Toronto0000000000 EReyes (5), Arencibia (10). DPToronto 1. LOBKansas City 7, Toronto 4. 2BBonifacio (21), Hosmer (28), S.Perez (21), A.Escobar (17). 3BR.Davis (2). SBBonifacio 2 (23), J.Dyson 2 (29). IPHRERBBSO Kansas City Shields W,10-8730019 Hochevar100002 G.Holland100000 Toronto Happ L,3-5465313 Jenkins320000 Wagner100010 McGowan110001 HBPby Wagner (S.Perez). WPMcGowan. T:51. A,961 (49,282). NL Marlins 7, Braves 0Miami Atlanta abrhbi abrhbi Hchvrr ss5120JSchafr rf5010 Yelich lf3220Smmns ss3010 Stanton rf4000EJhnsn ss1010 Coghln rf1000FFrmn 1b2000 Polanc 3b4131Trdslvc 1b1000 DSolan 2b5121J.Upton lf4010 Lucas 1b5112G.Laird c4010 Mrsnck cf3010BUpton cf3000 Mathis c4123Uggla 2b3000 Eovaldi p3000Janish 3b4010 Cishek p0000A.Wood p0000 FGarci p2000 Constnz ph1010 Varvar p0000 CJhnsn ph1010 Totals377137Totals34080 Miami 1150000007 Atlanta0000000000 DPAtlanta 2. LOBMiami 8, Atlanta 10. 2B Mathis (7), E.Johnson (2), Janish (2). 3BSimmons (4). HRMathis (5). SBYelich (4). SEovaldi. IPHRERBBSO Miami Eovaldi W,3-5870026 Cishek 110012 Atlanta A.Wood L,3-321/387722 F.Garcia 42/330012 Varvaro 220012 UmpiresHome, Laz Diaz; First, Cory Blaser; Second, Mike Winters; Third, Tim Timmons. T:44. A,441 (49,586).Cubs 7, Phillies 1PhiladelphiaChicago abrhbiabrhbi Berndn cf4010StCastr ss3111 Rollins ss2000Barney 2b4111 Utley 2b4010Rizzo 1b3011 Ruf rf3111Schrhlt rf4000 Asche 3b4000Sweeny cf3111 Frndsn 1b4000DMrph 3b4110 Orr lf3000Bogsvc lf4220 Kratz c4010Castillo c3112 Kndrck p2000Arrieta p3010 DBrwn ph1000Russell p0000 Diekmn p0000Strop p0000 JCRmr p0000Valuen ph0001 BParkr p0000 Totals31141Totals31797 Philadelphia0001000001 Chicago10130002x7 LOBPhiladelphia 7, Chicago 7. 2BRizzo (34), Bogusevic (6), Castillo (20). HRRuf (12). SBRollins (18). SFSt.Castro, Barney. IPHRERBBSO Philadelphia K.Kendrick L,10-12685514 Diekman100000 J.C.Ramirez112231 Chicago Arrieta W,2-162/331134 Russell110001 Strop1/300001 B.Parker100011Cardinals 7, Pirates 2St. Louis Pittsburgh abrhbi abrhbi MCrpnt 2b5220NWalkr 2b4010 SRonsn rf3120GJones rf4000 Hollidy lf5012McCtch cf3110 Rosnthl p0000PAlvrz 3b4000 Mujica p0000Byrd lf3121 Craig 1b4221Mornea 1b3010 YMolin c5121Buck c4011 Freese 3b4012Mercer ss4000 Jay cf3011KrJhns p0000 Kozma ss4000JGomz p1000 J.Kelly p3110Snider ph1000 Maness p0000JuWlsn p0000 Chamrs ph1000Morris p0000 Pie ph1000 Watson p0000 Frnswr p0000 Totals377127Totals32262 St. Louis3020020007 Pittsburgh0000010012 DPSt. Louis 1, Pittsburgh 1. LOBSt. Louis 8, Pittsburgh 6. 2BM.Carpenter (44), Freese (23), Byrd (29). SFJay. IPHRERBBSO St. Louis J.Kelly W,7-3641125 Maness 100002 Rosenthal 100003 Mujica 121100 Pittsburgh Kr.Johnson L,0-2275521 J.Gomez 300002 Ju.Wilson132210 Morris 110001 Watson 110000 Farnsworth100002Rockies 7, Reds 4Cincinnati Colorado abrhbi abrhbi Choo cf5132CDckrs lf4230 BPhllps 2b3110Culersn lf0000 Votto 1b4000LeMahi 2b5122 Bruce rf4000Tlwtzk ss3100 Mesorc c5121Cuddyr rf4143 Heisey lf4040Helton 1b3010 DRonsn lf1000Arenad 3b3112 Hannhn 3b4020Torreal c4000 Cozart ss4011Blckmn cf4000 Leake p2110Chatwd p1000 Simon p0000Ottavin p0000 Paul ph1010Pachec ph1110 MParr p0000WLopez p0000 Partch p0000Outmn p1000 Ludwck ph1000Belisle p0000 Ondrsk p0000Rutledg ph1000 Brothrs p0000 Totals38415 4Totals347127 Cincinnati0020000114 Colorado11004010x7 DPCincinnati 1, Colorado 3. LOBCincinnati 11, Colorado 7. 2BChoo (31), Co.Dickerson (10), LeMahieu (17), Cuddyer 2 (28), Helton (14). HRChoo (18), Cuddyer (18), Arenado (10). SBChoo (17), Co.Dickerson (2), LeMahieu (17), Cuddyer (10). SFArenado. IPHRERBBSO Cincinnati Leake L,11-641/386624 Simon 2/300010 M.Parra 2/310001 Partch 11/331100 Ondrusek 100000 Colorado Chatwood 242230 Ottavino W,1-2330010 W.Lopez 2/330000 Outman H,1211/300002 Belisle 131102 Brothers 121101 Rays scheduleSept. 2 at L.A. Angels Sept. 3 at L.A. Angels Sept. 4 at L.A. Angels Sept. 5 at L.A. Angels Sept. 6 at Seattle Sept. 7 at Seattle Sept. 8 at Seattle Se West Division WLPctGBWCL10StrHomeAway Texas7957.5816-4L-139-2940-28 Oakland7858.57417-3W-342-2536-33 Los Angeles6372.46715128-2W-431-3732-35 Seattle6274.45617133-7L-131-3831-36 Houston4591.33134304-6W-122-4723-44 East Division WLPctGBWCL10StrHomeAway Boston8256.5948-2W-345-2437-32 Tampa Bay7560.55653-7L-444-2631-34 Baltimore7263.533835-5W-138-2934-34 New York7264.529935-5L-140-2832-36 Toronto6275.45319145-5L-135-3427-41 East Division WLPctGBWCL10StrHomeAway Atlanta8353.6106-4L-149-1934-34 Washington6867.5041477-3L-239-3129-36 New York6272.46320124-6W-328-3834-34 Philadelphia6275.45321145-5L-235-3127-44 Miami5085.37032252-8W-129-3921-46 Central Division WLPctGBWCL10StrHomeAway Pittsburgh7957.5815-5L-145-2534-32 St. Louis7957.5816-4W-141-2538-32 Cincinnati7661.55534-6L-141-2335-38 Milwaukee5977.43420164-6L-330-3829-39 Chicago5878.42621174-6W-227-4231-36 West Division WLPctGBWCL10StrHomeAway Los Angeles8155.5967-3W-443-2838-27 Arizona6966.5111164-6L-139-2930-37 Colorado6573.47117116-4W-140-2925-44 San Fran.6175.44920145-5W-134-3527-40 San Diego6076.44121154-6L-336-3224-44 Central Division WLPctGBWCL10StrHomeAway Detroit8057.5846-4L-144-2736-30 Cleveland7264.529734-6W-140-2632-38 Kansas City7066.515956-4W-135-3335-33 Minnesota5976.43720164-6W-128-3631-40 Chicago5679.41523195-5L-332-3424-45 AMERICAN LEAGUE NATIONAL LEAGUE CITRUSCOUNTY(FL) CHRONICLEMAJORLEAGUEBASEBALL B2MONDAY, SEPTEMBER2, 2013
PAGE 13
SCOREBOARDCITRUSCOUNTY(FL) CHRONICLE In Sundays other fourth-round womens mens. Granollers, who is ranked 43rd, now takes on No. 1 Novak Djokovic, a 6-0, 6-2, 6-2 winner over 95th-ranked Joao Sousa of Portugal. Andy Murray struggled with his breathing on a muggy afternoon but otherwise faced little trouble in a 7-6 (2), 6-2, 6-2 victory over 47th-ranked Florian Mayer of Germany. In the fourth round, hell play 65thranked Denis Istomin of Uzbekistan, who eliminated No. 20 Andreas Seppi 6-3, 6-4, 2-6, 3-6, 6-1. aimed at volleyball. I love basketball, she said. Volleyball is my second favorite sport. We always thought Id grow out of this (affliction). So her training was altered this summer, with a greater emphasis placed on volleyball. This year, I did a lot more volleyball, Zachar said. I was with two different clubs, Ocala Power and OVA (Orlando Volleyball Academy). I played up (with older girls), so it was a very different level of play. Her focus has been duly noted by Seven Rivers coach Wanda Grey. Shes much improved from last year, Grey said. Shes improved her quickness on the front row. I definitely think she can play at the next level. It isnt just her front row play thats improved. Zachar stays on the court to play in the back court more, and her serving is more formidable. Last year I only played the front three, she said. This year Im staying in. And my serving last year, I couldnt hit the side of a barn if I was in it. My hittings improved a lot, too. Just being there (with her summer teams), I had to improve everywhere. Zachar, who was the Chronicles girls basketball player of the year last season and was part of the all-Chroniclevolleyball team, still has work to do. But her work ethic has been rewarded. She recently was named a team co-captain. I asked her to step it up, leadershipwise, Grey said. And she has stepped it up. Shes done everything weve asked. She has improved, but I do think she can improve even more. Its that potential that could ultimately put Zachar where she wants to be, playing volleyball at the collegiate level. ZACHARContinued from Page B1 US OPENContinued from Page B1 On the AIRWAVES TODAYS SPORTS TV AUTO RACING 12 p.m. (ESPN2) NHRA Drag Racing Chevrolet Performance U.S. Nationals (same-day tape) BASEBALL 2 p.m. (FSNFL, WGN-A) Miami Marlins at Chicago Cubs 9 p.m. (SUN) Tampa Bay Rays at Los Angeles Angels COLLEGE FOOTBALL 9:30 a.m. (SUN) Florida International at Maryland (taped) 8 p.m. (ESPN) Florida State at Pittsburgh HIGH SCHOOL FOOTBALL 3 p.m. (ESPN) Godby (Fla.) vs. Dematha (Md.) GOLF 11:30 a.m. (GOLF) PGA Tour Deutsche Bank Championship, Final Round 1 p.m. (NBC) PGA Tour Deutsche Bank Championship, Final Round TENNIS 11 a.m. (CBS) 2013 U.S. Open Mens and Womens Fourth Round 12:30 p.m. (CBS) 2013 U.S. Open Mens and Womens Fourth Round 7 p.m. (ESPN2) 2013 U.S. Open Round of 16 RADIO 8:30 p.m. (WYKE 104.3 FM) Tampa Bay Rays pregame 9:05 p.m. (WYKE 104.3 FM) Tampa Bay Rays at LA Angels Note: Times and channels are subject to change at the discretion of the network. If you are unable to locate a game on the listed channel, please contact your cable provider. Crystal River 14, Nature Coast 8Crystal River 01400 14 Nature Coast 0 800 8 SCORING SUMMARY Second Quarter CR Ryan 1-yd run (kick failed) CR Reynolds 12-yd pass from Ryan (Reynolds to Stephens) NC Smith 96-yd kickoff return (pass failed) NC Safety INDIVIDUAL LEADERS Rushing: CR: T. Reynolds 3-48-0NC: D. Smith 19-76; C. Maner 9-43-0; C. Syblis 6-21-0. Passing: CR: C. Ryan 5-13-0-56; NC: Quigley 4-9-1-17. Receiving: CR: T. Reynolds 4-52-1; R. Vickers 1-4-0; NC: R. McCane 1-10-0; J. Benyola 1-9-0Dunnellon 39, West Port 28Dunnellon14613639 West Port0217028 SCORING SUMMARY First Quarter DHS Kane Parks 32-run (West kick) DHS Kane Parks 35-pass from Kobi Jones (West Kick) Second Quarter WP Drhyromi Maxwell 28-pass from Jerall Townsend Jr. (Haworth kick) DHS Kobi Jones 2-run (kick failed) WP Quandre Woods 78-kickoff ret. (Haworth kick) WP Quandre Woods 3-run (Haworth kick) Third Quarter WP Jalen Stith 55-ret of blocked FG (Haworth kick) DHS Justin Hamm 15-pass from Kobi Jones (Pass failed) DHS Bubba Sims 15-run (West kick) Fourth Quarter DHS Anthony Small 37-INT return (Kick failed) INDIVIDUAL LEADERS Passing: DHS Kobi Jones 5-10, 93 yards, 2 TDs; Jerall Townsend Jr. 9-25, 75 yards, 2TDs, 3INTs Rushing: DHSBubba Sims 34-232, TD; Kane Parks 6-30, TD; Josh Williams 7-24; Jordan Williams 3-17; Kobi Jones 3-13, TD; WPJerall Townsend 8-61; Quandre Woods 9-22, TD; Nick Hatcher 3-24; Tyler Wallace 1-4. Receiving: DHSKane Parks 2-52, TD; Chase Brattin 226; Justin Hamm 1-15, TD; WP Drhyromi Maxwell 5-47, TD; Rickey McDuffie 3-20; Markell Glover-Cronick 1-8.U.S. OpenSunday, At The USTA Billie Jean King National Tennis Center, New York Singles Men Third Round Tomas Berdych (5), Czech Republic, def. Julien Benneteau (31), France, 6-0, 6-3, 6-2. Stanislas Wawrinka (9), Switzerland, def. Marcos Baghdatis, Cyprus, 6-3, 6-2, 6-7 (1), 7-6 (7). Andy Murray (3), Britain, def. Florian Mayer, Germany, 7-6 (2), 6-2, 6-2. Denis Istomin, Uzbekistan, def. Andreas Seppi (20), Italy, 6-3, 6-4, 2-6, 3-6, 6-1. Lleyton Hewitt, Australia, def. Evgeny Donskoy, Russia, 6-3, 7-6 (5), 3-6, 6-1. Mikhail Youzhny (21), Russia, def. Tommy Haas (12), Germany, 6-3, 6-2, 2-6, 6-3. Novak Djokovic (1), Serbia, def. Joao Sousa, Portugal, 6-0, 6-2, 6-2. Marcel Granollers, Spain, def. Tim Smyczek, United States, 6-4, 4-6, 0-6, 6-3, 7-5. Women Fourth Round Carla Suarez Navarro (18), Spain, def. Angelique Kerber (8), Germany, 4-6, 6-3, 7-6 (3). Serena Williams (1), United States, def. Sloane Stephens (15), United States, 6-4, 6-1. Li Na (5), China, def. Jelena Jankovic (9), Serbia, 6-3, 6-0. Ekaterina Makarova (24), Russia, def. Agnieszka Radwanska (3), Poland, 6-4, 6-4.Angels 5, Brewers 3Los AngelesMilwaukee abrhbiabrhbi Shuck lf5113Aoki rf3010 Bourjos cf0000Segura ss3000 Aybar ss5000Lucroy c3100 Trout cf-lf3130KDavis lf4000 Calhon rf4022CGomz cf4122 Trumo 1b4010YBtncr 1b3000 Conger c4110Gindl ph1000 LJimnz 3b4120Bianchi 3b4110 AnRmn 2b3010Gennett 2b2000 Frieri p0000Lohse p1001 CWilsn p1000McGnzl p0000 Hamltn ph0100Wooten p0000 CrRsm p0000D.Hand p0000 DDLRs p0000ArRmr ph1000 GGreen 2b1000Figaro p0000 Totals345115Totals29343 Los Angeles0010004005 Milwaukee0012000003 ECalhoun (6). DPLos Angeles 1, Milwaukee 3. LOBLos Angeles 6, Milwaukee 4. 2B Shuck (17), Trout (35), Calhoun (3), Bianchi (6). 3BTrout (9). HRC.Gomez (19). S An.Romine, Lohse. IPHRERBBSO Los Angeles C.Wilson W,14-6633223 Cor.Rasmus H,1100001 D.De La Rosa H,141/310020 Frieri S,30-3412/300004 Milwaukee Lohse671111 Mic.Gonzalez011100 Wooten L,3-1 2/333321 D.Hand11/300001 Figaro100000Astros 2, Mariners 0Seattle Houston abrhbi abrhbi BMiller ss4010Grssmn lf4000 Frnkln 2b4010Altuve 2b4130 Seager 3b4010JCastro c4111 KMorls dh4010MDmn 3b4010 FGtrrz rf4000Wallac 1b3010 MSndrs lf3000BBarns ph-cf1011 Smoak 1b2000Carter dh-1b3000 Ackley cf3000Crowe cf4020 HBlanc c3000Orhltzr p0000 Hoes rf3000 Villar ss3000 Totals31040Totals33292 Seattle0000000000 Houston00000002x2 LOBSeattle 5, Houston 8. 2BAltuve (23), J.Castro (35), Crowe (2). IPHRERBBSO Seattle Iwakuma 760017 Furbush L,2-52/332200 Wilhelmsen1/300000 Houston Oberholtzer W,4-1940015Indians 4, Tigers 0Cleveland Detroit abrhbi abrhbi Bourn cf4000Dirks lf-cf5020 Swisher 1b3010Iglesias ss4010 Kipnis 2b3000TrHntr rf4000 CSantn c3000Fielder 1b3010 JRmrz pr0100VMrtnz dh4010 YGoms c0000D.Kelly cf2000 Brantly lf3110NCstlns ph-lf2000 AsCarr ss2000Infante 2b4020 Kubel dh3010Avila c3030 MCarsn pr0100RSantg 3b4010 Aviles 3b4114 Stubbs rf4010 Totals294 54Totals350 110 Cleveland0000000044 Detroit0000000000 DPCleveland 1. LOBCleveland 6, Detroit 10. 2BDirks (15), Infante (19). HRAviles (9). SBBourn (21), Swisher (1), Brantley (15). CSIglesias (2). SAs.Cabrera 2. IPHRERBBSO Cleveland Salazar660005 Hagadone1/310010 Allen2/300001 J.Smith W,6-2110010 C.Perez130000 Detroit Verlander740026 B.Rondon100011 Benoit L,4-11/314430 Alburquerque2/300002Twins 4, Rangers 2MinnesotaTexas abrhbiabrhbi Presley cf4131LMartn cf4010 Mstrnn rf3010Profar ss4000 Dozier 2b4010Kinsler 2b4000 Wlngh dh4020ABeltre dh4010 Plouffe 3b4010Rios rf4010 Colaell 1b4010Adduci lf2010 Thoms lf3100Gentry ph1000 Pinto c4121JeBakr 3b3000 Bernier ss4111Morlnd 1b3111 G.Soto c2010 Przyns ph-c1111 Totals344123Totals32272 Minnesota0000300104 Texas0010000102 EProfar (8). DPMinnesota 2, Texas 2. LOBMinnesota 5, Texas 4. 2BDozier (30), Pinto (1), Bernier (3), G.Soto (7). HRMoreland (21), Pierzynski (16). SBMastroianni (2), L.Martin (30), Rios (33). CSPresley (1). S Mastroianni. IPHRERBBSO Minnesota Correia W,9-10751112 Burton H,24121100 Perkins S,32-35100002 Texas Blackley L,2-241/383304 Feliz12/310002 J.Ortiz111101 Soria110002 R.Ross110010Dodgers 2, Padres 1San Diego Los Angeles abrhbi abrhbi Venale rf3000Crwfrd lf3120 Amarst 3b3011M.Ellis 2b4021 Denorfi ph1000AdGnzl 1b4000 Stauffr p0000Puig rf4121 Gyorko 2b4000Ethier cf4000 Blanks 1b4000Uribe 3b3000 Kotsay lf4010A.Ellis c3000 Hundly c3000Punto ss2000 RCeden ss3000Greink p2010 Fuents cf2110HrstnJr ph1000 T.Ross p1000Belisari p0000 Thayer p0000PRdrgz p0000 Hynes p0000Jansen p0000 Guzmn ph1000 Forsyth 3b0000 Totals29131Totals30272 San Diego0010000001 Los Angeles00100100x2 LOBSan Diego 4, Los Angeles 6. 2B C.Crawford (25). HRPuig (14). SBFuentes (1), Greinke (2). CSPuig (8). ST.Ross. IPHRERBBSO San Diego T.Ross 5511110 Thayer L,2-512/311112 Hynes 1/300000 Stauffer 110002 Los Angeles Greinke W,14-3721127 Belisario H,181/310000 P.Rodriguez H,192/300001 Jansen S,24-27100002Giants 8, Diamondbacks 2San FranciscoArizona abrhbiabrhbi Arias ss5110Blmqst ss4020 Abreu 2b5010Eaton lf3121 Posey 1b5232Gldsch 1b4000 Pence rf4332Prado 3b4021 Sandovl 3b4020A.Hill 2b4000 Pill lf3000MMntr c4000 Kschnc lf2000Pollock cf4110 HSnchz c4123GParra rf4010 GBlanc cf4010Corbin p1000 Petit p3011Pnngtn ph1010 Mijares p0000Roe p0000 SCasill p0000Campn ph1000 Scutaro ph1110Sipp p0000 Kickhm p0000Bell p0000 Thtchr p0000 Nieves ph1000 Totals408158Totals35292 San Francisco0103100038 Arizona1000001002 DPSan Francisco 1, Arizona 1. LOBSan Francisco 7, Arizona 7. 2BPosey (32), Pence (32), H.Sanchez (2), Prado (31), G.Parra (33). HRPence (17). SBScutaro (2), Eaton (3). CSAbreu (1). IPHRERBBSO San Francisco Petit W,2-06722110 Mijares2/320001 S.Casilla H,1611/300001 Kickham100001 Arizona Corbin L,13-5595516 Roe220001 Sipp100010 Bell1/343301 Thatcher2/300001 BASEBALL American LeagueBarre. Transferred INF Jayson Nix to the 60-day DL. Released OF Melky Mesa. TAMPA BAY RAYS Selected the contract of OF-DH Delmon Young from Montgomery (SL). Recalled RHP Josh Lueke and C Chris Gimenez from Durham (IL). Reinstated OF-DH Luke Scott from the 15-day DL. National League ATLANTA BRAVES Purchased the contract of RHP Freddy Garcia from Gwinnett (IL). FOOTBALL National Football League JACKSONVILLE JAGUARS Claimed WR Stephen Burton (Minnesota), DB Winston Guy (Seattle), TE Clay Harbor (Philadelphia),, TAMPA BAY BUCCANEERSClaimed DT Chris Jones and WR Russell Shepard off waivers. Released WR Tiquan Underwood and LB Najee Goode. Signed CB Deveron Carr, OL Jace Daniels, LB Kalial Glaud, DT Matthew Masifilo, TE Danny Noble, WR Chris Owusu and T Mike Remmers to the practice squad. Florida LOTTERY Here are the winning numbers selected Sunday in the Florida Lottery: CASH 3 (early) 7 7 7 CASH 3 (late) 1 8 2 PLAY 4 (early) 3 3 5 8 PLAY 4 (late) 7 0 0 3 FANTASY 5 14 15 18 27 32 Players should verify winning numbers by calling 850-487-7777 or at. Saturdays winning numbers and payouts: Powerball: 2 7 25 40 56 Powerball: 20 5-of-5 PBNo winner No Florida winner 5-of-52 winners$1 million No Florida winners Lotto: 10 11 12 17 28 46 6-of-61 winner$3 million 5-of-637$4,189 4-of-62,455$49.50 3-of-645,244$5 Fantasy 5: 4 6 21 28 31 5-of-54 winners$67,323.94 4-of-5350$124 3-of-511,522$10.50MONDAY, SEPTEMBER2, 2013 B3 Garcia leads by two entering final round Associated Pressfor-birdie until a threeputt.Rocco Mediate wins Champions Tour eventCALGARY, Alberta. Tom Byrum had a 64 to finish second. Duffy Waldorf and Kirk Triplett tied for third at 14 under.Gregory Bourdy wins Wales Open by 2 shotsNEW but had a good start with an eagle at the par-5 second hole. He finished even stronger with birdies at 16 and 17 before holing a 15-foot putt at the last for a 67 and an 8-under total of 276.Suzann Pettersen wins Safeway ClassicPORTLAND, Ore. Suzann Pettersen won the Safeway Classic for the second time in three years Sunday, taking advantage of playing partner Yani Tsengs finalround collapse at Columbia Edgewater. and 12th overall.Deutsche Bank ChampionshipSunday, At TPC Boston, Norton, Mass., Purse: $8 million, Yardage: 7,216, Par 71, Third Round: Sergio Garcia65-64-65 194-19 Henrik Stenson67-63-66 196-17 Graham DeLaet67-68-62 197-16 Steve Stricker66-68-63 197-16 Jason Dufner66-66-66 198-15 Roberto Castro65-65-68 198-15 Kevin Stadler64-71-64 199-14 Ian Poulter66-68-66 200-13 Marc Leishman70-67-64 201-12 Jim Furyk70-68-63 201-12 Hunter Mahan65-70-66 201-12 Brian Davis63-72-66 201-12 Charley Hoffman70-65-66 201-12 Nicholas Thompson66-68-67 201-12 Scott Piercy68-66-67 201-12 Jason Day67-67-67 201-12 Keegan Bradley69-65-67 201-12 Matt Kuchar66-66-69 201-12 Chris Kirk66-71-65 202-11 Kevin Chappell68-70-64 202-11 K.J. Choi67-67-68 202-11 Charl Schwartzel67-68-67 202-11 Justin Rose70-63-69 202-11 John Merrick67-69-67 203-10 Ernie Els66-69-68 203-10 Brendan Steele67-67-69 203-10 Brendon de Jonge69-65-69 203-10 David Hearn68-69-67 204-9 Dustin Johnson68-69-68 205-8 Boo Weekley67-69-69 205-8 Bryce Molder71-67-67 205-8 Brandt Snedeker68-68-69 205-8 Stewart Cink66-69-70 205-8 Bob Estes66-69-70 205-8 Daniel Summerhays68-68-69 205-8 Gary Woodland72-67-66 205-8 Phil Mickelson63-71-71 205-8 Jordan Spieth67-66-72 205-8 Harris English66-67-72 205-8 Rory McIlroy70-71-64 205-8 Scott Stallings68-69-69 206-7 Chris Stroud69-70-67 206-7 Camilo Villegas71-68-67 206-7 Adam Scott73-66-67 206-7 Russell Henley70-70-66 206-7 Pat Perez68-72-66 206-7 Kevin Streelman66-71-70 207-6 John Huh66-71-70 207-6 Charles Howell III71-67-69 207-6 Graeme McDowell72-66-69 207-6 Lee Westwood66-72-69 207-6 Tiger Woods68-67-72 207-6 Ryan Moore66-73-68 207-6 Richard H. Lee69-70-68 207-6 Brian Gay67-67-73 207-6 Brian Stuard71-66-71 208-5 Nick Watney69-67-72 208-5 Jerry Kelly66-72-70 208-5 Bo Van Pelt68-71-69 208-5 Luke Donald71-70-67 208-5 Webb Simpson73-68-67 208-5 Martin Kaymer69-72-67 208-5 Zach Johnson69-72-67 208-5 Matt Every70-67-72 209-4 Stuart Appleby74-67-68 209-4 Josh Teater70-67-73 210-3 Billy Horschel72-66-72 210-3 Bubba Watson71-69-70 210-3 Rory Sabbatini70-71-69 210-3 Jonas Blixt66-75-69 210-3 Justin Leonard69-70-72 211-2 Angel Cabrera72-67-72 211-2 Cameron Tringale73-67-71 211-2 Jason Kokrak70-71-70 211-2 Michael Thompson71-70-71 212-1 Patrick Reed68-72-73 213E Coed softball tourney Sept. 14 in Crystal RiverThe Team Mutiny 2013 Summer Coed Softball Classic will be held Saturday, Sept. 14 at Bicentennial Park in Crystal River. There must be a minimum of four girls on the field (six boys/four girls) and every player begins an at-bat with a 1-1 count. There is a $150 entry fee, with three games guaranteed for each team. There will be prizes awarded to the top three teams. For more information or to register contact Woody Worley at 352-613-0866 or worley.wood@yahoo.com.Buccaneers sign two, release two othersTAMPA Kalial Glaud, defensive tackle Matthew Masifilo, tight end Danny Noble, wide receiver Chris Owusu and tackle Mike Remmers to the practice squad.From staff and wire reports SPORTS BRIEF Sergio Garcia
PAGE 14
Associated PressGAINESVILLE No. 10 Florida doesnt have any identity issues. The Gators know exactly who they are under third-year coach Will Muschamp: a blue-collar, physical group thats going to try to beat opponents up and wear them down on both sides of the ball. Its mostly boring, often predictable and fairly successful. Its Muschamps mark. And its Floridas way these days. In the season opener, a 24-6 victory over Toledo on Saturday, the Gators looked to be in midseason form. They ran for 262 yards and two touchdowns, were efficient in the passing game and dominant on defense. Its the same formula that helped Florida win 11 games last season and reach the Sugar Bowl. I had a lot of confidence before today and I feel even more so after today, Muschamp said after the game. When were able to run the ball that effectively, wereidas initial possession, finding a huge hole and crossing the goal line without getting touched. It was the first touchdown the Gators have scored on a season-opening drive in the postTim. Quarterback Jeff wasnt all positive, though. He was sacked twice and fumbled on both, and he failed to connect on any down-field throws. Those have been missing during Muschamps tenure, but the Gators insist they will be part of the run-heavy offense. Big plays will come, Driskel said. You cant force them. We had some deeper throws designed, but sometimes the defense takes those away from you. Later on down the road, theyll be there. Floridasve been coached to play, I dont see anyone being able to block us. That kind of defense is one aspect of Muschamps philosophy. Its also a perfect complement to the ball-control offense. Together, they have the Gators well aware of who they are, what they need to do to be successful and understanding theres plenty of progress left to be made. They always say your most improvements from Week 1 to Week 2, Muschamp said. We hope that adage continues.B4MONDAY, SEPTEMBER2, 2013CITRUSCOUNTY(FL) CHRONICLE COLLEGEFOOTBALL Associated PressLOU schools remarkable run of success that included an NCAA mens basketball title, the womens teams runnerup NCAA finish and an appearance in the College World Series. Bridgewater kicked off his Heisman Trophy campaign by going 23 of 28 for 355 yards. Damian Copeland and Kai De La Cruz each caught two touchdowns and DeVante Parker and Robert Clark each had one. Dyer, the former Auburn star, debuted for Louisville and the Cardinals outgained Ohio 615-273.Saturdays late Top 25 games No. 8 Clemson 38, No. 5 Georgia 35CLEMSON, S.C. Tajh Boyd threw for three touchdowns and rushed for two others, Clemsonss opening weekend. The Tigers took the lead for good, 31-28, on Chandler Catanzaros 24yard field goal in the third quarter. Georgia had a chip-shot try for a tying kick on its next possession, but couldnt get if off after Nathan Theus bad snap Two series later, Boyd led a 12play, 87-yard TD drive that ended with tight end Seckinger tip-toeing the sidelines to get in. Georgias Todd Gurley ran for 154 yards and two touchdowns.No. 12 LSU 37, No. 20 TCU 27ARLINGTON, Texas Terrence Magee ran for two touchdowns in the second half, Zach Mettenberger threw for 251 yards with a key late score and LSU held on for a victory. Odell Beckhams. 15 Texas 56, New Mexico State 7AUSTIN, Texas David Ash threw four touchdown passes and ran for another as Texas shook off a slow start to roll. After falling behind, Texas (1-0) scored 35 points on 15 snaps and finished with a school-record 715 total yards with Ash accounting for 434.No. 16 Oklahoma 34, Louisiana-Monroe 0NORMAN, Okla.. No. 18 Nebraska 37, Wyoming 34LINCOLN, Neb. Ameer Abdullah and Imani Cross each ran for more than 100 yards, Taylor Martinez passed for three touchdowns and Nebraska survived two late turnovers to defeat Wyoming. The Cowboys converted two late Nebraska turnovers into touchdowns to pull within 37-34 with 1:32 left. Nebraska recovered the onside kick after Brett Smiths 47-yard TD pass to Robert Herron.Washington 38, No. 19 Boise State 6SEATTLE Keith Price threw a pair of third-quarter touchdown passes to become the schools alltime leader, and Washington returned to renovated Husky Stadium with a stunning blowout of Boise State. It was the worst loss in Chris Petersens tenure as the Broncos head coach. Price completed 23 of 31 passes for 324 yards. No. 21 UCLA 58, Nevada 20PASADENA, Calif. Brett Hundley passed for 274 yards and two touchdowns and rushed for two more scores, leading UCLAs second-half surge. Jordon James rushed for 155 yards and a touchdown, Shaq Evans had six receptions for 81 yards and a score, and Malcolm Jones caught a late TD pass during a dominant effort by the UCLA offense, which piled up 647 total yards.No. 22 Northwestern 44, California 30BERKELEY, Calif.. Associated PressFloridas Gideon Ajagbe gains yardage as he gets past Toledo linebacker Trent Voss in the second half Saturday in Gainesville. Florida won 24-6. FSU ready to welcome Pitt to the ACC Associated PressP is thats what you come to do thats why you come to play division I football, you come to play the best of the best. And nobody in the ACC has been better through the years than the Seminoles, last seen crushing BCS crasher Northern Illinois in the Orange Bowl. While quarterback E.J. Manuel is now in the NFL, Florida State already has hisstons fastball tops 90 mph and he combines it with a sprinters States athleticism in the old Big East. Stopping the Connecticuts and Rutgers of the world is one thing. Doing it to a team that averaged nearly 40 points a game a year ago is another matter entirely. It doesnt bother me, Pitt linebacker Shane Gordon said. I think well be ready. We know were going to have to work our kinks out, theyyear-old will try to make up for lost time, but hellsts second recruiting class last spring, but its unclear just how hell fit in. The same could be said about the Panthers hes were appreciative of the people who made this happen. Joining the ACC in this fashion is pretty impressive. Florida knows its identity under Muschamp No. 9 Louisville dominates Ohio Associated PressLouisville quarterback Teddy Bridgewater launches a pass Sunday during the first quarter against Ohio University in Louisville, Ky. The ninth-ranked Cardinals cruised to victory in their opener 49-7.
PAGE 15
MONDAY, SEPTEMBER2, 2013 B5CITRUSCOUNTY(FL) CHRONICLEENTERTAINMENT PHILLIPALDER Newspaper Enterprise Assn.John Monks, an English trade unionist who is now in the House of Lords, said, I concede nothing until they throw dirt on my face. A bridge player should concede nothing until he has lost the setting trick. Until then, he should fight for every winner. In this example, South gets into four spades. West leads the heart queen. East takes the trick with his ace and returns the heart three. How should South proceed? North had a maximum single raise, and South was a fraction light for his jump to game. But with so many aces and kings, one should always push, especially when the lure is a game bonus. Initially, this looks like an easy contract. When trumps break 3-2, as they normally will, declarer will lose one spade and two hearts. So he takes the second trick with his heart king and draws two rounds of trumps. Curses! Suddenly South has four losers. But before anyone has time to throw dirt on his face, he should ask if he might be able to take 10 tricks. If so, he needs three clubs, two diamonds, one heart and four spades, the two he has already and either two diamond ruffs, or one ruff and a later trump winner. Declarer should cash his diamond ace, play a diamond to dummys king, and ruff a diamond in his hand. Then he takes his three club winners ending on the board. Now, with nine tricks in, when declarer leads dummys last diamond, East has no defense. If he discards, South ruffs. If East trumps in, South pitches his last heart and must get one more spade trick. (NGC) 109 65 109 44 53 Lif e B e l ow Z ero Lif e B e l ow Z ero Lif e B e l ow Z ero Checkmate PG Lif e B e l ow Z ero Th e Chase PG Lif e B e l ow Z ero PGLif e B e l ow Z ero (NICK) 28 36 28 35 25Sponge.Sponge.Sponge.Sponge.FriendsFriendsFriendsFriendsFriendsFriendsFriendsFriends (OWN) 103 62 103 The Haves, NotsThe Haves, NotsThe Haves, NotsThe Haves, NotsThe Haves, NotsThe Haves, Nots (OXY) 44 123 Enough (2002) Jennifer Lopez. PG-13 Enough (2002) Jennifer Lopez. PG-13 Snapped PG (SHOW) 340 241 340 4Dexter Are We There Yet? MA Dexter (In Stereo) MA The Twilight Saga: Breaking Dawn Part 1 (2011) Kristen Stewart. PG-13 Lawless (2012, Crime Drama) Shia LaBeouf. (In Stereo) R (SPEED) 732 112 732 FOX Football Daily (N) (Live) Fox 1 on 1Mission October Breaking Ground: Ronda Rousey Boxing Golden Boy: Daniel Jacobs vs. Giovanni Lorenzo. From New York. FOX Sports Live (N) (Live) (SPIKE) 37 43 37 27 36Cops PG Cops PG Cops PG Cops PG Cops PG Cops PG Cops PG Cops Cops PG Cops PG Cops PG Cops PG (STARZ) 370 271 370 Miracle (2004) Kurt Russell. (In Stereo) PG Hotel Transylvania (2012) Voices of Adam Sandler. The Wedding Planner (2001) Jennifer Lopez. (In Stereo) PG-13 The Vow (2012) PG-13 (SUN) 36 31 36 ScubaNationInto the Blue G Saltwater Exp. FSU First Look Inside the Rays Rays Live! (N) MLB Baseball Tampa Bay Rays at Los Angeles Angels of Anaheim. From Angel Stadium of Anaheim in Anaheim, Calif. (N) (Live) (SYFY) 31 59 31 26 29Stargate Atlantis An ancient weapon. PG Stargate Atlantis Outsiders PG Stargate Atlantis Inquisition PG Stargate Atlantis The Prodigal PG Stargate Atlantis Remnants PG Stargate Atlantis Brain Storm PG (TBS) 49 23 49 16 19SeinfeldSeinfeldSeinfeldSeinfeldFam. GuyFam. GuyFam. GuyBig BangBig BangBig BangConan (TCM) 169 53 169 30 35 Burden of Dreams (1982) Claudia Cardinale. NR Werner HAn Edison Album (N)Lumieres 1st The Story of Film: An Odyssey (N) A Trip to the Moon Falling Leaves (TDC) 53 34 53 24 26Fast N Loud (In Stereo) Fast N Loud (In Stereo) Fast N Loud: Revved Up (N) Fast N Loud (N) (In Stereo) Turn & Burn The Crown Jewel PG Fast N Loud (In Stereo) (TLC) 50 46 50 29 30Undercover BossUndercover BossUndercover BossUndercover BossUndercover BossUndercover Boss (TMC) 350 261 350 Man on a Ledge Agent Cody Banks (2003) Frankie Muniz, Hilary Duff. (In Stereo) PG Spy Kids: All the Time in the World (2011) PG Source Code (2011) Jake Gyllenhaal. PG-13 Halloween: Res (TNT) 48 33 48 31 34Castle Pandora PG Castle Linchpin PG (DVS) Castle Once Upon a Crime PG Castle Kick the Ballistics PG Rizzoli & Isles Remember Me Castle Kill Shot (In Stereo) PG (TOON) 38 58 38 33 AdvenRegularRegularAdvenRegularMAD PGKing/HillKing/HillBurgersAmericanFam. GuyFam. Guy (TRAV) 9 54 9 44Bizarre FoodsBizarre FoodsBizarre FoodsBizarre FoodsHotel Impossible (N)Hotel Impossible (truTV) 25 55 25 98 55LizardLizardLizardLizardLizardLizardLizardSafeSafeLizardWorkedWorked (TVL) 32 49 32 34 24ClevelandClevelandClevelandClevelandClevelandClevelandRaymondRaymondRaymondRaymondKingKing (USA) 47 32 47 17 18NCIS A package contains two eyes. PG NCIS: Los Angeles Bounty WWE Monday Night RAW (N) (In Stereo Live) PG Summer Camp Winner Takes All PG (WE) 117 69 117 Roseanne G Roseanne PG Roseanne PG Roseanne PG CSI: Miami Backfire CSI: Miami Meltdown CSI: Miami Mommie Deadest CSI: Miami Time Bomb (WGN-A) 18 18 18 18 2010th Inning Americas Funniest Home Videos PG Funny Home VideosWGN News at NineFunny Home Videos Dear Annie: My husband has a wonderful mother, and I am happy that such a terrific woman raised him. The problem is, she wants me to call her Mom. I love her dearly, but I am not comfortable with this. She introduces me as her daughter and signs all of her emails and texts, Love, Mom. Any advice on how to handle this situation?Americans,, Im still married to the brown-eyed man. Hat Creek, Calif. Dear Hat Creek: Many readers compared this to not being attracted to redheads. But its not the same. Selecting an entire group of human beings based on their ancestral heritage is like saying you arent attracted to anyone whose great-grandmother was a redhead. You actually provided an excellent example of our point: You didnt say Swedes or Italians as a group. You said blue-eyed blondes and brown-eyed brunettes. Those preferences occur within many groups, including darkeyed, brunette Swedes and blonde, blue-eyed Italians, which are plentiful. Its not always easy to recognize bigotry in ourselves, and in most cases, it is not intentional. But aside from the obvious fact that people should be judged on an individual basis, Nebraskas friends didnt say they have a problem with a specific feature and African-Americans have a range of features. They also did not say they arent attracted to a specific skin tone. They said AfricanAmericans, making them all the same in looks and personality. You dont have to be attracted to everybody. But when one pronounces an entire group of people to be unappealing based solely on their racial heritage, what, exactly, would you call that? Dear Annie: You recommended NAMIs Family-toFamily program to Parents at Wits End. Idies Snippet for Labor Day (credit Booker T. Washington): Nothing ever comes to one that is worth having, except as a result of hard work.Ann www. creators.com. ANNIES MAILBOX Bridge (Answers tomorrow) GUILTWHEELCOPPER FROSTY Saturdays Jumbles: Answer: When her priceless Ming vase crashed to the floor, she FELLTO PIECES Now arrange the circled letters to form the surprise answer, as suggested by the above cartoon.THAT SCRAMBLED WORD GAMEby David L. Hoyt and Jeff Knurek Unscramble these four Jumbles, one letter to each square, to form four ordinary words. ATPAD LIVIG CRENDH SLAWEE Tribune Content Agency, LLC All Rights Reserved. Jumble puzzle magazines available at pennydellpuzzles.com/jumblemags Answer here: MONDAY EVENING SEPTEMBER 2,ican Ninja Warrior Vegas Finals PGSiberia (N) NewsJay Leno # (WEDU) PBS 3 3 14 6World News Nightly Business PBS NewsHour (N) (In Stereo) Great Performances: Andrea Bocelli Live in Central Park The popular Italian tenor performs. G Aaron Neville: Doo Wop: My True Story (In Stereo) G % (WUFT) PBS 5 5 5 41JournalBusinessPBS NewsHour (N)Antiques RoadshowThe National Parks: Americas Best IdeaWorldT. Smiley ( (WFLA) NBC 8 8 8 8 8NewsNightly NewsNewsChannel 8 Entertainment Ton.American Ninja Warrior Vegas Finals Las Vegas finals. (N) (In Stereo) PG Siberia One by One (N) NewsJay Leno ) (WFTV) ABC 20 20 20 NewsWorld News Jeopardy! G Wheel of Fortune Shark Tank PG (DVS) Mistresses (N) (DVS) Castle The Fast and the Furriest PG Eyewit. News Jimmy Kimmel (WTSP) CBS 10 10 10 10 1010 News, 6pm (N) Evening News Wheel of Fortune Jeopardy! G How I MetMike & Molly 2 Broke Girls Mike & Molly Under the Dome (N) (In Stereo) 10 News, 11pm (N) Letterman ` (WTVT) FOX 13 13 13 13News2013 FOX Fall TMZ (N) PGomg! Insider PGRaising Hope PG Raising Hope New Girl Mindy Project FOX13 10:00 News (N) (In Stereo) NewsAccess Hollywd 4 (WCJB) ABC 11 11 4 NewsABC EntInside Ed.Shark Tank PGMistresses (N) Castle Shark Tank PG (DVS) Mistresses (N) (DVS) Castle The Fast and the FurriestLaw & Order: SVULaw & Order: SVUSeinfeldScrubsBaggageExcused H (WACX) TBN 21 21 PresentThe 700 Club (N) GTurningChildGive Me the BibleJentezenPaidStudioHealingMinistries L (WTOG) CW 4 4 4 12 12King of Queens King of Queens Two and Half Men Two and Half Men Hart of Dixie This Kiss PG Breaking Pointe (N) (In Stereo) PGEngagementEngagementAccording to Jim The Simpsons O (WYKE) FAM 16 16 16 15Chamber Chat Citrus Today County Court Casita Big Dog Auction Adv Your Plumber Moving On GCold Squad (DVS) Eye for an Eye Fam Team S (WOGX) FOX 13 7 7SimpsonsSimpsonsBig BangBig BangRaisingRaisingNew GirlMindyFOX PGCriminal Minds PGCriminal Minds Criminal Minds PGCriminal Minds PG (A&E) 54 48 54 25 27Storage Wars PG Storage Wars Storage Wars PG Storage Wars Bad Ink Bad Ink Bad Ink Bad Ink Bad Ink Bad Ink Modern Dads PG Modern Dads PG (AMC) 55 64 55 Above the Law (1988, Action) Steven Seagal, Pam Grier. R Hard to Kill (1990, Action) Steven Seagal, Kelly LeBrock, Bill Sadler. R Exit Wounds (2001, Action) Steven Seagal, DMX, Isaiah Washington. R (ANI) 52 35 52 19 21To Be AnnouncedCallWildman CallWildman CallWildman CallWildman Call of Wildman CallWildman Call of the Wildman: Viva Live Action! (N) CallWildman CallWildman (BET) 96 19 96 Friday After Next (2002, Comedy) Ice Cube, Mike Epps. R BET Awards 2013 Chris Brown; Mariah Carey. PG, D (BRAVO) 254 51 254 Housewives/NJHousewives/OCTamra--WeddingReal HousewivesBelow Deck (N) Housewives/OC (CC) 27 61 27 33Tosh.0 Tosh.0 Tosh.0 Tosh.0 Tosh.0 Tosh.0 MATosh.0 Tosh.0 The Comedy Central Roast James Franco (N) MA Comedy Roast (CMT) 98 45 98 28 37Dallas Cowboys Cheerleaders Dallas Cowboys Cheerleaders Twister (1996) Helen Hunt. Storm chasers race to test a new tornado-monitoring device. PG-13 Fat Cops (In Stereo) Cops Reloaded Cops Reloaded (CNBC) 43 42 43 The Profit The Profit The Profit The Profit Eco-MeThe Profit Twitter Rev. (CNN) 40 29 40 41 46The Situation RoomErin Burnett OutFrontAnderson CooperThe Cheshire Murders MA Anderson Cooper (DISN) 46 40 46 6 5GoodCharlie GoodCharlie Jessie G Liv & MaddieTeen Beach Movie (2013) Ross Lynch. (In Stereo) Phineas and Ferb Austin & Ally Jessie G A.N.T. Farm Y7 Austin & Ally G (ESPN) 33 27 33 21 17SportsCenter (N)College Football LiveCollege Football Florida State at Pittsburgh. (N) (Live) SportsCenter (N) (ESPN2) 34 28 34 43 49SportsNation (N)2013 U.S. Open Tennis Round of 16. (N) (Live) Olbermann (N) (Live) (EWTN) 95 70 95 48FaithBread...Daily Mass The Journey HomeEvangeRosaryWorld Over LiveThe HeartWomen (FAM) 29 52 29 20 28 Burlesque (2010) Cher. PG-13 The Breakfast Club (1985, ComedyDrama) Emilio Estevez. R Sixteen Candles (1984, Comedy) Molly Ringwald. PG The 700 Club (In Stereo) PG (FLIX) 118 170 Twins (1988) Arnold Schwarzenegger. Premiere. (In Stereo) PG Mean Girls (2004) Lindsay Lohan. PG-13 Beaches (1988, Drama) Bette Midler, John Heard. (In Stereo) PG-13 Heathers R (FNC) 44 37 44 32Special ReportFOX Report The OReilly FactorHannity (N) Greta Van SusterenThe OReilly Factor (FOOD) 26 56 26 DinersDinersDinersDinersDinersDinersDinersDinersThe ShedBubba-QDinersDiners (FSNFL) 35 39 35 MarlinsShipNFL Preseason Football New Orleans Saints at Miami Dolphins. DolphinsFOX Sports Live (N) (FX) 30 60 30 51 Just Go With It (2011, RomanceComedy) Adam Sandler. PG-13 Grown Ups (2010, Comedy) Adam Sandler, Kevin James, Chris Rock. PG-13 Grown Ups (2010, Comedy) Adam Sandler, Kevin James, Chris Rock. PG-13 (GOLF) 727 67 727 Golf Central (N)The Golf Fix (N)PGA Tour Golf Deutsche Bank Championship, Final Round. Golf Central (HALL) 59 68 59 45 54Home Improve. Home Improve. Home Improve. Home Improve. Wild Hearts (2006, Drama) Richard Thomas, Nancy McKeon. Frasier PGFrasier PGFrasier PGFrasier PG (HBO) 302 201 302 2 2We BoughtBeyonc: Life Is but a Dream (In Stereo) MA Horrible Bosses (2011) Jason Bateman. R In Time (2011, Science Fiction) Justin Timberlake. (In Stereo) PG-13 Hard Knocks (HBO2) 303 202 303 Anchorman: The Legend of Ron Burgundy (2004) Hard Knocks: Training Camp With Life of Pi (2012, Adventure) Suraj Sharma, Tabu. (In Stereo) PG Boardwalk Em. VICE MA For Good (HGTV) 23 57 23 42 52Love It or List It GLove It or List It GBeachBeachLove It or List It GHuntersHunt IntlLove It or List It G (HIST) 51 25 51 32 42Counting Cars PG Counting Cars PG Counting Cars PG Counting Cars PG Counting Cars PG Counting Cars PG Counting Cars PG Counting Cars PG God, Guns & God, Guns & God, Guns & God, Guns & (LIFE) 24 38 24 31 Obsessed (2009) Idris Elba. A stalker threatens a married mans idyllic life. Tyler Perrys Madea Goes to Jail (2009, Comedy) Tyler Perry. PG-13 Madeas Family Reunion (2006, Comedy) Tyler Perry. PG-13 (LMN) 50 119 Hush (2005, Suspense) Tori Spelling, Victoria Pratt. (In Stereo) The Surrogacy Trap (2013, Drama) Adam Reid, Mia Kirshner. (In Stereo) NR Maternal Obsession (2010, Suspense) Jean Louisa Kelly. (In Stereo) NR (MAX) 320 221 320 3 3 Con Air (1997) Nicolas Cage. Vicious convicts hijack their flight. R The Lucky One (2012, Drama) Zac Efron. (In Stereo) PG-13 Jawbreaker (1999) Rose McGowan. (In Stereo) R Strike Back (MSNBC) 42 41 42 Lockup G Lockup G Lockup G Lockup G Lockup G Lockup G WANT MORE PUZZLES? Look for Sudoku and Wordy Gurdy puzzles in the Classified pages.
PAGE 16
B6MONDAY, SEPTEMBER2, 2013CITRUSCOUNTY(FL) CHRONICLECOMICS Pickles Crystal River Mall 9; 564-6864 Jobs (PG-13) 1:45 p.m., 7:45p.m. Kick-Ass 2 (R) 7:50p.m. Lee Daniels The Butler (PG-13) 1 p.m., 4 p.m., 7p.m. Monsters University (G) 1:50 p.m., 4:50. The Mortal Instruments: City of Bones (PG13) 1:15 p.m., 4:15 p.m., 7:15p.m. One Direction: This Is Us (PG) 4:30 p.m. One Direction: This Is Us In 3D. (PG) 1:30 p.m., 7:20p.m. Nopasses. Paranoia (PG-13) 4:45 p p:15 p.m. Jobs (PG-13) 7:20 p.m. Lee Daniels The Butler (PG-13) 12:45 p.m., 3:50 p.m., 7p.m. Monsters University (G) 1:30 p.m., 4:30p.m. The Mortal Instruments: City of Bones (PG13) 1 p.m., 4 p.m., 7:10p.m. One Direction: This Is Us (PG) 4:45p.m. One Direction: This Is Us In 3D. (PG) 1:45 p.m., 7:45p.m. Nopasses. Planes (PG) 2 p.m., 5p.m. Were the Millers (R) 1:15 p.m., 4:15 p.m., 7:30 KPSRX LPA FN P EXTPG PITXFMPJ CRKFLPA GCPG HTRHKT MTKTSXPGT SA ERFJE RVG PJL SVAFJE HXRLVMGN IPLT FJ MCFJP. LPZFL KTGGTXIPJPrevious Solution: Id rather be a could-be if I cannot be an are; because a could-be is a maybe who is reaching for a star. Milton Berle (c) 2013 by NEA, Inc., dist. by Universal Uclick 9-2
PAGE 17
MONDAY,SEPTEMBER2,2013B 7 CITRUS COUNTY (FL) CHRONICLE CLASSIFIEDS Fax: (352) 563-5665 l Toll Free: (888) 852-2340 l Email: classifieds@chronicleonline.com l website: line.comTo place an ad, call563-5966 ChronicleClassifiedsClassifieds In Print and Online All The Time697161 000FUY2 000FUXP Estate Liquidations and Auctions LLC AUCTION FRIDA Y 9/6/2013 6:00 pm 628 SE HWY19 Crystal River 352-228-4920 est ateliquidations andauctions.com AU 4381 /AB 3202 ALUMINUM FOLDING LADDER, HEAVY DUTYFour 4 ft. sections $60.00 352 382 4037 MITER SAW RIGID 12 COMPD. With adj laser on Rigid vehicle. 2 extra blades $300 352-860-2701 ROCKWELLBELT SANDER $100 HEAVY DUTYMADE OF METALNOTPLASTIC INVERNESS 419-5981 ROLLER GUIDED STANDS Sears Heavy DutyAdjustable Roller Stands. In Box, never used. $70.00 586-8931 KENMORE BOX-TYPE FREEZER Freezer has a little rust on it but works great.Asking $50. Inverness Telephone: 352-860-0302 RANGE-GE self-clean, elec, glass top.Exc $125; GE Dishwasher, built-in, Exc cond $125. Both bisque (352) 270-8343 REFRIGERATOR. LG 26 cu. ft. side by side stainless steel refrigerator with automatic ice maker and filtered water. Excellent condition. $400. call 352-419-4482. Samsung Refrigerator white, side by side all computerized inside & out, $600. Call Walter (352) 527-3552 SMITTYSAPPLIANCE REPAIR.Also W anted Dead or Alive W ashers & Dryers. FREE PICK UP! 352-564-8179 WASHER Drafting Board white tubular frame. Includes a parallel arm clamp on protractor. 42x31 $60 352-816-4879 Fire Proof 3 Drawer filing cabinet, $50, 3 Drawer file cabinet w/safe $50 OBO 601-2346 / 601-2214 P/T DELIVERY HELPApply In Person Mon thru Fri 10a-4p EASY LIVING FURNITURE 4100 W Gulf to Lake Hwy., Lecanto No Phone Calls AIRLINE CAREERSbegin here -Get FAA approvedAviation MaintenanceTechnician training. Housing and Financial aid for qualified students. Job placement assistance. CallAviation Institute of Maintenance 877-741-9260 www .FixJet s.com MEDICALOFFICE TRAINEES NEEDED!Train to become a Medical Office Assistant. NO EXPERIENCE NEEDED! Online training gets you Job readyASAP. HS Diploma/GED & PC/Internet needed! (888)528-5547 Well Established Auto BusinessNeeds Investors minimum. 10% return Owner 352-461-4518 3 pc 1924 Wicker set, white, $200 352 601-2346 352-601-2214 APPLIANCES like new washers/dryers, stoves, fridges 30 day warranty trade-ins, 352-302-3030 CLERICALLocal contractor seeking P/T to possible F/T, Accts Payable/Purchase Order candidate. must posess good computer skills in Microsoft Windows & Excel Spread sheets. Must be dependable and detailed oriented for this position. Knowledge of accounting software helpful but not mandatory. Bckgrnd check & drug-screening required after hire. Qualified applicants email resume to: jrogers@fandh contractors.com FLORAL DESIGNERExp. ONLY, P/THrs. 352-726-9666. Annie W Johnson Service Center is accepting applications for aCLIENT SERVICE COORDINATORThe role of CSC is to provide service to the client by assisting in a variety of tasks, including but not limited to fulfilling client needs, ie. food distribution, answering client questions and concerns, including all incoming phone calls. The CSC will be empathetic to the client, have self-control, and be solution driven. Familiar with a variety of nonprofit concepts, practices, and procedures. Relies on experience and judgment to plan and accomplish goals. A wide degree of creativity and latitude is expected. Applications accepted at 1991 Test Ct. Dunnellon, FL 3443170 CR 124A Unit 4 Wildwood QUALIFIED A/C SERV TECHExp Only & current FL DR Lic a must. Apply in person: Daniels Heating & Air 4581 S. Florida Ave. Inverness career-opportunities 000FZ1ERECEPTIONIST DISPATCHER BILLINGFULL-TIME EXPERIENCE REQUIREDApply in Person: 6970 W. Grover Cleveland Blvd. Homosassa Tues. 9/3 Fri. 9/6 9am-4pm Annie W Johnson Service Center is accepting applications for aTRUCK DRIVERfor pickup and deliveries in the Dunnellon area. 2 years experience preferred, clean driving record and background checks required. Applications accepted at 1991 W Test Ct. Dunnellon, Fl 34431. NEEDEDExperienced,Caring & DependableCNAs/HHAsHourly & Live-in,flex schedule offeredLOVING CARE(352) 860-0885 Need a JOB? ClassifiedsEmployment source is... Free KittensBeautiful & Healthy eyes 1 male, 1 female (352) 442-4131 FREE Part Bengal Cat Young Male, neutered, he is a lap cat and likes to be held & have lots of attention. Are you home most of the time to give him lots of love? call for more information 352-464-1567 Kittens 2 male, 2 female. 6 weeks old, box trained. Very cute&good w/ kids and animals. (352) 228-0280 Mini Pin, Mix, male, 2yrs old, tri color, great with kids & sm dogs. 352-812-9257 Power House/GYM. You take down and haul and its yours for free 352-228-3040 Lost Camera Photo Card Homosassa Area (352) 464-4239 LOST CAT Solid Black, male, Wheaton Point & Lake Front Dr. Hernando Please check your sheds. REWARD 352-419-5143 Lost Dentures off of Golden Rd & 488 at boat ramp. Reward offered (352) 453-6194 Lost Dog Basset Hound Mix Male, Homosassa Area (352) 897-1366 Lost Horse, 8/27 Brown w/ black mane & tail, tatoo on left shoulder, Istachatta Area REWARD (727) 244-4451 Lost Key w/key remote, Pontiac Crystal River, Walgreens or Home Depot 352-563-5226 Found Cat Very Friendly, gray, brown & black fluffy tail, male unneutered Connell Heights Call (352) 746-8400 Animal Shelter ID #20828844 I I I I I I I I Tell that special person Happy Birthday with a classified ad under Happy Notes. Only $28.50 includes a photo Call our Classified Dept for details352-563-5966 I I I I I I I I IAM LOOKING FOR A GOOD WOMAN Up to age 38. Are you looking for a good man-HERE I AM Call 352-422-0440 Home 352-628-9416 I I I I I I I I Tell that special person Happy Birthday with a classified ad under Happy Notes. Only $28.50 includes a photo Call our Classified Dept for details352-563-5966 I I I I I I I I $$ TOPDOLLAR $$ For Wrecked, Junk or Unwanted Cars/Trucks $$ (352) 201-1052 $$ 3 Adult Cats spayed/neutered female calico & torti; male-orange cat. Emergency situation Free to good home. (352) 427-7781 9 FREE PUPPIES 2 females, 7 males (352) 364-1072 Ally Cats 8 wks old, great with kids pets and people, please call if interested (352) 419-7393 Christmas Decorations Various Christmas items. All for free 352-228-3040 fertilizer horse manure mixed with pine shavings great for gardens u load and haul 352-628-9624 FREE KITTENS 7 wks. old, 1 male, 1 female pictures available (352) 436-7996
PAGE 18
B8MONDAY,SEPTEMBER2,2013 CLASSIFIEDS CITRUSCOUNTY( FL ) CHRONICLE All Tractor & Tree Work Land Cleared, Hauling 1 time Cleanup, Driveways (352) 302-6955 Davies Tree Service Serving Area 15yrs. Free Est. Lic & Ins cell 727-239-5125 local 352-344-5932! COUNTYWIDE DRY-W ALL D & R TREE SERVICE Lawn & Landscape Specialist. Lic. & Ins. Free Est. 352-302-5641 All Major Credit Cards Tweet Tweet Tweet Follow the Chronicle on citruschroniclenews as it happens right at your finger tips. INTERIOR/EXTERIOR & ODD JOBS. 30 yrs J. Hupchick Lic./Ins. (352) 726-9998 Painting & Wallpaper Removal, Husband & Wife Team. Excel Ref. Free Est. 352-726-4135 Bay Leak Detection for all Pools & Spas Lic#G13000070891 Ins. 352-433-6070 CALLSTELLAR BLUE All Int./ Ext. Painting Needs. Lic. & Ins. FREE EST. (352) 586-29961 AFaux Line, LLC Paint, pres-wash, stains 20yrs exp, Cust. Satisfaction Lic/Ins 247-5971 CALLSTELLAR BLUE All Int./ Ext. Painting Needs. Lic. & Ins. FREE EST. (352) 586-2996 CHRIS SATCHELL PAINTINGASAP 30 yrs. Exp., Excel. Ref. Insured 352-464-1397 Comfort Works, Inc. Air Conditioning and Heating Service Res//Com352 400-8361 Mention this ad and get a service call for $19. Exp 9/30/13 Lic# CAC1817447 Install, restretch, repair Clean, Sales, Vinyl Carpet, Laminent, Lic. #4857 Mitch, 201-2245 #1A+TECHNOLOGIES All Home Repairs. All TVs Installed lic#5863 352-746-3777 T A YLORS TOUCH Home Repairs, painting,flooring, lic. & Ins. (352) 678-9094-W ALL25 yrs exp. lic.2875, all your drywall needs! Ceiling & Wall Repairs. Pop Corn Removal 352-302-6838 M& W Interiors Inside/Out Home Repair Wall/Ceiling Repair Experts, Popcorn Removal,DockPainting & Repair(352) 537-4144 #1AAPPLIANCEAPPEAL Yardscape, Curbing, Flocrete. River Rock Reseals & Repairs. Lic. (352) 364-2120 000FUXT BEVERLYHILLS 2/1 Fl Rm, $500 mthly 1st, last, sec. 106 S. Adams St. (352) 422-6407 INVERNESS1/1 $465 near CM Hospital & Medical Offices 352-422-2393 INVERNESS2/1, no pets, all appl, waterview, $550/mo. 352-860-0904 212-6815 CRYSTALRIVER5 bedroom, 3 bath in Meadowcrest. $1,700.00/mo. No Pets. (352) 601-8445 HOMOSASSANice 1988 3/2 DWMH lg corner lot, covered parking & utili., sheds. many up grades, cash sale $44,900 628-4819 / 228-2175Registered Lots of Colors Ask about my Summer Discount, Beverly Hills, FL (352) 270-8827 BRINGYOUR FISHING POLE! INVERNESS, FL55+ park on lake w/5 piers, clubhouse and much more! Rent includes grass cutting and your water 2 bedroom, 1 bath @$500 inc H20. Pets considered and section 8 is accepted. Call 800-747-4283 For Details! FLORALCITY2/1, $375/mo. Pet OK. Rent to own (352) 422-3670, 422-7636 1986 Manufactured Home, Laminate floors, great shape $19,900 352-795-1272 1991 Manufacture dHome, owner financing or cash willing to make a deal OBO with reasonable offer $24,900. Will not last 727-967-4230 $11,094, DISCOUNT New Jacobsen, 2085 sq. ft., 4BR/3BA BAD CREDIT? FORECLOSURE? BANKRUPTCY? Want your own home? I can help!! 35% down cash or land and you are approved. No gimmick, 386-546-5833 Palm Harbor Homes 4/2 Stock Sequoia 2,200 sq ft $12K OFF! FOR FREE PHOTOS.... John L yons @ 800 622 2832 ext 201 for det ails Tired of Renting? Super clean 2004 3BR/2BA, on acre ready to move in!!! $3,500 down, $380.03/mo. W.A.C. Call 386-546-5833 for details Wont last! USED HOMESSingle, Double & Triple Wides Starting at $6,500 Call (352) 621-9183 2011 Live Oak 4BR/2BA $46,900, 28x60 Golf Cartexc. condition exc. batteries w/back seats from $1500. (352) 527-3125 RAYS GUN SHOP Stokes Flea Mkt Cry.Riv Mossberg 715T22-AR $295. NRA-concealed classes 586-7516 Two Place Aluminum Jet Ski Hoist $500. (352) 341-4178 TandemAxel 16 X 6 can be used as car hauler or utility, home built, you finish $500 Inglis (352) 949-7874 WantedSmall Galvanized single axel boat trailer, Text info to 352-220-3682 4 yr old Umbrella cockatoo $2000 & Cocktail $100. Both hand fed, very tame, incl. cages, food, toys. Lv Mg 352-503-6604. Miniature Schnauzer Pups!AKC, born 5/20/13, 2 males, Health Cert. & all shots current, paper & crate trained. Cash discount! (352)464-0916 Ultimate Water Condtioner for salt system. Pd. $2500. asking $300. obo (352) 746-5171 WET/DRY VAC Craftsmans 16 gal., 6HP. $40. Maple Couch Table 52 L,15 W, 27H w/glass top $25 (352) 344-1088 Bedside Commode Aluminum Walker both have adjustable legs 20.00 EACH 352-464-0316 CUSTOM 4 wheeled walker, brakes seat basket, even footrests ONLY$85.00 352-464-0316 Manual Wheelchair with footrests, great shape $100.00 352-464-0316 POWER CHAIR Excellent Condition. NewTires, brakes & seat. $500.00. Call 352-341-4606 Safety Bath Tub Grab Bar, it clamps to the side of the tub ONLY$25.00, 352-464-0316 TRANSPORTCHAIR (SMALLWHEELS) Great shape with footrest 90.00 352-464-0316 IBANEZ GUITAR IbanezAW30ECE acoustic electric guitar.Beautiful finish. Plays and sounds great.Small ding on rosette. $250 with hard shell case.Beverly Hills. 352-527-0433 PIANO LESSONS Study Piano w/ Rick D Beginner to Advanced All styles 352-344-5131 COMFORTER/QUEEN WITH SHAMS,BEDSKIRT/ COPPER/TAN/GREEN $50.00 352-564-4214 CUISINARTBRAND Juice Extractor. Brand New paid $150. Sell for $100. 352-621-0175 Die Cast Car Collection 1/18th scale 30 cars, must buy entire Collection $300 (352) 726-9151 ELECTRICTREADMILL SPORTCRAFT4.9 wide trac all electronics work super shape only 185.00 call David 352 464 0316 ELLIPTICALIMAGE 8.0ALLELECTRONICS WORK SUPER GREAT.ITCOSTOVER 700.00 NEW,ONLY 175.00 352 464 0316 EXERCISE BIKE (UPRIGHTTYPE) works great only 90.00 352 464-0316 HOME GYM Total body workout. In excellent condition. $85.00/OBO 352-637-2647 MANUALTREADMILL GREATSHAPE NEARLYNEW ONLY 75.00 352 464 0316 Olympic Bench Press $150. Plate Loading Leverage Squat/Calf Machine $200. (352) 726-9151 Concealed Weapons Permit Course DANS GUN ROOM (352) 726-5238 Fear No-Evil GunsHi-Point & Beretta Concealed Classes 352-447-5595 Named Handbags Lg. Louis Vuitton $100, Coach nice leather, numbered $100 both are in good condition (352) 212-8594 !!!! LT225/75R 16 TIRE!!!! Good Year LightTruck Great Shape 90% Tread ONLY60.00 464-0316 !!!!!!!!!! LT225 /75 R 16 !!!!!!!!!!!!! GOODYEAR LIGHTTRUCKTIRE (1) 90%TREAD 50.00 352 464 0316 3 DOUBLE ROLLS FLORALWALLCOVERING $25 VINYLPRE PASTED 165 SQ FT NEW 419-5981 23 PINE WOOD HEARTS,TEDDY BEARS, BUNNIES $25 E-MAILPHOTOS 419-5981 1913 WHITE ROTARY Treadle Sewing machine $200 (352) 212-8594 APPLIANCES like new washers/dryers, stoves, fridges 30 day warranty trade-ins, 352-302-3030 BLOWER/VACUUM WORX-WG500 $50 STAMINAINDOOR PRO CYCLE $60 352 637 5209 BURTON STOVE ON THE GO $20 LIKE NEW WORKS IN CAR/TRUCK 12 VOLT INVERNESS 419-5981 BUYER BE AWARE Dont be fooled by ridiculous offers! FREE HEARING AID CONSUMER GUIDE This FREE guide will let you compare all makes and models BEFORE you buy hearing aids!Call 795-1775 and we will mail you one TODAY! Chevy Silverado Aluminum Running Boards, great shape ONLY$100.00 352-464-0316 Chevy Silverado Bra for 4 headlights Great Shape ONLY $80 352-464-0316 Chevy Silverado Bra for 4 headlights Great Shape ONLY $80 352-464-0316 ELECTRIC SMOKER ( LITTLE CHIEF) COST 120.00 NEW / USED IN BOX ONLY70.00 352 464 0316 Garage Doors 7x18 w/openers and hardware $350. (352) 464-1977 GAS GRILL 2 burners Includes gas tank. $40.00 352-344-5311 GENERATOR: B/S 10 HP,5250 running watts,7350starting watts.NEW, never used. Paid $650, sell for $350 obo Ed 352-746-4160 GRILLOUTDOOR GRILLGOOD CONDITIONASKING $80.00 CALL352 897 4681 HAMMOND ORGAN with padded bench. Gd cond. $100.00 352-344-5311 Harley Mufflers Slide on Original NEW 1350/1450 ONLY$90.00 352-464-0316 HEAT PRESS 15X15; Includes large case of baby tees. size 6mo & up. Doll to display shirts. $600 for all. (352) 527-4301 KITCHEN COUNTER TOPCANISTER SET $10 DECORATIVE CERAMIC CAN E-MAIL PHOTO 419-5981 PETGEAR STROLLER Like a baby stroller, can email pics. $85.00 352-513-4027 PETSTAIRS-ANIMAL PLANETSolid wood. Never used. $35.00 Can e-mail pics 352-513-4027 RUBBER RIDING BOOTS $15 BLACK LIKE NEW SIZE 43L EUR E-MAILPHOTO 419-5981 Dining Rm Table 62x41 w/ 22 self-storing leaf, 4 chairs all teak,made in Denmark $475 (352) 382-4779 OAK HUTCH LIghted w / 3 glass doors, 3 cabinets underneath. Exc Cond. $200 (352) 341-2574 HEDGE TRIMMER 24V B&D cordless-3 batteries, 2 chargers $110; CHIPPER SHREDDER-Central Machinery $200 352 637 5209 HOMOSASSASat. through Sat. 8am NO SUNDAY SALE 3 Family Moving Sale Name brand clothing all Sizes, sell by bag. Qn. matt. set, like new carpet cleaner, fishing polls deer stand 5011 S. Canary Palm Terrace CABINETS white kitchen, you remove & you haul, includes counter tops $300 (352) 527-8993 GENERATOR Briggs & Stratton, 5250 watts, used once. Exc Condition. $400 (352) 527-8993 CAMCORDER Panasonic PV-A218 Camcorder w/Case. New $600.00 Sell for $100.00 352-746-5421 PA TIOTABLE 3 Cushion Couch med. brown, microfiber, excel. cond. No pets, no smoking $50. (352) 637-0050 4 pc. Sectional Sofa camel microfiber w/2 recliners $400. Black leather chair. $300. Both exc. condition! (352) 382-7454 Antique Cherry Dresser withTwin Mirrors. $350 (352) 212-8594 BAR STOOLS Heavy Duty Wrought Iron Bar Stools beige. 30 f / seat to floor. Exc. Cond. $70.00 586-8931 19
MONDAY,SEPTEMBER2,2013B 9 CITRUS COUNTY (FL) CHRONICLE CLASSIFIEDS 000FUY0 0 0 0 8 X G V For more information on how to reach Citrus County readers call 352-563-5592. I Buy Houses Cash ANY CONDITION Over Financed ok! call ** 352-503-3245** HANDYMAN SPECIAL2/1, EZ 3bd 52k Cash 352-503-3245 TONY Pauelsen Realtor ILLTAKE NEW LISTINGSBUYING OR SELLINGSALES ARE WAY UP!TOP PERFORMANCEReal estate Consultant 352-303-0619 tpauelsen@ hotmail.com Your Worldof garage sales Classifieds ww.chronicleonline.com SANDI HARTRealtorListing and Selling Real Estate Is my Business I put my heart into it!352-476-9649sandra.hart@ era.com ERA American Realty 352-726-5855 Tweet Tweet Tweet Follow the Chronicle on citruschroniclenews as it happens right at your finger tips HOMOSASSA4/2 BLOCK HOME, MOTHER IN LAWAPT. MICHELE ROSERealtorSimply put I ll work harder 352-212-5097 isellcitruscounty@ yahoo.com Craven Realty, Inc. 352-726-1515 UNIQUE & HISTORIC Homes, Commercial Waterfront & Land Small Town Country Lifestyle OUR SPECIALTY SINCE 1989LET US FIND YOUAVIEW TO LOVEwww. crosslandrealty.com(352) 726-6644Crossland Realty Inc. Inverness Cute 3/1, Highlands, $49K/offer, owner financing possible, good starter home/rental (352) 422-4864 Inverness Nice 3/2 home w/detached apartment, fenced yard, good neighborhood.Apt. rent can pay mortgage. $79OA NATURE PRESERVE HOME IS AFORECLOSURE SHORTSALEANDTHE BANK IS WORKING WITHTHE SELLERS. THIS HOME WAS BUILTIN 2005 dennis_neff @yahoo.com TAMI SCOTTExit Realty Leaders 352-257-2276 exittami@gmail.com When it comes to Realestate ... Im there for you The fishing is great Call me for your new Waterfront Home LOOKINGTO SELL? CALLMETODAY! 3/2/2, 328 S. Monroe 352-464-2514 CRYSTALRIVER2/1/1, Cent. loc. clean $700. 352-563-0166 CRYSTAL RIVERWaterfront Eaglepoint 3/2 $900.: 2/1 $496 212-2051, 220-2447 Homosassa3/2 $775. first, last, sec. pets ok, (352) 434-1235 INVERNESS3/2 $775 Monthly 306 Hunting Lodge Dr (352) 895-0744 INVERNESS4/2/1, handicap access. CHA, remodeled $750 mo 352-422-1916 INVERNESSBeautiful 2/1, gated comm. 55+pool, clbhs activities, 5405 S. Stoneridge. $650 + dep. (330) 806-9213 LECANTO3/2 1 acre $650 mthly, plus deposit, small pet ok w/extra deposit, Lecanto school system 352-220-0802 RENT TO OWN!! No Credit Check! 3BD $750-$850 888-257-9136 JADEMISSION.COM HERNANDOAffordable Rentals Watsons Fish Camp (352) 726-2225 CRYSTALRIVERRooms in house, Full Kichen, Near Publix, furn, one price for elec, W/D, H20, cable,+ WIFI $115wk/ 420mo $120wk/430mo 352-563-6428 Wanted to Rent 1200 or more sq. ft. of open area, air & heat, no carpet for Inverness Florida Kennel Club Dog Classes, pls call 352-586-5075
PAGE 20
B10MONDAY,SEPTEMBER2,2013 CLASSIFIEDS CITRUSCOUNTY( FL ) CHRONICLE 427-0902 MCRN BEVERLYHILLS MSBU PUBLIC NOTICE NOTICE IS HEREBYGIVEN that the Beverly Hills Advisory Council will meet on Monday, September 9, 2013, September 2, 2013. 428-0902 MCRN Lien Foreclosure Sale 9-13 PUBLIC NOTICE NOTICE OF SALE Notice is hereby given that the undersigned intends to sell the vehicle described below under Florida Statutes 713.78. The undersigned will sell at public sale by competitive bidding on Friday, September 13, 2013 at 9:00 am on the premises where said vehicle has been stored and which are located at, Smittys Auto, Inc., 4631 W Cardinal St, Homosassa, Citrus County, Florida, the following: 1988 NISSAN 300ZX Vin # JN1HZ16SXJX205134 Purchase must be paid for at the time of purchase in cash only. Vehicle sold as is and must be removed at the time of sale. Sale is subject to cancellation in the event of settlement between owner and obligated party. September 2, 2013 431-0909 FCRN BERNDT, TERRY 09-2009-CA-006957 NOA PUBLIC NOTICE IN THE CIRCUIT COURT OF THE 5TH JUDICAL CJRCUIT, IN AND FOR CITRUS COUNTY, FLORIDA. CASE No. 09-2009-CA-006957 THE BANK OF NEW YORK MELLON FKA THE BANK OF NEW YORK, AS TRUSTEE FOR THE CERTIFICATEHOLDERS, CWABS INC., ASSETBACKED CERTIFICATES, SERIES 2007-5 CERTIFICATES, SERIES 2007-5, Plaintiff vs. TERRY BERNDT, et al., Defendants NOTICE OF ACTION TO: WENDY CIRADULO 837 S. WESTMORE MEYERS RD LOMBARD, IL 60148 AND TO: All persons claiming an interest by, through, under, or against the aforesaid Defendant(s). YOU ARE HEREBY NOTIFIED that an action to foreclose a mortgage on the following described property located in Citrus County, Florida: COMMENCE AT THE SW CORNER OF SECTION 27, TOWNSHIP 18 SOUTH, RANGE 20 EAST, CITRUS COUNTY, FLORIDA, THENCE N. 0 00 48., ALONG THE WEST LINE OF SAID SECTION 27, A DISTANCE OF 501.76 FEET, THENCE N. 42 36 20 E. 207.49 FEET, THENCE N. 20 27 30 E. 113.90 FEET, THENCE S. 88 22 48 E. 117.08 FEET, THENCE N. 0 48 W. 324.81 FEET, THENCE N. 88 50 40 W. 317.33 FEET, THENCE N. 57 59 W.142.90 FEET, THENCE S. 50 10 40. 343.12 FEET, THENCE S. 5 28 20 W. 311.99 FEET TO POINT OF BEGINNING, THENCE S. 32 39 30. 76.82 FEET, THENCE N. 56 23 10 W. 185 FEET TO THE WA TERS OF A CANAL, THENCE CONTINUE N. 56 23 10 W. 46.69 FEET, THENCE N. 43 21 20 E. 53.23 FEET TO A POINT THAT BEARS N. 62 39 40. FROM THE POINT OF BEGINNING, THENCE S. 62 39 40 E. 47.74 FEET TO THE WATERS EDGE, THENCE S. 62 39 40 E. 175 FEET TO THE POINT OF BEGINNING, BEING LOT 59, BLOCK D OF POINT LONESOME UNIT NO. 1., AN UNRECORDED SUBDIVISION.AND COMMENCE AT THE SW CORNER OF SECTION 27, TOWNSHIP 18 SOUTH, RANGE 20 EAST, CITRUS COUNTY, FLORIDA, THENCE N. 0 00 48 W, ALONG THE WEST LINE OF SAID SECTION 27, A DISTANCE OF 501.76 FEET, THENCE N. 42 36 20 E. 207.49 FEET, THENCE N. 24 37 30 E. 113.90 FEET, THENCE S. 88 22 48 E. 117.08 FEET, THENCE N. 0 00 48 W. 324.81 FEET, THENCE N. 88 50 40 W. 317.33 FET, THENCE N. 57 59 W. 142.90 FEET, THENCE S. 50 10 40 W. 343.12 FEET, THENCE S. 5 28 20 W. 231.99 FEET TO THE WATERS OF A CANAL, THENCE CONTINUE N. 62 39 40 W. 47.74 FEET, THENCE N. 43 21 E. 24.25 FEET, THENCE N. 22 34 50 W. 62.89 FEET TO A POINT THAT BEARS N. 65 12 40 W. FROM THE POINT OF BEGINNING, THENCE S. 65 12 40 E. 69.59 FEET TO THE WATERS EDGE, THENCE CONTINUE S. 65 12 40 E. 165 FEET TO THE POINT OF BEGINNING, BEING LOT 60, BLOCK D OF PIONT LONESOME UNIT NO. 1, AN UNRECORDED SUBDIVISION. SUBJECT TO EASEMENT AS DESCRIBED IN OFFICIAL RECORD BOOK 409, PAGE 540, PUBLIC RECORDS OF CITRUS COUNTY, FLORIDA. has been filed against you. You are required to serve a copy of your written defenses, if any, on Greenspoon Marder, P.A., Default Department, Attorneys for Plaintiff, whose address is Trade Centre South, Suite 700, 100 West Cypress Creek Road, Fort Lauderdale, FL 33309, and the file original with the Clerk of Court within 30 days after the first publication of this notice in the Citrus County Chronicle on or before October 2, 2013; otherwise a default and a judgement may be entered against you for the relief demanded in the Complaint. WITNESS MY HAND AND SEAL OF SAID COURT on this 26th day of August, 2013. ANGELA VICK, As Clerk of said Court (SEAL) By:/s/ Vivian Cancel, g impaired, contact (TDD) (800)955-8771 via Florida Relay System. September 2 & 9, 2013 20187.2933/AG 432-0909 FCRN Hollenbach, Carl A. 2013-CA-729 NOA PUBLIC NOTICE IN THE CIRCUIT COURT OF THE 5TH JUDICIAL CIRCUIT, IN AND FOR CITRUS COUNTY, FLORIDA CIVIL DIVISION CASE NO.:2013-CA-729 FEDERAL NATIONAL MORTGAGE ASSOCIATION, Plaintiff, vs. CARL A. HOLLENBACH, et al., Defendants. NOTICE OF ACTION TO: CARL DEBORAH YOU ARE NOTIFIED that an action for Foreclosure of Mortgage on the following described property: LOT 12, IN BLOCK 1435, OF CITRUS SPRINGS UNIT 21, ACCORDING TO THE MAP OR PLAT THEREOF AS RECORDED IN PLAT BOOK 7, PAGES 73 THROUGH 83, INCLUSIVE, PUBLIC RECORDS OF CITRUS COUNTY, FLORIDA has been filed against you and you are required to serve a copy of your written defenses, if any, to it, on Choice Legal Group, P.A., Attorney for Plaintiff, whose addr ess is 1800 NW 49 STREET, SUITE 120, FT.LAUDERDALE FL 33309 on or before October 2, 2013,. WITNESS my hand and the seal of this Court this 23rd day of August 2013. Angela Vick As Clerk of the Court [COURTSEAL] By:/s/ Vivian Cancel, As Deputy Clerk September 2 & 9, 2013. 11-25980 429-0909 MCRN Estate of Lawrence Jason Riviere 2013-CP-397 NTC-SA PUBLIC NOTICE IN THE CIRCUIT COURT FOR CITRUS COUNTY FLORIDA, PROBATE DIVISION IN RE: ESTATE of LAWRENCE JASON RIVIERE, FILE NO.: 2013-CP-397 DECEASED, NOTICE TO CREDITORS (Summary Administration) TO ALL PERSONS HAVING CLAIMS OR DEMANDS AGAINST THE ABOVE ESTATE: You are hereby notified that an Order of Summary Administration has been entered in the Estate of Lawrence Jason Riviere, deceased, File Number 2013-CP-397 by the Circuit Court for Citrus County, Florida, Probate Division, the address of which is 110 North Apopka Avenue, Inverness, Florida 34450; that the decedents date of death was May 23, 2013: that the total value of the estate is $NONE and that the names and address of those to whom it has been assigned by such order are: Larry A. Riviere, 302 N. McGowan Avenue, Crystal River, FL 344 WITH BE FOREVER BARRED. 430-0909 THCRN Bury, Janice 2013-CP-442 NOC PUBLIC NOTICE IN THE CIRCUIT COURT FOR CITRUS COUNTY, FLORIDA PROBATE DIVISION File No.: 2013-CP-442 IN RE: ESTATE OF JANICE E BURY a/k/a JANICE K. BURY Deceased. NOTICE TO CREDITORS (Summary Administration) TO ALL PERSONS HAVING CLAIMS OR DEMANDS AGAINST THE ABOVE ESTATE: You are hereby notified that an Order of Summary Administration has been entered in the estate of JANICE E BURY, deceased, File Number 2013 CP 442, by the Circuit Court for Citrus County, Florida, Probate Division, the address of which is 110 N Apopka Avenue, Inverness, FL 34450; that the decedents date of death was April 4, 2013; that the total value of the estate is $3,665.00 and that the names of those to whom it has been assigned by such order are: NAME ADDRESS Alison C. Zoubek, Trustee of The Bury 834 Hobert Avenue Family Trust dated October 26, 2006Plainfield, NJ 07063 September 2, 2013. Personal Representative: /S/ Alison C. Zoubek 834 Hobert Avenue, Plainfield, NJ 07063 Attorney for Personal Representative: John S. Clardy III, Florida Bar No. 123129 Clardy Law Firm PA, PO Box 2410, Crystal River, FL 34423-2410, E-mail Addresses:clardy@tampabay.rr.com Published in the Citrus County Chronice September 2 & 9, 2013. NOTWITHSTANDING ANY OTHER APPLICABLE TIME PERIOD, ANY CLAIM FILED TWO (2) YEARS OR MORE AFTER THE DECEDENTS DATE OF DEATH IS BARRED. The date of first publication of this Notice is September 2, 2013. Person Giving Notice: /S/LARRY A. RIVIERE 302 N. McGowan Avenue, Crystal River, FL 34429, September 2 & 9, 2013. 417-0902 MCRN Lugo, Vivian 2013-DR-1335 NOA-Dissolution PUBLIC NOTICE IN THE CIRCUIT COURT OF THE FIFTH JUDICIAL CIRCUIT, IN AND FOR CITRUS COUNTY, FLORIDA Case No.: 2013-DR-1335 Division: Family VIVIAN R. LUGO Petitioner and CARLOS PACHECO Respondent NOTICE OF ACTION FOR DISSOLUTION OF MARRIAGE (NO CHILD OR FINANCIAL SUPPORT) TO:CARLOS PACHECO 1140 S. Highlands Avenue, Inverness, Florida 34452 (2007) YOU ARE NOTIFIED that an action for dissolution of marriage has been filed against you and that you are required on or before 9-11-13 and file the original with the clerk of this Court at CITRUS COUNTY COURTHOUSE 110 N. APOPKA A VE, INVERNESS, FL 34450before service on Petitioner or immediately thereafter. If you fail to do so, a default may be entered against you for the relief demanded in the petition. The action is asking the court to decide how the following real or personal property should be divided: THERE IS NO PROPERTY TO DIVIDE., ROBERT WEBB, 5164 S. FLORIDA AVENUE, INVERNESS, FLORIDA 34450, (352) 201-7136, helped VIVIAN R. LUGO, who is the petitioner, fill out this form. August 12, 19, 26 & September 2, 2013. 418-0902 MCRN Brown, Francis 2012-DR-1466 NOA-Dissolution PUBLIC NOTICE IN THE CIRCUIT COURT OF THE FIFTH JUDICIAL CIRCUIT, IN AND FOR CITRUS COUNTY, FLORIDA Case No.: 2012-DR-1466 Division: Family Francis A. Brown III Petitioner and Colleen S Brown Respondent NOTICE OF ACTION FOR DISSOLUTION OF MARRIAGE (NO CHILD OR FINANCIAL SUPPORT) TO:COLLEEN S. BROWN 3437 S. Cedar Oak Lane, Hernando, Florida 34442 YOU ARE NOTIFIED that an action for dissolution of marriage has been filed against you and that you are required on to serve a copy of your written defenses, if any to it on Francis A. Brown III whose address is 4708 S. Brush Hollows Loop, Inverness, FL. 34450 on or before 9-11-13 and file the original with the clerk of this Court at CITRUS COUNTY COURTHOUSE, 110 N. APOPKA A VE, INVERNESS, FL 34450, before service on Petitioner or immediately thereafter. If you fail to do so, a default may be entered against you for the relief demanded in the petition. The action is asking the court to decide how the following real or personal property should be divided: Both the Petitioner and the Respondent have divided the property and there are no new changes. There is no division requested., CARMEN DURSO, 2439 S. ROCK CRUSHER ROAD, HOMOSASSA, FLORIDA 34448, (352) 621-3199, helped Francis A. Brown III, who is the petitioner, fill out this form. August 12, 19, 26 & September 2, 2013. 423-0909 MCRN Morias, Damian 2013-J-0443 Notice of Summons PUBLIC NOTICE IN THE JUVENILE COURT OF LAURENS COUNTY CITATION STATE OF GEORGIA FILE#34. 13920.1233 CASE # 2013-J-0443 IN THE INTEREST OF: MORAIS, Damian SEX: Male DOB: 12/24/11 A Child Under Eighteen (18) Yea rs of Age ORDER FOR SERVICE BY PUBLICATION The State Department of Human Resources, acting through the Laurens County Department of Family and Child ren Services, having filed a Petition before this Court for termination of parental rights of the following parties with respect to the child named above, and any other person having a parental interest in said child and named as follows: RACHEL EAVES AND LEONARD MORAIS It appearing to this Court that the whereabouts of the parent is u nknown to Petitioner and Petitioner having therefore requested an Order directing service to be made u pon said party by publication of summons as by law provided; and It further appearing upon Affidavit made by the Caseworker with the Lau rens County Department of Family and Child ren Services, that said party cannot be fou nd with d ue d iligence within the State of Georgia; IT IS THEREFORE ORDERED that service of process be made upon the followi ng pa rty by publication as by law provided; RACHEL EAVES AND LEONARD MORAIS and an y other person having a paren tal interest in said child. SO ORDERED, this 5TH day of AUGUST, 2013. /S/SAMUEL A. HILBUN, JUDGE LAURENS COUNTY JU VENILE COU RT DUBLIN JUDICIAL CIRCUIT NOTICE OF SUMMONS TO WHOM IT MAY CONCERN, RACHEL EAVES AND LEONARD MORAIS and anyone claiming to have a parental interest in the minor child named above. YOU ARE FURTHER NOTIFIED that the above styled action seeking the termination of the parental rights of the parent of the named child was filed against you in said Court on the 5TH day of August, 2013, and that by reason of an Order for Service by Publication entered by the Court on the 5TH day of August, 2013; YOU ARE HEREBY COMMANDED AND REQUIRED to appea r before the Juvenile Court of Laurens County, Georgia, in Dublin, Georgia, on the, 23 day of October, 2013, at 9:00 oclock A.M. The hearing is for the purpose of determining whether or not said parental rights should be terminated. The affect of an order terminating parental rights under O.C.G.A. Title 15, Chapter 11, Article 2, is without limit as to duration and terminates all the parents rights and obl igations with respect to the child and all right and obligations of the child to the parent arising from the parental relationship, including rights of inheritance. The parent whose rights are terminated is not thereaf ter entitled to notice of proceedings for the adoption of the child by another, nor has the parent any right to object to the adoption or otherwise to participate in the proceedings. A copy of the petition may be obtained from the Clerk of the Juvenile Court at Dublin, Georgia, during regular business hours, Monday through Friday, 8:30 A.M. to 5:00 P.M. exclusive of holidays. A free copy shall be available to the parents. Upon request, the copy will be mailed to the requester. The child is in the present physical custody of the Laurens County Department of Family and Children Services. The general nature of the allegations are that said child is in need of proper care, custod y and control, and it would be in the best interest of the child and the public that said child be placed in the permanent custody of the Petitioner and that the parental rights be terminated as requested so that said child may be placed for adoption. YOU ARE FURTHER NOTIFIED that while responsive pleadings are not mandatory, they are permissible and you are encouraged to file with the Clerk of this Court and serve upon Petitioners Attorney, Charles C. Butler, P.O. Drawer 4430, Dublin, Georgia 31040, an answer or other responsive pleading within sixty (60) days of the date of the Order for Service by Publication. All concerned parties are informed that they are entitled to have an attorney represent them, and if a party is entitled to counsel during the proceedings, the Court will appoint counsel, at no cost if the party is unable, without undue financial hardship to employ counsel. WITNESS THE HONORABLE Samuel A. Hilbun, Judge of said Court, this 5TH day of AUGUST, 2013. Presented by: Charles C. Butler Attorney for Laurens County Department of Family and Children Services PO Drawer 4430, Dublin, Ga 31040-4430, State Bar No. 099517 Published in the Citrus County Chronicle, August 19, 26, September2 & 9, 2013. Terminationo RightsNoti Terminationo RightsNoti Terminationo RightsNoti Harley Davidson 2010 ULTRACLASSIC Excellent condition original owner with extras priced to sell $16,250 callTim 352-400-8787 SUZUKI2009 GZ250 EXCELLENTCONDITION, WITH EXTRAS ONLY 3,303 MILES. $1,995 352-527-3738 CHEVROLET Camaro Z28, Runs good, 350 eng. hurst shifter, $2,500 (352) 634-1764 pickup, good tires, good running, full of gas. Best Offer (352) 746-4412 CHEVY, Silverado 114k mi. motor. 4.8L, V8, looks & runs excel. $8,000.., $7,500 obo (352) 422-4548 GMC2006 Sierra Crew Cab; V8, 4.8L, 109k miles, V ery Clean $11,999 (352) 382-2721 DODGE2005, Durango leather, navi $9,995. 352-341-0018 HONDA2007, Element, Hard to find, cold A/C, runs great, Must See, Call (352) 628-4600 pugnutx11@msn.com $$AutoV CHEVYVETTE,02 Convert. Royal Blue, Saddle oak int. 16k mi, Gar, Mint, $23,900 obo call 352-489-1700 KIA2006 Optima, 45k mi. fully loaded, 1 owner, exc. cond. Must Sell Diana (352) 637-4695 LINCOLN2006Towncar, signature edition, sunroof, garage kept, all leather $10,500.(352) 382-3013-1111 TOYOTA2010, Yaris $8,995 352-341-0018 TOYOTA COROLLADX good clean, cruise, AM/FM/CDACAll Pwr $1600 352-610-6061 Chevrolet1987 Corvette, silver 39,500 orig.mi.mint condition, 4 spd $16500. (352) 341-056066, Nova, Red, black interioir automatic, 350 HP, mint. cond. $29,500 obo YOUR High** 12 Ft DURANAUT1968, 9.9 HPJohnson, Tilting trailer, ready to go $800 (352) 637-5616 BOAT SLIP FOR RENT HOMOSASSA RIVER $125. mo. 352-220-2077. PONTOON BOAT2003 Sun Tracker. 25 ft. Great running party/fishing boat! 130 hp Honda motor. Very Quite and great on gas! $10,500 352-697-3428 PolarisATV 2 x 4 (352) 400-3585Tow Bar for Jeep 97-06 or Chevy Pick $775, fender flares jeep new $110, call jack 352-220-9101 Need a JOB?#1 Employment source is Classifieds
PAGE 21
CITRUSCOUNTY(FL) CHRONICLEMONDAY, SEPTEMBER2, 2013 B11 000FXAX
PAGE 22
B12MONDAY, SEPTEMBER2, 2013CITRUSCOUNTY(FL) CHRONICLE 000FXAY | http://ufdc.ufl.edu/UF00028315/03217 | CC-MAIN-2014-41 | refinedweb | 29,811 | 65.42 |
I'm reading bottle.py source code. It's a web framework, with only 3000+ lines python code. So cool.
I found some code like this:
class ServerAdapter(object):
quiet = False
def __init__(self, host='127.0.0.1', port=8080, **config):
self.options = config
self.host = host
self.port = int(port)
def run(self, handler): # pragma: no cover
pass
...
# pragma: no cover
pragma
It is apparenly related to the coverage.py:
Coverage.py is a tool for measuring code coverage of Python programs. It monitors your program, noting which parts of the code have been executed, then analyzes the source to identify code that could have been executed but was not.
That exact
# pragma: no cover is the hint that the part of code should be ignored by the tool -- see Excluding code from coverage . | https://codedump.io/share/05KIlxwSxmoU/1/pragmas-in-python | CC-MAIN-2017-17 | refinedweb | 136 | 69.89 |
Even though XHTML supports the same elements and attributes as HTML 4.0, there are some significant differences that are due to the fact that XHTML is an XML-based language. Given your knowledge of XML, you may already have a pretty good idea regarding some of these differences, but the following list will help you to understand exactly how XHTML documents differ from HTML documents:
XHTML documents must be well formed.
Element and attribute names in XHTML must be in lowercase.
End tags in XHTML are required for nonempty elements.
Empty elements in XHTML must consist of a start-tag/end-tag pair or an empty element.
Attributes in XHTML cannot be used without a value.
Attribute values in XHTML must always be quoted.
An XHTML namespace must be declared in the root
htmlelement.
The
headand
bodyelements cannot be omitted in XHTML.
The
titleelement in XHTML must be the first element in the
headelement.
In XHTML, all script and style elements must be enclosed within
CDATAsections.
These differences between XHTML and HTML 4.0 shouldn't come as too much of a surprise. Fortunately, none of them are too difficult to find and fix in HTML documents, which makes the move from HTML 4.0 to XHTML relatively straightforward. However, web pages developed with versions of HTML prior to 4.0 typically require more dramatic changes. This primarily has to do with the fact that HTML 4.0 does away with some previously popular formatting attributes such as background and instead promotes the usage of style sheets. Because XHTML doesn't support these formatting attributes, it is necessary first to convert legacy HTML (prior to 4.0) documents to HTML 4.0, which quite often involves replacing formatting attributes with CSS equivalents. Once you get a web page up to par with HTML 4.0, the move to XHTML is pretty straightforward.updated | http://www.brainbell.com/tutorials/XML/Comparing_XHTML_And_HTML.htm | CC-MAIN-2017-04 | refinedweb | 314 | 67.76 |
ANTLR. (source)
We’ll be using version 4. Download antlr-4.5.1-complete.jar.
More applications are mentioned on the Wikipedia page. Here are a bunch of example grammars:
Overview
Writing translators (which includes compilers) is hard. You know this from experience writing an assembler-to-binary and VM-to-assembly translator. In both of those cases, the translation was linear: a single line of input translated to one or a few lines of output. Once the output was generated, you could move on to the next line of input. Each line of input had no impact on how the prior or following lines would be translated
But more complex (and more useful) languages are typically nested languages. Expressions with multiple operations (+, -, *, /, etc.), expressions within parentheses, loops inside if’s, if’s inside loops, loops inside loops inside functions!
Just translating the expression
-((3-1)*(2+7)) into VM code is troublesome. VM code is a stack language. But the expression is nested (not in stack form). The negation must happen last but it is the first character in the input. The stack-language version (e.g., Forth) would be:
3 1 - 2 7 + * neg. The result in VM code should be (assuming
mult exists as a VM operation):
push constant 3 push constant 1 sub push constant 2 push constant 7 add mult neg
The order is significantly different than the input. The order actually represents the “parse tree,” which respects parentheses. The VM code contains left-subtree code followed by right-subtree code, which is then followed by the actual operator (
add,
sub,
neg). (The
- negation operator out front only has a right-subtree.)
No fear. We can easily translate a nested language into a stack language, or whatever else, by parsing the input into a tree and then flattening that tree into a list of VM code commands (or Forth commands or whatever). All we need to do is write a grammar, then a tree visitor. The ANTLR tool will generate all the (horrendously complicated) parsing code for our specific grammar.
Grammars
ANTLR supports grammars written in Extended Backus-Naur Form (EBNF). The structure of the input language (which will be translated to something else) is expressed in a list of rules. Each rule has one or more patterns that it matches. Vertical bars
| mean alternative patterns for the rule.
Here is a snippet of the calculator example below:
expr: left=expr op='%' | left=expr op='^' right=expr | left=expr op=('*'|'/') right=expr | left=expr op=('+'|'-') right=expr | neg='-' right=expr | funcCall | NUMBER | '(' expr ')' ;
This snippet states the an expression (
expr) has one of the following patterns:
- an expression followed a
%sign
- a
^sign between two expressions
- a
*or
/sign between two expressions
- a
+or
-sign between two expressions
- a
- a function call (e.g.,
foo(5, 2))
- a number (e.g.,
55)
- or an expression inside parentheses
Note the rule is recursive. This is how we support nesting like
-((3-1)*(2+7)). The parse tree above shows how the
expr matched that expression.
Some notes:
We can name certain parts of the patterns in order to easily refer to them in our visitor code. Examples above include
left=... and
op=....
An ALL-CAPS rule means the rule won’t be added to the parse tree, but we can refer to the rule (and get its matching text for translation) in the tree visitor code. Example:
NUMBER : DIGIT* '.' DIGIT* | DIGIT+ | CONSTANT ;
Note,
* means “any number of these, including possibly none” and
+ means “at least one of these.”
A “fragment” rule is only used by the grammar to help define other rules. A fragment does not even exist as an accessible property on nodes in the parse tree. Example:
fragment DIGIT: '0'..'9';
Lexers
ANTLR will generate a “lexer” from the grammar. A lexer reads an input file and translates the symbols in that file into a stream (list) of “tokens.” The grammar is full of tokens:
+,
-, etc. Here are the tokens for
-((3-1)*(2+7)). Note how the positions are specified for each token. The numbers in
<brackets> indicate internal IDs for the various unique tokens (they are unimportant to us).
[@0,0:0='-',<6>,1:0] [@1,1:1='(',<7>,1:1] [@2,2:2='(',<7>,1:2] [@3,3:3='3',<12>,1:3] [@4,4:4='+',<5>,1:4] [@5,5:5='1',<12>,1:5] [@6,6:6=')',<8>,1:6] [@7,7:7='*',<3>,1:7] [@8,8:8='(',<7>,1:8] [@9,9:9='2',<12>,1:9] [@10,10:10='+',<5>,1:10] [@11,11:11='7',<12>,1:11] [@12,12:12=')',<8>,1:12] [@13,13:13=')',<8>,1:13] [@14,15:14='<EOF>',<-1>,2:0]
Parsers
ANTLR will also generate a parser from the grammar. A parser takes a stream of tokens (produced by the lexer) and generates a parse tree according to the rules in the grammar. The diagram of the tree above is an example parse tree.
Tree visitors
Finally, given the parse tree, the last step is to flatten the parse tree into a list of statements in the target language (in our case, VM code). To do so, we can walk down the tree with a collection of “visitor” functions. We start at the top root of the tree, then look at each node. The visitor for a node calls the visitors of its children. See the calculator example below for details.
Translators vs. compilers
We have been using the terminology “translator” rather than “compiler” just to be politically correct. To be a compiler, a program usually must translate a source language into machine code. Whether or not that distinction is important to you dictates whether you call a program a translator or compiler. Our use of ANLTR (lexer + parser + tree visitor) makes our approach otherwise very close to a compiler.
Calculator example
We’ll build a simple calculator as an example. We’ll define a grammar and a tree visitor. The result of the tree visitor is not code in another language (e.g., VM code) but rather the result of the computation. In that sense, this is an “interpreter” rather than a “compiler” because the result is a value not a program to be executed later.
Grammar (Calc.g4)
Note that the order of definitions in a rule matter. For example, if
'%' comes after
'+', then
55% + 100% is computed as
1.0055, i.e.,
(55% + 100)%. If
'%' it comes before
'+' then we get correct behavior:
55% + 100% => 1.55. We order
+ and
- after
* and
/ for this same reason. The first matching rule wins.
grammar Calc; prog: expr ; expr: left=expr op='%' | left=expr op='^' right=expr | left=expr op=('*'|'/') right=expr | left=expr op=('+'|'-') right=expr | neg='-' right=expr | funcCall | NUMBER | '(' expr ')' ; funcCall : f='sin' '(' expr ')' | f='cos' '(' expr ')' | f='log' '(' expr ')' ; NUMBER : DIGIT* '.' DIGIT* | DIGIT+ | CONSTANT ; fragment DIGIT: '0'..'9'; CONSTANT : 'pi' | 'e' ; WS : [ \t\n\r]+ -> skip;
Diagrammatic form
These are railroad diagrams. I used this tool to generate them.
prog
expr
funcCall
NUMBER
DIGIT
CONSTANT
Example parse trees
These are generated by ANTLR4 with the following command (or something similar):
echo "5+2*3" | java -cp antlr-4.5.1-complete.jar:. \ org.antlr.v4.gui.TestRig Calc prog -ps calc-tree1.ps
Input:
5+2*3
Input:
-(sin(pi)+log(e^(5/2)))
Main file (Calc.java)
The
main() function reads a line of input from
System.in and feeds it into the generated lexer. The lexer produces a stream of tokens, which is fed into the generated parser. The parser gives back a parse tree. Finally, our custom tree visitor (
CalcExprVisitor) flattens to the tree to a final value. This value is printed, and another line of input is read.
import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTreeWalker; import java.util.Scanner; public class Calc { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); while(in.hasNext()) { String s = in.nextLine(); ANTLRInputStream input = new ANTLRInputStream(s); CalcLexer lexer = new CalcLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); CalcParser parser = new CalcParser(tokens); CalcParser.ProgContext tree = parser.prog(); // root of grammar Double result = new CalcExprVisitor().visit(tree); System.out.println("=> " + result); } } }
Visitor (CalcExprVisitor.java)
The visitor is where most of the work takes place. Each
visit* function handles a particular rule in the grammar. Should the rule be encountered while visiting the nodes of the parse tree, the appropriate
visit* function will be called. Each such function should evaluate the remainder of the tree from that point down, and return the resulting value for the subtree. Obviously, you want use recursion as much as possible, and only handle a single action at a time.
Visiting starts at
visitProg since
prog was the root of the grammar. We know
prog is just an
expr so the
visitProg function simply returns whatever happens when the first
expr is visited.
Now we are in the
visitExpr function. There are different situations in the
expr rule. We might have a unary operator, a binary operator, a negation, a function call, a number, or a nested expression in parentheses. We can tell which case we have by looking at whether
ctx.op is non-null and what it’s value is (
ctx.op.getText()), whether
ctx.neg is non-null, etc. We named various parts of the rule in the grammar so we could easily identify which case we’re in:
expr: left=expr op='%' | left=expr op='^' right=expr | left=expr op=('*'|'/') right=expr | left=expr op=('+'|'-') right=expr | neg='-' right=expr | funcCall | NUMBER | '(' expr ')' ;
Here is the code:
public class CalcExprVisitor extends CalcBaseVisitor<Double> implements CalcVisitor<Double> { public Double visitProg(CalcParser.ProgContext ctx) { return this.visit(ctx.expr()); } public Double visitExpr(CalcParser.ExprContext ctx) { Double result = 0.0; if(ctx.neg != null) { result = -this.visit(ctx.expr().get(0)); } else if(ctx.op != null) { if(ctx.right == null) { Double l = this.visit(ctx.left); switch(ctx.op.getText()) { case "%": result = l*0.01; break; } } else { Double l = this.visit(ctx.left); Double r = this.visit(ctx.right); switch(ctx.op.getText()) { case "+": result = l+r; break; case "-": result = l-r; break; case "*": result = l*r; break; case "/": result = l/r; break; case "^": result = Math.pow(l,r); break; } } } else if(ctx.funcCall() != null) { result = this.visit(ctx.funcCall()); } else if(ctx.NUMBER() != null) { switch(ctx.NUMBER().getText()) { case "pi": result = Math.PI; break; case "e": result = Math.E; break; default: result = Double.parseDouble(ctx.NUMBER().getText()); } } else { result = this.visit(ctx.expr().get(0)); } return result; } public Double visitFuncCall(CalcParser.FuncCallContext ctx) { Double result = 0.0; Double expr = this.visit(ctx.expr()); switch(ctx.f.getText()) { case "sin": result = Math.sin(expr); break; case "cos": result = Math.cos(expr); break; case "log": result = Math.log(expr); break; } return result; } }
Building the calculator example
First, use ANTLR4 to generate the lexer, parser, and default (empty) visitor from the grammar (step 1), then compile all the Java source including code we wrote (step 2), and finally run the result (step 3).
Of course, the antlr-4.5.1-complete.jar file is needed.
Generate parser/lexer/visitor from grammar:
java -jar antlr-4.5.1-complete.jar -visitor -no-listener Calc.g4
- This command generates:
Calc.tokens: list of tokens the lexer recognizes
CalcBaseVisitor.java: empty implementation of tree visitor
CalcLexer.java: subclass of ANTLR4
Lexerthat has calculator grammar specific code for splitting input into tokens
CalcParser.java: subclass of ANTLR4
Parserthat builds a parse tree out of the lexer’s token stream
CalcVisitor.java: interface for any tree visitor that works with the calculator grammar
Compile all code:
javac -cp antlr-4.5.1-complete.jar:. *.java
Run program:
java -cp antlr-4.5.1-complete.jar:. Calc
If you change the grammar, repeat steps 1-3. If you change the Java code, repeat steps 2-3. | http://csci201.artifice.cc/notes/antlr.html | CC-MAIN-2020-10 | refinedweb | 2,001 | 51.04 |
Now that we have the enemies spawning, we want them to shoot bullets at certain intervals. The bullets will spawn wherever the enemy is currently located. Once they have spawned, they should start moving left and once they are out of the screen, they should be deleted. For this, we create a class named
Projectile and add the
Projectile.h and
Projectile.cpp files to the
Classes folder, as we did previously for the other classes.
In the
Projectile.h file, add the following lines of code:
#ifndef __wp8Game__Projectile__ #define __wp8Game__Projectile__ #pragma once #include "cocos2d.h" using namespace cocos2d; class Projectile : public CCSprite { public: Projectile(void); ~Projectile(void); int type; static Projectile* ...
No credit card required | https://www.oreilly.com/library/view/learning-cocos2d-x-game/9781783988266/ch03s03.html | CC-MAIN-2018-51 | refinedweb | 116 | 60.31 |
I'm still early into learning to code, so sorry if the code is wonky...
I'm making a number guessing game that guesses based on a first guess from two numbers the user gives and then puts those numbers into a list ascending. then my issue, i want to remove numbers lower/higher from my first guess then just do random.choice(list) code to follow....
import random
print("\nLets see if I can guess the number you're thinking.\nI've got some questions first")
tryNumber=1)+".\n")
firstGuess=random.randint(numberRangeLow, numberRangeHigh)
numbers=[]
nums=[]
while numberRangeLow < numberRangeHigh+1:
numbers.append(numberRangeLow)
nums.append(numberRangeLow)
numberRangeLow+=1
while tryNumber < trys:
print("Is your number", str(firstGuess), "?")
answer=input("Enter 'higher', 'lower' or correct (Case-Sensitive)")
if answer == "higher":
numbers.remove('''nums >= firstGuess''')
firstGuess=random.choice(numbers)
print("Is your number", str(firstGuess), "?")
First off,
while numberRangeLow < numberRangeHigh+1: do stuff is basically the same as
range.
For the same result, you can use
numbers = range(numberRangeLow, numberRangeHigh + 1), which will build the list for you.
You also don't need to warn about it being case sensitive, if you use
str.lower() it'll automatically put it into lower case. For example, you could do
if answer.lower() == "higher".
To remove numbers, you can do list slicing. For example, if you have
a = [1, 2, 3, 4], and it's lower than 3, you can get the index of 3 by using
a.index(3), which in this case, will give 2.
By then cutting off anything higher than this index with
a[2:], you have removed any higher numbers than 3.
Here's a quick update to your code doing the bits I mentioned.) #New bits: numbers = range(numberRangeLow, numberRangeHigh + 1) for i in range(trys): guess = random.choice(numbers) print("Is your number", str(guess), "?") answer = input("Enter 'higher', 'lower' or 'correct'").lower() if answer == 'correct': break elif answer == 'higher': list_index = numbers.index(guess) numbers = numbers[list_index + 1:] elif answer == 'lower': list_index = numbers.index(guess) numbers = numbers[:list_index]
I rearranged the last part of the code so you didn't have 2 copies of the random choice. Also for the record, it's seen as better practice to
name_variables_like_this and
notLikeThis.
Edit: Kevins way is slightly different from mine, a simple comparison would be assuming you have written the numbers down on paper, this way would rip the paper in half and discard one part, whereas Kevins way would be writing it out again on a fresh sheet of paper, so you get more control, but it's a bit slower.
Edit 2: Since I'm bored, I wrote it how I'd do it with a function (with some comments). Bear in mind it's python 2 not python 3 I'm using so copy + paste won't work for you.
def number_guess(tries, low, high): #Error if low is more than or the same as high if low >= high: raise ValueError('invalid range') #Build number list num_list = range(low, high + 1) print 'I have got {} tries'.format(tries) print 'And the number is between {} and {}'.format(low, high) for i in range(tries): guess = random.choice(num_list) print 'Is {} your number?'.format(guess) answer = input('Enter higher, lower or correct').lower() #Empty answer if not answer: continue #Correct answer if answer[0] in ('c', 'y'): print 'I guessed in {} tries'.format(i) return True #Number is higher if answer[0] == 'h': list_index = num_list.index(guess) num_list = num_list[list_index + 1:] #Number is lower elif answer[0] == 'l': list_index = num_list.index(guess) num_list = num_list[:list_index] #If it hits this point there are no tries left print 'I failed to guess' return False tries = int(input('How many tries will you let me have?' )) low = int(input('What is the lowest number I can guess?' )) high = int(input('And what is the highest?' )) success = number_guess(tries, low, high) | https://codedump.io/share/e9TqnLB6b1oL/1/remove-numbers-from-a-list-less-than-variable | CC-MAIN-2017-47 | refinedweb | 651 | 66.84 |
FAQs
Search
Recent Topics
Flagged Topics
Hot Topics
Best Topics
Register / Login
Win a copy of
Modern JavaScript for the Impatient
this week in the
Server-Side JavaScript and NodeJS
Action form - design issue
Chetan Bengaluru
Greenhorn
Posts: 9
posted 15 years ago
Hi,
I'm developing a expense authorisantion tool.The expenses can be under various heads like administration,operations,travel etc. most of these have a few common fields that have to be captured.the rest of them are specific to the type like travel may capture airline details etc. i have to dynamically show the screens to capture these information based on the expense type selected.that means i cannot have a formbean that will have get/set methods based on travel etc(simply because the fields to be captured itself is configurable).how do i go about this.
i have decided to have a baseform with facility to capture all possible information.and then use only the relevant ones to display those screens itself with if clauses in the
jsp
(the fields to be displayed will be stored in the database for a particular expense type).
is this a good approach?.is it feasible?.
There are around 15 expense types that an employee could raise a request for.
if there are any drawbacks in the approach that i have thought of then what are they?.
can anybody let me know all pros and cons of this approach and a better approach if there is any.
Regards,
Chetan
Jason Menard
Sheriff
Posts: 6450
posted 15 years ago
"Chetan M V",
Welcome to JavaRanch. We don't have many rules here, but we do have a
naming policy
which we try to strictly enforce. Specifically, you must have a first (familiar) name or initial followed by a last (family) name. Initials are not acceptable in place of last names. Please re-read this document and edit your display name in order to comply. Thanks in advance, and we look forward to seeing you around the Ranch.
Merrill Higginson
Ranch Hand
Posts: 4864
posted 15 years ago
Regarding your first question:
When you have configurable fields, I find that it's useful to have a field in the form bean that is based on a Properties or Map object as in the following example:
public class MyForm extends ActionForm { private Properties values = null; /** * Set definition * @param <code>java.util.Properties</code> */ public void setDefinition(java.util.Properties d) { values = d; } public void setValue(String key, Object value){ values.setProperty( key, (String)value ); } public Object getValue(String key){ return values.getProperty( key ); } }
In your JSP, the code would look like:
<html:text
where xyz is the key within the Properties object.
This way you can programmatically manipulate the Properties object any way you want without having to write specific getters and setters for each field.
Regarding your second question, I would think that rather than having a single form for all the pages, a more Object Oriented approach might be to build an abstract base form, and write subclasses of it (one for travel, one for meals, etc.) to use as your actual forms for each jsp page. This way, you have the common fields in every form, but each form has what it needs and no more.
Merrill
Consultant,
Sima Solutions
Chetan Bengaluru
Greenhorn
Posts: 9
posted 15 years ago
thank you for showing some way forward.I have a reason for going in for one single form rather that using inheritance etc methodology.
The reason is there is an admin role for this web appln and he/she can configure fields(add/delete) from an available list.This will then be stored in the database.
Like for instance the admin may think airline detials may not be required and he will strike it off.This should then immediately be reflected when the next user logs on.His travel expense form should not show up airline details field.
This being the case I can't write my form class beforehand and have it extended from my base form.I can't even have prewritten form classes for any expense types(pls correct me if i'm wrong)
I have no clue whatsoever about how to approach this.
Can you tell me how this can be achieved.
Regards,
Chetan
Jason Menard
Sheriff
Posts: 6450
posted 15 years ago
Hi Chetan,
Since I'm sure you must have simply missed it, I'm going to have to once again direct your attention to my previous post in this
thread
. If this is not taken care of, it's very likely that your account will be disabled and these threads will be closed. Thanks again.
Don't get me started about those stupid
light bulbs
.
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
DispatchAction question
confused about 48 hours rule check.
Dynamic screen and table generation
displaying 100 rows per page.
Struts Validator Javascript Problems
More... | https://www.coderanch.com/t/50779/frameworks/Action-form-design | CC-MAIN-2020-40 | refinedweb | 827 | 71.14 |
O/RM Vs Stored Procedures. Which is the best approach?
For the last few years, many developers and architects are engage in a series of debates about ORM Vs Stored Procedures. Many of them argue for ORM and others are arguing for stored procedures. The interesting thing is that people with highly object orientation sense, recommends ORM. The J2EE community strongly recommending the ORM approaches instead of using stored procedures. Some .NET developers coming from Visual Basic 6.0 background supports stored procedures. Hibernate and NHibernate (.NET version of java version Hibernate) are the highly successful ORM that using both .NET and J2EE community. Then which is the best approach for data persist? Personally I hate stored procedures and strongly recommend for ORM instead of using the legacy stored procedure programming.
Why I hate stored procedures?
Stored Procedures are written by DB languages such as PL/SQL and T-SQL and this type of languages are not designed for writing business logic and debugging process is really a nightmare. And stored procedures hide the business logic and lacks readability of business process. If you are going to port DB from one RDBMS to another one, you have to re-write your all stored procedures. If you want to run your product on multiple databases, the ORM is the right approach. And ultimately the stored procedure restricts the proper business abstraction. Many people argue that stored procedure provides better performance than dynamic generated Sql from an ORM and people believed that all stored procedure are pre-compiled. According to Microsoft Sql Server documentation, Sql Server does cache the execution plan for stored procedure instead of pre-compiled. Have a look at the MSDN article Execution Plan Caching and Reuse. And I believe that maintainability, scalability and proper abstraction are the key factors of enterprise applications. The ORM approach enables these benefits.
If you are a .NET developer, there is happy news for you. A new ORM named Linq to Sql coming from the Redmond campus along with the .Net framework 3.5.
What is LINQ to SQL?.
Lets look at the below business object that mapped the customers table using Linq to Sql.
[Table(Name="Customers")]public class Customer{ [Column(Id=true)] public string CustomerID;
[Column] public string CustomerName;
[Column] public string City;
[Column] public string Phone;}
After modeling the Database with Linq to Sql, we can do all DB operations against it. The below code is the query against Customer object that represents the Customer table.
DataContext db = new DataContext();
var q = from c in db.Customer where c.City == "Cochin" select c;
In the above query will select customers of city Cochin .The DataContext represent an abstraction of your database.
The below code is update existing customer
DataClassesDataContext db=new DataClassesDataContext();
Customer cust=db.Customer.Single(c=> c.CustomerID ==”C101”);
cust.Phone="919847059589";
db.SubmitChanges();
The below code is add new customer
DataClassesDataContext db=new DataClassesDataContext();
Customer cust=new Customer();
Cust. CustomerName=”ABC Ltd”
cust.City=”Mumbai”;
cust.Phone=”919847059589”;
db.Customer.Add(cust);
db.SubmitChanges();
The below code is delete customer
Customer cust=db.Customer.Single(c=> c.CustomerID ==”C101”);
Db.Customer.Remove(cust);
The below code is using a join query
var orders =from o in db.Ordersjoin c in db.Customer on o.CustomerID equals c.CustomerIDwhere c.CustomerID == "C101"select new {c.CustomerName, o.ShipName, o.ShipAddress };
Linq to Sql is an exciting ORM tool from Microsoft and I hope that people will use this ORM along with .NET 3.5 applications.
Try creating the customer outside the context and add it later.. then you realize.. did Microsoft forget to tell me that Linq doesnt support this out of the box?
To say stored procedures hide the business functionality is a definitely defined as a comment coming from someone who really doesnt understand TSQL and wants to hide that fact. If all your business functionality is wrapped within your TSQL and your frontend correctly acts as a pure presentation layer then you will find that nothing is hidden - its all there -> In your stored procedures !
We have worked with 100% SProcs used in our systems for years. All our business logic sits ONLY on the DB side. If we have major business changes we find them easy to do by just modifying stored procedures. And no - nothing is hidden - its all there.
Good article. The database should act solely as a repository with no business logic incorporated within. That doesn't imply the database shouldn't have constraints as the primary goal, without exception, is the protection of its data.
Goodbye and good riddance to Stored procs indeed.
We only use stored procedures for data retrieval. Also security is MUCH more reliable granting execute only to procs instead of each database table and view. Looks like a step backwards of the intent is to NOT use procedures. Especially since the link explaining the Execution Plan Caching and Reuse, this is true HOWEVER, if you have a bad plan to begin with, it will Still perform poorly, no matter if it is direct SQL call via LINQ OR a proc that is poorly written! One other aspect lost is change management. If procs are used solely for data retrieve, update, delete, insert, there should be little to change in them as long as the schema design does not change... not good arguments to me.
Like so many other ORM promoters, you've gone with the argument that if you need to change your back end database you have to rewrite stuff and then you assume that your middle tier will never change, so the business logic will be safe there.
From 15 years of experience I can tell you that most corporate IT departments that I've worked with change their middle tier a lot more often than they change their database technology.
You also mention abstraction being one of "the key components to enterprise architecture". If that's the case, then why would you possibly want to couple your middle tier directly to tables rather than abstract them through stored procedures??? | http://weblogs.asp.net/shijuvarghese/archive/2008/03/26/goodbye-stored-procedures-it-s-the-time-to-move-on-quot-linq-to-sql-quot.aspx | crawl-002 | refinedweb | 1,016 | 57.77 |
7. Source/Values¶
GPIO Zero provides a method of using the declarative programming paradigm to connect devices together: feeding the values of one device into another, for example the values of a button into an LED:
from gpiozero import LED, Button from signal import pause led = LED(17) button = Button(2) led.source = button pause()
which is equivalent to:
from gpiozero import LED, Button from time import sleep led = LED(17) button = Button(2) while True: led.value = button.value sleep(0.01)
except that the former is updated in a background thread, which enables you to do other things at the same time.
Every device has a
value property (the device’s current value).
Input devices (like buttons) can only have their values read, but output devices
(like LEDs) can also have their value set to alter the state of the device:
>>> led = PWMLED(17) >>> led.value # LED is initially off 0.0 >>> led.on() # LED is now on >>> led.value 1.0 >>> led.value = 0 # LED is now off
Every device also has a
values property (a generator
continuously yielding the device’s current value). All output devices have a
source property which can be set to any iterator. The
device will iterate over the values of the device provided, setting the device’s
value to each element at a rate specified in the
source_delay property (the default is 0.01 seconds).
The most common use case for this is to set the source of an output device to match the values of an input device, like the example above. A more interesting example would be a potentiometer controlling the brightness of an LED:
from gpiozero import PWMLED, MCP3008 from signal import pause led = PWMLED(17) pot = MCP3008() led.source = pot pause()
The way this works is that the input device’s
values
property is used to feed values into the output device. Prior to v1.5, the
source had to be set directly to a device’s
values property:
from gpiozero import PWMLED, MCP3008 from signal import pause led = PWMLED(17) pot = MCP3008() led.source = pot.values pause()
Note
Although this method is still supported, the recommended way is now to set
the
source to a device object.
It is also possible to set an output device’s
source to
another output device, to keep them matching. In this example, the red LED is
set to match the button, and the green LED is set to match the red LED, so both
LEDs will be on when the button is pressed:
from gpiozero import LED, Button from signal import pause red = LED(14) green = LED(15) button = Button(17) red.source = button green.source = red pause()
7.1. Processing values¶
The device’s values can also be processed before they are passed to the
source:
For example, writing a generator function to pass the opposite of the Button value into the LED:
from gpiozero import Button, LED from signal import pause def opposite(device): for value in device.values: yield not value led = LED(4) btn = Button(17) led.source = opposite(btn) pause()
Alternatively, a custom generator can be used to provide values from an artificial source:
For example, writing a generator function to randomly yield 0 or 1:
from gpiozero import LED from random import randint from signal import pause def rand(): while True: yield randint(0, 1) led = LED(17) led.source = rand() pause()
If the iterator is infinite (i.e. an infinite generator), the elements will be
processed until the
source is changed or set to
None.
If the iterator is finite (e.g. a list), this will terminate once all elements are processed (leaving the device’s value at the final element):
from gpiozero import LED from signal import pause led = LED(17) led.source_delay = 1 led.source = [1, 0, 1, 1, 1, 0, 0, 1, 0, 1] pause()
7.2. Source Tools¶
GPIO Zero provides a set of ready-made functions for dealing with
source/values, called source tools. These are available by importing from
gpiozero.tools.
Some of these source tools are artificial sources which require no input:
In this example, random values between 0 and 1 are passed to the LED, giving it a flickering candle effect:
from gpiozero import PWMLED from gpiozero.tools import random_values from signal import pause led = PWMLED(4) led.source = random_values() led.source_delay = 0.1 pause()
Note that in the above example,
source_delay is used to
make the LED iterate over the random values slightly slower.
source_delay can be set to a larger number (e.g. 1 for a
one second delay) or set to 0 to disable any delay.
Some tools take a single source and process its values:
In this example, the LED is lit only when the button is not pressed:
from gpiozero import Button, LED from gpiozero.tools import negated from signal import pause led = LED(4) btn = Button(17) led.source = negated(btn) pause()
Note
Note that source tools which take one or more
value parameters support
passing either
ValuesMixin derivatives, or iterators, including a
device’s
values property.
Some tools combine the values of multiple sources:
In this example, the LED is lit only if both buttons are pressed (like an AND gate):
from gpiozero import Button, LED from gpiozero.tools import all_values from signal import pause button_a = Button(2) button_b = Button(3) led = LED(17) led.source = all_values(button_a, button_b) pause()
Similarly,
any_values() with two buttons would simulate an OR
gate.
While most devices have a
value range between 0 and 1, some have
a range between -1 and 1 (e.g.
Motor,
Servo and
TonalBuzzer). Some source tools output values between -1 and 1, which
are ideal for these devices, for example passing
sin_values() in:
from gpiozero import Motor, Servo, TonalBuzzer from gpiozero.tools import sin_values from signal import pause motor = Motor(2, 3) servo = Servo(4) buzzer = TonalBuzzer(5) motor.source = sin_values() servo.source = motor buzzer.source = motor pause()
In this example, all three devices are following the sine wave. The motor
value ramps up from 0 (stopped) to 1 (full speed forwards), then back down to 0
and on to -1 (full speed backwards) in a cycle. Similarly, the servo moves from
its mid point to the right, then towards the left; and the buzzer starts with
its mid tone, gradually raises its frequency, to its highest tone, then down
towards its lowest tone. Note that setting
source_delay
will alter the speed at which the device iterates through the values.
Alternatively, the tool
cos_values() could be used to start from -1
and go up to 1, and so on.
7.3. Internal devices¶
GPIO Zero also provides several internal devices which
represent facilities provided by the operating system itself. These can be used
to react to things like the time of day, or whether a server is available on the
network. These classes include a
values property which can
be used to feed values into a device’s
source. For example,
a lamp connected to an
Energenie socket can be controlled by a
TimeOfDay object so that it is on between the hours of 8am and 8pm:
from gpiozero import Energenie, TimeOfDay from datetime import time from signal import pause lamp = Energenie(1) daytime = TimeOfDay(time(8), time(20)) lamp.source = daytime lamp.source_delay = 60 pause()
Using the
DiskUsage class with
LEDBarGraph can show your Pi’s
disk usage percentage on a bar graph:
from gpiozero import DiskUsage, LEDBarGraph from signal import pause disk = DiskUsage() graph = LEDBarGraph(2, 3, 4, 5, 6, 7, 8) graph.source = disk pause()
Demonstrating a garden light system whereby the light comes on if it’s dark and
there’s motion is simple enough, but it requires using the
booleanized() source tool to convert the light sensor from a float
value into a boolean:
from gpiozero import LED, MotionSensor, LightSensor from gpiozero.tools import booleanized, all_values from signal import pause garden = LED(2) motion = MotionSensor(4) light = LightSensor(5) garden.source = all_values(booleanized(light, 0, 0.1), motion) pause()
7.4. Composite devices¶
The
value of a composite device made up of the nested values of
its devices. For example, the value of a
Robot object is a 2-tuple
containing its left and right motor values:
>>> from gpiozero import Robot >>> robot = Robot(left=(14, 15), right=(17, 18)) >>> robot.value RobotValue(left_motor=0.0, right_motor=0.0) >>> tuple(robot.value) (0.0, 0.0) >>> robot.forward() >>> tuple(robot.value) (1.0, 1.0) >>> robot.backward() >>> tuple(robot.value) (-1.0, -1.0) >>> robot.value = (1, 1) # robot is now driven forwards()
Note that this example uses the built-in
zip() rather than the tool
zip_values() as the
scaled() tool yields values which
do not need converting, just zipping. Also note that this use of
zip()
will not work in Python 2, instead use izip. | https://gpiozero.readthedocs.io/en/stable/source_values.html | CC-MAIN-2019-26 | refinedweb | 1,475 | 51.38 |
The Samba-Bugzilla – Bug 1098
AIX has msleep
Last modified: 2005-11-14 09:26:01 UTC
AIX has a function msleep in libc.
#include <sys/mman.h>
int msleep (Sem)
msemaphore * Sem;
Description
The msleep subroutine puts a calling process to sleep when a
semaphore is busy.
Samba also names a function msleep. This does not affect samba itself, but other
applications linked with libsmbclient might use the wrong "msleep". Symptom is
"timeout connecting to ..." when connecting to remote servers, because AIX
msleep does not sleep but fails immediatly with EFAULT.
msleep should be renamed.
I have a patch to rename this to smb_msleep()
I've checked in a patch to rename msleep() to smb_msleep().
sorry for the same, cleaning up the database to prevent unecessary reopens of bugs.
database cleanup | https://bugzilla.samba.org/show_bug.cgi?id=1098 | CC-MAIN-2017-26 | refinedweb | 132 | 65.93 |
(For more resources related to this topic, see here.)
For workflow transitions that have transition screens, you can add validation logic to make sure what the users put in is what you are expecting. This is a great way to ensure data integrity, and we can do this with workflow validators.
In this recipe, we will add a validator to perform a date comparison between a custom field and the issue's create date, so the date value we select for the custom field must be after the issue's create date.
Getting ready
For this recipe, we need to have the JIRA Suite Utilities add-on installed. You can download it from the following link or install it directly using the Universal Plugin Manager:
Since we are also doing a date comparison, we need to create a new date custom field called Start Date and add it to the Workflow Screen.
How to do it…
Perform the following steps to add validation rules during a workflow transition:
- Select and edit the workflow to configure.
- Select the Diagram mode.
- Select the Start Progress transition and click on the Validators link towards the right-hand side.
- Click on the Add validator link and select Date Compare from the list.
- Select the Start Date custom field for This date, > for Condition, and Created for Compare with, and click on Update to add the validator:
- Click on Publish Draft to apply the change.
After we add the validator, if we now try to select a date that is before the issue's create date, JIRA will prompt you with an error message and stop the transition from going through, as shown in the following screenshot:
How it works…
Validators are run after the user has executed the transition but before the transition starts. This way, validators can intercept and prevent a transition from going through if one or more of the validation logics fail.
If you have more than one validator, all of them must pass for the transition to go through.
See also
Validators can be used to make a field required only during workflow transitions.
Creating custom workflow transition logic
In the previous recipe, we have looked at using workflow conditions, validators, and post functions that come out of the box with JIRA and from other third-party add-ons.
In this recipe, we will take a look at how to use scripts to define our own validation rules for a workflow validator. We will address a common use case, which is to make a field required during a workflow transition only when another field is set to a certain value.
So, our validation logic will be as follows:
- If the Resolution field is set to Fixed, the Solution Details field will be required
- If the Resolution field is set to a value other than Fixed, the Solution Details field will not be required
Getting ready
For this recipe, we need to have the Script Runner add-on installed. You can download it from the following link or install it directly using the Universal Plugin Manager:
You might also want to get familiar with Groovy scripting ().
How to do it…
Perform the following steps to set up a validator with custom-scripted logic:
- Select and edit the Simple Workflow.
- Select the Diagram mode.
- Click on the Move to Backlog global workflow transition.
- Click on the Validators link from the panel on the right-hand side.
- Click on Add validator, select Script Validator from the list, and click on Add. Now enter the following script code in the Condition textbox:
import com.opensymphony.workflow.InvalidInputException import com.atlassian.jira.ComponentManager import org.apache.commons.lang.StringUtils def customFieldManager = ComponentManager.getInstance().getCustomFieldManager() def solutionField = customFieldManager.getCustomFieldObjectByName("Solution Details") def resolution = issue.getResolutionObject().getName() def solution = issue.getCustomFieldValue(solutionField) if(resolution == "Fixed" && StringUtils.isBlank(solution)) { false } else { true }
- Enter the text "You must provide the Solution Details if the Resolution is set to Fixed." for the Error field.
- Select Solution Details for Field.
- Click on the Add button to complete the validator setup.
- Click on Publish Draft to apply the change.
Your validator configuration should look something like the following screenshot:
Once we add our custom validator, every time the Move to Backlog transition is executed, the Groovy script will run. If the resolution field is set to Fixed and the Solution Details field is empty, we will get a message from the Error field as shown in the following screenshot:
How it works…
The Script Validator works just like any other validator, except that we can define our own validation logic using Groovy scripts. So, let's go through the script and see what it does.
We first get the Solution Details custom field via its name, as shown in the following line of code. If you have more than one custom field with the same name, you need to use its ID instead of its name.
def solutionField = customFieldManager.getCustomFieldObjectByName("Solution Details")
We then select the resolution value and obtain the value entered for Solution Details during the transition, as follows:
def resolution = issue.getResolutionObject().getName() def solution = issue.getCustomFieldValue(solutionField)
In our example, we check the resolution name; we can also check the ID of the resolution by changing getName() to getId().
If you have multiple custom fields with the same name, use getId().
Lastly, we check whether the Resolution value is Fixed and the Solution Details value is blank; in this case, we return a value of false, so the validation fails. All other cases will return the value true, so the validation passes. We also use StringUtils.isBlank(solution) to check for blank values so that we can catch cases when users enter empty spaces for the Solution Details field.
There's more…
You are not limited to creating scripted validators. With the Script Runner add-on, you can create scripted conditions and post functions using Groovy scripts.
Summary
In this article, we studied how to work with workflows, including permissions and user input validation.
Resources for Article:
Further resources on this subject:
- Getting Started with JIRA 4 [Article]
- Gadgets in JIRA [Article]
- Advanced JIRA 5.2 Features [Article] | https://www.packtpub.com/books/content/validating-user-input-workflow-transitions | CC-MAIN-2015-14 | refinedweb | 1,030 | 53.92 |
Using Backbone Within the WordPress Admin: The Front End
Welcome to the second part of Using Backbone Within the WordPress Admin. In the first part, we set up the 'back-end' of our plugin and now in the second part we'll finish off by adding our 'client-side' or 'front end' functionality. For an overview of what we're building in this tutorial along with our folder structure and files, please review the first part.
1. Create the Template File
Within the src folder, create another one called Templates and a file inside that one called metabox.templ.php. This is where we will be putting the HTML needed for our meta box. It's also a great opportunity to output the JSON data needed for our Answers.
Your folders and files should now look like this.
Create the Template for a Single Answer
Let's take another look at what we are creating. You can think of each Answer as a Model of data and because we'll be using client-side templates to generate a view for each one, that view can react to changes within the model. This allows us to be very specific when binding events to the UI and naturally leads to an easier workflow - once you've gotten your head around it, that is.
Inside our newly created metabox.templ.php, this is the template that we'll be using for each of our models. You can see that we are basically wrapping some HTML in a script tag. We give the script tag the attribute
type="text/template" so that the browser does not render it to the page. This small chunk of HTML is to be used later to generate the markup needed for each view. We will be using Underscore's built-in template capabilities so values wrapped like this
will be replaced by data in our models later on.
<!-- src/templates/metabox.templ.php --> <!-- Template --> <script type="text/template" id="inputTemplate"> <label for="<%= answer_id %>"><%= index %>:</label> <input id="<%= answer_id %>" class="answers" size="30" type="text" name="<%= answer_id %>" value="<%= answer %>" placeholder="Answer for Question <%= index %> Here"> <button disabled="true">Save</button> </script> <!-- End template -->
Base HTML
Still inside of src/templates/metabox.templ.php - here we are just laying down the containers that will be populated with the inputs from the template above. This happens after Backbone has parsed the JSON data needed for the model, so for now this is all we need to do here.
<!-- src/templates/metabox.templ.php --> <p>Enter the Answers below</p> <div id="answerInputs"></div> <div id="answerSelect"> <span>Correct Answer:</span> </div> <p> <input name="save" type="submit" class="button button-primary button-small" value="Save all"> </p>
Output the JSON
The final thing needed inside the src/templates/metabox.templ.php file, is the JSON data that represents each answer. Here we are creating an object on the Global Namespace and then assigning the values that we sent through with the
$viewData array. I also like to save references to the containers we will be using later on so that I don't have IDs in two seperate files.
<!-- src/templates/metabox.templ.php --> <script> window.wpQuiz = {}; var wpq = window.wpQuiz; wpq.answers = <?= $answers ?>; wpq.answers.correct = <?= $correct ?>; wpq.answerSelect = '#answerSelect'; wpq.answerInput = '#answerInputs'; wpq.inputTempl = '#inputTemplate'; wpq.post_id = <?= $post->ID ?>; </script>
2. The JavaScript
Ok, if you have gotten this far, you have successfully set-up your plugin to allow the use of Backbone.js and your meta box is outputting the required mark-up and JSON data. Now it's time to bring it all together and use Backbone.js to organise our client-side code. It's time to cover:
- Creating a collection of models from the JSON data
- Using client-side templates to construct a view for each
- Watching for click, key up and blur events within each view
- Saving a model back to the database
Create the File admin.js and Place It Into the js Folder
Your final directory structure and files should look like this.
First of all we'll wrap everything we do in an immediately called function and pass in jQuery to be used with the
$ sign, I won't show this wrapper in any more snippets, so ensure you put everything below within it.
/* js/admin.js */ (function($) { /** Our code here **/ }(jQuery));
Next we need to access our data stored on the global namespace and also create a new object that will store our Backbone objects.
/* js/admin.js */ var Quiz = { Views:{} }; var wpq = window.wpQuiz;
The Model
The model represents a single answer. Within its constructor we are doing a couple of things.
- Setting a default value for correct as
false
- Setting the URL that Backbone requires to save the model back to the database. We can access the correct URL thanks to WordPress proving the
ajaxurlvariable that is available on every admin page. We also append the name of our method that handles the ajax request
- Next we are overwriting the
toJSONmethod to append the current post's ID to each model. This could've been done server-side, but I've put it in here as an example of how you can override what is saved to the server (This can come in very handy which is why I've included it here)
- Finally in the initialize method, we are checking if the current model is the correct answer by comparing its ID to the ID of the correct answer. We do this so that later on we know which answer should be selected by default
/* js/admin.js */ Quiz.Model = Backbone.Model.extend({ defaults : { 'correct' : false }, url : ajaxurl+'?action=save_answer', toJSON : function() { var attrs = _.clone( this.attributes ); attrs.post_id = wpq.post_id; return attrs; }, initialize : function() { if ( this.get( 'answer_id' ) === wpq.answers.correct ) { this.set( 'correct', true ); } } });
The Collection
A Collection is essentially just a wrapper for a bunch of models and it makes working with those models a breeze. For our small example, we won't be modifying the collection, other than specifying which model it should use.
/* js/admin.js */ Quiz.Collection = Backbone.Collection.extend({ model: Quiz.Model });
The Inputs Wrapper
Our first view can be considered a wrapper for the individual input fields. We don't need to declare a template or which HTML element we want Backbone to create for us in this case, because later on when we instantiate this view, we'll pass it the ID of a
div that we created in the meta box file. Backbone will then simply use that element as its container. This view will take a collection and for each model in that collection, it will create a new
input element and append it to itself.
/* js/admin.js */ Quiz.Views.Inputs = Backbone.View.extend({ initialize:function () { this.collection.each( this.addInput, this ); }, addInput : function( model, index ) { var input = new Quiz.Views.Input({ model:model }); this.$el.append( input.render().el ); } });
A Single Input
This next view represents a single model. In the interest of showing off the types of things you can do when coding JavaScript this way, I've tried to provide a few different interaction techniques and show how to react to those with Backbone.
Note that we are specifying a '
tagName' here along with a template. In our case, this is going to grab that template we looked at earlier, parse it using data from the model, and then wrap everything in a
p tag (which will give us a nice bit of margin around each one).
Also note how events are bound to elements within a view. Much cleaner than your average jQuery callback and what's even better is the ability to use a jQuery selector like this
this.$('input') within our views knowing that they are automatically scoped within the view. This means that jQuery is not looking at the entire DOM when trying to match a selector.
In this view, we'll be able to:
- Know when an input field has been changed
- Update the model associated with it automatically (which will be used to automatically update the select field below it)
- Enable the save button at the side of the input that was changed
- Perform the save back to the database
/* js/admin.js */ Quiz.Views.Input = Backbone.View.extend({ tagName: 'p', // Get the template from the DOM template :_.template( $(wpq.inputTempl).html() ), // When a model is saved, return the button to the disabled state initialize:function () { var _this = this; this.model.on( 'sync', function() { _this.$('button').text( 'Save' ).attr( 'disabled', true ); }); }, // Attach events events : { 'keyup input' : 'blur', 'blur input' : 'blur', 'click button' : 'save' }, // Perform the Save save : function( e ) { e.preventDefault(); $(e.target).text( 'wait' ); this.model.save(); }, // Update the model attributes with data from the input field blur : function() { var input = this.$('input').val(); if ( input !== this.model.get( 'answer' ) ) { this.model.set('answer', input); this.$('button').attr( 'disabled', false ); } }, // Render the single input - include an index. render:function () { this.model.set( 'index', this.model.collection.indexOf( this.model ) + 1 ); this.$el.html( this.template( this.model.toJSON() ) ); return this; } });
The Select Element
This select element is where the user can choose the correct answer. When this view in instantiated, it will receive the same collection of models that the input's wrapper did. This will come in handy later because we'll be able to listen for changes to the model in the input fields and automatically update the corresponding values within this select element.
/* js/admin.js */ Quiz.Views.Select = Backbone.View.extend({ initialize:function () { this.collection.each( this.addOption, this ); }, addOption:function ( model ) { var option = new Quiz.Views.Option({ model:model }); this.$el.append( option.render().el ); } });
A Single Option View
Our final view will create an option element for each model and will be appended to the select element above. This time I've shown how you can dynamically set attributes on the element by returning a hash from a callback function assigned to the attributes property. Also note that in the
initialize() method we have 'subscribed' to change events on the model (specifically, the
answer attribute). This basically just means: any time this model's answer attribute is changed, call the
render() method (which in this case, will just update the text). This concept of 'subscribing' or 'listening' to events that occur within a model is really what make Backbone.js and the many other libraries like it so powerful, useful and a joy to work with.
/* js/admin.js */ Quiz.Views.Option = Backbone.View.extend({ tagName:'option', // returning a hash allows us to set attributes dynamically attributes:function () { return { 'value':this.model.get( 'answer_id' ), 'selected':this.model.get( 'correct' ) } }, // Watch for changes to each model (that happen in the input fields and re-render when there is a change initialize:function () { this.model.on( 'change:answer', this.render, this ); }, render:function () { this.$el.text( this.model.get( 'answer' ) ); return this; } });
Instantiate Collection and Views
We are so close now, all we have to do is instantiate a new collection and pass it the JSON it needs, then instantiate both of the 'wrapper' views for the select element and for the inputs. Note that we also pass the
el property to our views. These are references to the div and select element that we left blank earlier in the meta box.
/* js/admin.js */ var answers = new Quiz.Collection( wpq.answers ); var selectElem = new Quiz.Views.Select({ collection:answers, el :wpq.answerSelect }); var inputs = new Quiz.Views.Inputs({ collection:answers, el:wpq.answerInput });
3. Activate the Plugin
If you have made it to the end, you should now have a fully working example of how to incorporate Backbone JS into a WordPress plugin. If you go ahead and take a look at the source files, you'll notice that the actual amount of code needed to incorporate Backbone is relatively small. Much of the code we went over here was the PHP needed for the plugin. Working with Backbone on a daily basis for the last 6 weeks has really given me a new found respect for front end code organisation and I hope that you can appreciate the benefits that will surely come from working in this manner.
Within the WordPress community I can envision some of the more complex and high-quality plugins out there really benefiting from using Backbone and I am honoured to have been able to share with you a technique for doing exactly that.
Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| http://code.tutsplus.com/tutorials/using-backbone-within-the-wordpress-admin-the-front-end--wp-30121 | CC-MAIN-2015-32 | refinedweb | 2,111 | 54.52 |
Working on my connector sandbox I've been trying to run stuff in pax-exam and in unmodified
karaf. I ran into some rather hard to diagnose problems due to package versioning.
Our stax 1.2 api bundle includes the javax.xml.namespace package and it apparently matches
the same packages as implemented in java 5 and java 6. We are exporting it at version 1.0
but pax-exam/pax-runner and karaf export it with no version (version 0.0.0.0). We've modified
our copy of karaf to export at version 1.0. Trying to use our stax bundles and bundles compiled
against it (jaxb spec, jaxb impl, woodstox for example) cause mysterious CNFE and NCDFE inside
jaxb impl.
If I rebuild everything without this package version then I can run tests in pax-exam and
deploy stuff in regular karaf. I think we should remove this package version.
I see that we also have versions for
javax.jws;version="2.0", \
javax.jws.soap;version="2.0", \
and wonder if we will encounter similar problems with pax-exam and plain karaf with those
packages.
I think as a general policy that unless there's a compelling reason such as with javax.transaction,
until there is a spec defining package versions for stuff coming with java, we should not
version these packages.
I opened and I'm going to commit changes
to at least the affected bundles if not geronimo trunk.
thanks
david jencks | http://mail-archives.apache.org/mod_mbox/geronimo-dev/201103.mbox/%3C735E8CD7-9C1E-4C1C-8B19-88C26576ABE8@yahoo.com%3E | CC-MAIN-2016-40 | refinedweb | 248 | 66.84 |
#include <wx/config.h>
A handy little class which changes the current path in a wxConfig object and restores it in dtor.
Declaring a local variable of this type, it's possible to work in a specific directory and ensure that the path is automatically restored when the function returns.
For example:
Changes the path of the given wxConfigBase object so that the key strEntry is accessible (for read or write).
In other words, the ctor uses wxConfigBase::SetPath() with everything which precedes the last slash of strEntry, so that:
has the same effect of:
Restores the path selected, inside the wxConfig object passed to the ctor, to the path which was selected when the wxConfigPathChanger ctor was called.
Returns the name of the key which was passed to the ctor.
The "name" is just anything which follows the last slash of the string given to the ctor.
This method must be called if the original path inside the wxConfig object (i.e.
the current path at the moment of creation of this wxConfigPathChanger object) could have been deleted, thus preventing wxConfigPathChanger from restoring the not existing (any more) path.
If the original path doesn't exist any more, the path will be restored to the deepest still existing component of the old path. | https://docs.wxwidgets.org/3.1.5/classwx_config_path_changer.html | CC-MAIN-2021-31 | refinedweb | 214 | 56.49 |
// int Enum Pattern - has severe problems! public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; public static final int SEASON_SUMMER = 2; public static final int SEASON_FALL = 3;This pattern has many problems, such as:
intyou can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
SEASON_) to avoid collisions with other int enum types.
switchstatements.
In 5.0, the Java™ programming language gets linguistic support for enumerated types. In their simplest form, these enums look just like their C, C++, and C# counterparts:
enum Season { WINTER, SPRING, SUMMER, FALL }
But appearances can be deceiving. Java programming language
enums are far more powerful than their counterparts in other
languages, which are little more than glorified integers. The new
enum declaration defines a full-fledged class
(dubbed an enum type). In addition to solving all the
problems mentioned above, it allows you to add arbitrary methods
and fields to an enum type, to implement arbitrary interfaces,
and more. Enum types provide high-quality implementations of all
the Object methods. They are Comparable and
Serializable, and the serial form is designed to
withstand arbitrary changes in the enum type.
Here is an example of a playing card class built atop a couple
of simple enum types. The
Card class is immutable,
and only one instance of each
Card is created, so it
need not override
equals or
hashCode:
import java.util.*; public class Card { public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } private final Rank rank; private final Suit suit; private Card(Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } public Rank rank() { return rank; } public Suit suit() { return suit; } public String toString() { return rank + " of " + suit; } private static final List<Card> protoDeck = new ArrayList<Card>(); // Initialize prototype deck static { for (Suit suit : Suit.values()) for (Rank rank : Rank.values()) protoDeck.add(new Card(rank, suit)); } public static ArrayList<Card> newDeck() { return new ArrayList<Card>(protoDeck); // Return copy of prototype deck } }The
toStringmethod for
Cardtakes advantage of the
toStringmethods for
Rankand
Suit. Note that the
Cardclass is short (about 25 lines of code). If the typesafe enums (
Rankand
Suit) had been built by hand, each of them would have been significantly longer than the entire
Cardclass.
The (private) constructor of
Card takes two
parameters, a
Rank and a
Suit. If you
accidentally invoke the constructor with the parameters reversed,
the compiler will politely inform you of your error. Contrast
this to the
int enum pattern, in which the program
would fail at run time.
Note that each enum type has a static
values
method that returns an array containing all of the values of the
enum type in the order they are declared. This method is commonly
used in combination with the for-each
loop to iterate over the values of an enumerated type.
The following example is a simple program called
Deal that exercises
Card. It reads two
numbers from the command line, representing the number of hands
to deal and the number of cards per hand. Then it creates a new
deck of cards, shuffles it, and deals and prints the requested
hands.
import java.util.*; public class Deal { public static void main(String args[]) { int numHands = Integer.parseInt(args[0]); int cardsPerHand = Integer.parseInt(args[1]); List<Card> deck = Card.newDeck(); Collections.shuffle(deck); for (int i=0; i < numHands; i++) System.out.println(deal(deck, cardsPerHand)); } public static ArrayList<Card> deal(List<Card> deck, int n) { int deckSize = deck.size(); List<Card> handView = deck.subList(deckSize-n, deckSize); ArrayList<Card> hand = new ArrayList<Card>(handView); handView.clear(); return hand; } } $ java Deal 4 5 [FOUR of HEARTS, NINE of DIAMONDS, QUEEN of SPADES, ACE of SPADES, NINE of SPADES] [DEUCE of HEARTS, EIGHT of SPADES, JACK of DIAMONDS, TEN of CLUBS, SEVEN of SPADES] [FIVE of HEARTS, FOUR of DIAMONDS, SIX of DIAMONDS, NINE of CLUBS, JACK of CLUBS] [SEVEN of HEARTS, SIX of CLUBS, DEUCE of DIAMONDS, THREE of SPADES, EIGHT of CLUBS]
Suppose you want to add data and behavior to an enum. For example consider the planets of the solar system. Each planet knows its mass and radius, and can calculate its surface gravity and the weight of an object on the planet. Here is how it looks:(); } }
The enum type
Planet contains a constructor, and
each enum constant is declared with parameters to be passed to
the constructor when it is created.
Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):
The idea of adding behavior to enum constants can be taken one
step further. You can give each enum constant a different
behavior for some method. One way to do this by switching on the
enumeration constant. Here is an example with an enum whose
constants represent the four basic arithmetic operations, and
whose
eval method performs the operation:
public enum Operation { PLUS, MINUS, TIMES, DIVIDE; // Do arithmetic op represented by this constant double eval(double x, double y){ switch(this) { case PLUS: return x + y; case MINUS: return x - y; case TIMES: return x * y; case DIVIDE: return x / y; } throw new AssertionError("Unknown op: " + this); } }This works fine, but it will not compile without the throw statement, which is not terribly pretty. Worse, you must remember to add a new case to the switch statement each time you add a new constant to Operation. If you forget, the eval method with fail, executing the aforementioned throw statement
There is another way give each enum constant a different behavior for some method that avoids these problems. You can declare the method abstract in the enum type and override it with a concrete method in each constant. Such methods are known as constant-specific methods. Here is the previous example redone using this technique:); }
Here is a sample program that exercises the
Operation class. It takes two operands from the
command line, iterates over all the operations, and for each
operation, performs the operation and prints the resulting
equation:Constant-specific methods are reasonably sophisticated, and many programmers will never need to use them, but it is nice to know that they are there if you need them.
Two classes have been added to
java.util in
support of enums: special-purpose
Set and
Map implementations called
EnumSet
and
EnumMap.
EnumSet is a high-performance
Set
implementation for enums. All of the members of an enum set must
be of the same enum type. Internally, it is represented by a
bit-vector, typically a single
long. Enum sets
support iteration over ranges of enum types. For example given
the following enum declaration:
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }you can iterate over the weekdays. The
EnumSetclass provides a static factory that makes it easy:
for (Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY)) System.out.println(d);Enum sets also provide a rich, typesafe replacement for traditional bit flags:
EnumSet.of(Style.BOLD, Style.ITALIC)
Similarly,
EnumMap is a high-performance
Map implementation for use with enum keys,
internally implemented as an array. Enum maps combine the
richness and safety of the
Map interface with speed
approaching that of an array. If you want to map an enum to a
value, you should always use an EnumMap in preference to
an array.
The
Card class, above,
contains a static factory that returns a deck, but there is no
way to get an individual card from its rank and suit. Merely
exposing the constructor would destroy the singleton property
(that only a single instance of each card is allowed to exist).
Here is how to write a static factory that preserves the
singleton property, using a nested EnumMap:
private static Map<Suit, Map<Rank, Card>> table = new EnumMap<Suit, Map<Rank, Card>>(Suit.class); static { for (Suit suit : Suit.values()) { Map<Rank, Card> suitTable = new EnumMap<Rank, Card>(Rank.class); for (Rank rank : Rank.values()) suitTable.put(rank, new Card(rank, suit)); table.put(suit, suitTable); } } public static Card valueOf(Rank rank, Suit suit) { return table.get(suit).get(rank); }The
EnumMap(
table) maps each suit to an
EnumMapthat maps each rank to a card. The lookup performed by the
valueOfmethod is internally implemented as two array accesses, but the code is much clearer and safer. In order to preserve the singleton property, it is imperative that the constructor invocation in the prototype deck initialization in
Cardbe replaced by a call to the new static factory:
// Initialize prototype deck static { for (Suit suit : Suit.values()) for (Rank rank : Rank.values()) protoDeck.add(Card.valueOf(rank, suit)); }It is also imperative that the initialization of
tablebe placed above the initialization of protoDeck, as the latter depends on the former.
So when should you use enums? Any time you need a fixed set of constants. That includes natural enumerated types (like the planets, days of the week, and suits in a card deck) as well as other sets where you know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, and the like. It is not necessary that the set of constants in an enum type stay fixed for all time. The feature was specifically designed to allow for binary compatible evolution of enum types. | https://docs.oracle.com/javase/7/docs/technotes/guides/language/enums.html | CC-MAIN-2018-34 | refinedweb | 1,579 | 60.65 |
prerequisite to this section.
A
PersistentEntity has a stable entity identifier, with which it can be accessed from the service implementation or other places. The state of an entity is persistent (durable) using Event Sourcing. We represent all state changes as events and those immutable facts are appended to an event log. To recreate the current state of an entity when it is started we replay these events.
A persistent entity corresponds to an Aggregate Root in Domain-Driven Design terms. Each instance has a stable identifier and for a given id there will only be one instance of the entity. Lagom takes care of distributing those instances across the cluster of the service. If you know the identifier you can send messages, so called commands, to the entity.
The persistent entity is also a transaction boundary. Invariants can be maintained within one entity but not across several entities.
If you are familiar with JPA it is worth noting that a
PersistentEntity can be used for similar things as a JPA
@Entity but several aspects are rather different. For example, a JPA
@Entity is loaded from the database from wherever it is needed, i.e. there may be many Java object instances with the same entity identifier. In contrast, there is only one instance of
PersistentEntity with a given identifier. With JPA you typically only store current state and the history of how the state was reached is not captured.
You interact with a
PersistentEntity by sending command messages to it. Commands are processed sequentially, one at a time, for a specific entity instance. A command may result in state changes that are persisted as events, representing the effect of the command. The current state is not stored for every change, since it can be derived from the events. These events are only ever appended to storage, nothing is ever mutated, which allows for very high transaction rates and efficient replication.
The entities are automatically distributed across the nodes in the cluster of the service. Each entity runs only at one place, and messages can be sent to the entity without requiring the sender to know the location of the entity. If a node is stopped the entities running on that node will be started on another node when a message is sent to it next time. When new nodes are added to the cluster some existing entities are rebalanced to the new nodes to spread the load.
An entity is kept alive, holding its current state in memory, as long as it is used. When it has not been used for a while it will automatically be passivated to free up resources.
When an entity is started it replays the stored events to restore the current state. This can be either the full history of changes or starting from a snapshot which will reduce recovery times.
§Pers.
A command handler returns a Persist directive that defines what event or events, if any, to persist. Use the
thenPersist,
thenPersistAll or
done methods of the context that is passed to the command handler function to create the
Persist directive.
thenPersistwill persist one single event
thenPersistAllwill persist several events atomically, i.e. all events
are stored or none of them are stored if there is an error
doneno events are to be persisted
External side effects can be performed after successful persist in the
afterPersist function. In the above example a reply is sent with the
ctx.reply method..get) }
The commands must be immutable to avoid concurrency issues that may occur from changing a command instance that has been sent.
The section Immutable Objects describes how to define immutable command classes.
§Event Handlers
When an event has been persisted successfully the current state is updated by applying the event to the current state. The functions for updating the state are registered with the. The same event handlers are also used when the entity is started up to recover its state from the stored events.
The events must be immutable to avoid concurrency issues that may occur from changing an event instance that is about to be persisted.
The section Immutable Objects describes how to define immutable event classes.
§Replies
Each command must define what type of message to use as reply to the command by implementing the PersistentEntity.ReplyType interface.
final.
The state must be immutable to avoid concurrency issues that may occur from changing a state instance that is about to be saved as snapshot.
The section Immutable Objects describes how to define immutable state classes.
§Usage from Service Implementation
To access an entity from a service implementation you first need to inject the PersistentEntityRegistry and at startup (in the constructor) register the class that implements the
PersistentEntity.
In the service method you retrieve a
PersistentEntityRef for a given entity identifier from the registry. Then you can send the command to the entity using the
ask method of the
PersistentEntityRef.
ask returns a(ack => "OK") }
In this example we are using the command
AddPost also as the request parameter of the service method, but you can of course use another type for the external API of the service.
The commands are sent as messages to the entity that may be running on a different node. If that node is not available due to network issues, JVM crash or similar the messages may be lost until the problem has been detected and the entities have been migrated to another node. In such situations the
ask will time out and the
Future will be completed with
akka.pattern.AskTimeoutException.
Note that the
AskTimeoutException is not a guarantee that the command was not processed. For example, the command might have been processed but the reply message was lost.
§Serialization
JSON is the recommended format the persisted events and state. The Serialization section describes how to add Play-json serialization support to such classes and also how to evolve the classes, which is especially important for the persistent state and events, since you must be able to deserialize old objects that were stored.
§Unit Testing
For unit testing of the entity you can use the PersistentEntityTestDriver, which will run the
PersistentEntity without using a database. You can verify that it emits expected events and side-effects in response to incoming commands.
import import org.scalatest.WordSpecLike class PostSpec extends WordS) } } }
run may be invoked multiple times to divide the sequence of commands into manageable steps. The Outcome contains the events and side-effects of the last
run, but the state is not reset between different runs.
Note that it also verifies that all commands, events, replies and state are serializable, and reports any such problems in the
issues of the
Outcome.
To use this feature add the following in your project’s build:)
§Refactoring Consideration
If you change the class name of a
PersistentEntity you have to override
entityTypeName and retain the original name because this name is part of the key of the store data (it is part of the
persistenceId of the underlying
PersistentActor). By default the
entityTypeName is using the short class name of the concrete
PersistentEntity class.
§Configuration
The default configuration should be good starting point, and the following settings may later be amended to customize the behavior if needed. The following is a listing of the non database specific settings for Lagom persistence:
lagom.persistence { # As a rule of thumb, the number of shards should be a factor ten greater # than the planned maximum number of cluster nodes. Less shards than. The value # must be the same on all nodes in a running cluster. It can be changed # after stopping all nodes in the cluster. max-number-of-shards = 100 # Persistent entities saves snapshots after this number of persistent # events. Snapshots are used to reduce recovery times. # It may be configured to "off" to disable snapshots. snapshot-after = 100 # A persistent entity is passivated automatically if it does not receive # any messages during this timeout. Passivation is performed to reduce # memory consumption. Objects referenced by the entity can be garbage # collected after passivation. Next message will activate the entity # again, which will recover its state from persistent storage. Set to 0 # to disable passivation - this should only be done when the number of # entities is bounded and their state, sharded across the cluster, will # fit in memory. passivate-after-idle-timeout = 120s # Specifies that entities run on cluster nodes with a specific role. # If the role is not specified (or empty) all nodes in the cluster are used. # The entities can still be accessed from other nodes. run-entities-on-role = "" # Default timeout for PersistentEntityRef.ask replies. ask-timeout = 5s dispatcher { type = Dispatcher executor = "thread-pool-executor" thread-pool-executor { fixed-pool-size = 16 } throughput = 1 } }
§Underlying Implementation
Each
PersistentEntity instance is executed by a PersistentActor that is managed by Akka Cluster Sharding.. | https://www.lagomframework.com/documentation/1.6.x/scala/PersistentEntity.html | CC-MAIN-2020-24 | refinedweb | 1,474 | 53.61 |
.
What you'll learn
Learn how to use C++ from first principles in a practical hands-on way.
Understand how to use Custom types, virtual functions and objects to structure your code
Build your own function templates, namespaces and containers from the ground up.
Put everything together to create sophisticated programs that work with pointers, dynamic memory and overloaded functions to achieve the results you want.
Who this book is for
Read this book if you want to learn C++ and have a basic understanding of how computer programs work. You don't need to know a C-based language before you start, but a basic understanding of how programs are structured is helpful. | https://www.safaribooksonline.com/library/view/exploring-c-11/9781430261933/ | CC-MAIN-2017-04 | refinedweb | 114 | 57.61 |
You may not know it but you have the availability to define and play with counters in NiFi. If policies are correctly configured (if your NiFi is secured), you should be able to access the existing counters using the menu:
Counters are just values that you can increase or decrease of a given delta. This is useful if you want to monitor particular values along your workflow. At the moment, unless you use a processor that explicitly uses counters or provides a way to define counters, there is nothing available out of the box.
The best way to define and update counters is to use ExecuteScript processor with the following piece of Groovy code:
def flowFile = session.get() if(!flowFile) return session.adjustCounter("my-counter", 1, true) session.transfer(flowFile, REL_SUCCESS)
With this example, the ExecuteScript processor will just transmit the flow file without any modification to the success relationship but will also increment the counter “my-counter” of 1. If this counter does not exist it will be initialized with the delta value given as argument.
Here is the documentation of this method:
/** * Adjusts counter data for the given counter name and takes care of * registering the counter if not already present. The adjustment occurs * only if and when the ProcessSession is committed. * * @param name the name of the counter * @param delta the delta by which to modify the counter (+ or -) * @param immediate if true, the counter will be updated immediately, * without regard to whether the ProcessSession is commit or rolled back; * otherwise, the counter will be incremented only if and when the * ProcessSession is committed. */ void adjustCounter(String name, long delta, boolean immediate);
Let’s see an example: I want to confirm the correct behavior of the GetHDFS processor when I have multiple instances of this processor looking into the same directory but getting different flow files based on a regular expression.
Here is the first part of my flow:
Basically, I am generating flow files every 1ms with GenerateFlowFile. The generated flow files will be named after the generation date timestamp (without any extension). I am sending the files into HDFS and then I’m using a RouteOnAttribute where I check the filename according to a regular expression to split files according to even and uneven names. This way I can increment counters tracking the number of files I sent to HDFS with even names and with uneven names.
Here is the second part of my flow:
I have two instances of GetHDFS processor configured to look into the same input directory but one with a regular expression to look for files with an even name, and one to look for files with an uneven name, this way there is no concurrent access. Besides, the processor is configured to delete the file on HDFS once the file is retrieved in NiFi. Then I update two different counters to track the number of files with an even name that I retrieved from HDFS, and one for files with an uneven name.
If everything is working correctly, I should be able to let run my workflow a bit, then stop the generation of flow files, wait for all the flow files to be processed and confirm that:
- even-producer counter is equal to even-consumer counter
- unenven-producer counter is equal to uneven-consumer counter
Let’s have a look into our counters table:
It looks like we are all good 😉
As a remark, if you have multiple processors updating the same counter, then you will have the global value of the counter but also the value at each processor level. For example, if I have:
With both ExecuteScript incrementing the same “test” counter, then, I’ll have:
Also, as a last remark, you can notice that it’s possible to reset a counter to 0 from the counters table with the button in the last column (assuming you have write access to the counters based on the defined policies). It can be useful when doing some tests.
As always, questions/comments are welcomed!
6 thoughts on “Using counters in Apache NiFi”
[…] Using counters in Apache NiFi by Pierre Villard […]
Hi Pierre,
We have nifi 1.2, it seems not possible to delete the counter once it was created by executeScript or by UpdateCounter, it is correct ?
regards
Hi Mayki, sorry for the late answer. It seems to be correct. What’s the use case you have requiring to delete a counter? If you that’s something you need, feel free to raise a JIRA to get this added.
Hi pierre,
can i have the same code in javascript
Hi pierre,
with python script how to get counter values using Rest Api’s passing curl command
You might want to have a look at: | https://pierrevillard.com/2017/02/07/using-counters-in-apache-nifi/comment-page-1/ | CC-MAIN-2019-09 | refinedweb | 795 | 54.66 |
What is Narcissistic Personality Indicator and how does it connect to NumPy?
NumPy is an amazing library that makes analyzing data easy, especially numerical data.
In this tutorial we are going to analyze a survey with 11.000+ respondents from an interactive Narcissistic Personality Indicator (NPI) test.
Narcissism in personality trait generally conceived of as excessive self love. In Greek mythology Narcissus was a man who fell in love with his reflection in a pool of water.
The only connection between NPI and NumPy is that we want to analyze the 11.000+ answers.
The dataset can be downloaded here, which consists of a comma separated file, or CSV file for short and a description.
Step 1: Import the dataset and explore it
NumPy has thought of it for us, as simple as magic to load the dataset (in from the link above).
import numpy as np # This magic line loads the 11.000+ lines of data to a ndarray data = np.genfromtxt('data.csv', delimiter=',', dtype='int') # Skip first row data = data[1:] print(data)
And we print a summary out.
[[ 18 2 2 ... 211 1 50] [ 6 2 2 ... 149 1 40] [ 27 1 2 ... 168 1 28] ... [ 6 1 2 ... 447 2 33] [ 12 2 2 ... 167 1 24] [ 18 1 2 ... 291 1 36]]
A good idea is to investigate it from a spreadsheet as well to investigate it.
Oh, that end.
Then investigate the description from the dataset. (Here we have some of it).
For questions 1=40 which choice they chose was recorded per the following key. ... [The questions Q1 ... Q40] ... gender. Chosen from a drop down list (1=male, 2=female, 3=other; 0=none was chosen). age. Entered as a free response. Ages below 14 have been ommited from the dataset. -- CALCULATED VALUES -- elapse. (time submitted)-(time loaded) of the questions page in seconds. score. = ((int) $_POST['Q1'] == 1) ... [How it is calculated]
That means we score, answers to questions, elapsed time to answer, gender and age.
Reading a bit more, it says that a high score is an indicator for having narcissistic traits, but one should not conclude that it is one.
Step 2: Men or Women highest NPI?
I’m glad you asked.
import numpy as np data = np.genfromtxt('data.csv', delimiter=',', dtype='int') # Skip first row data = data[1:] # Extract all the NPI scores (first column) npi_score = data[:,0] print("Average score", npi_score.mean()) print("Men average", npi_score[data[:,42] == 1].mean()) print("Women average", npi_score[data[:,42] == 2].mean()) print("None average", npi_score[data[:,42] == 0].mean()) print("Other average", npi_score[data[:,42] == 3].mean())
Before looking at the result, see how nice the data the first column is sliced out to the view in npi_score. Then notice how easy you can calculate the mean based on a conditional rules to narrow the view.
Average score 13.29965311749533 Men average 14.195953307392996 Women average 12.081829626521191 None average 11.916666666666666 Other average 14.85
I guess you guessed it. Men score higher.
Step 3: Is there a correlation between age and NPI score?
I wonder about that too.
How can we figure that out? Wait, let’s ask our new friend NumPy.
import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt('data.csv', delimiter=',', dtype='int') # Skip first row data = data[1:] # Extract all the NPI scores (first column) npi_score = data[:,0] age = data[:,43] # Some age values are not real, so we adjust them to 0 age[age>100] = 0 # Scatter plot them all with alpha=0.05 plt.scatter(age, npi_score, color='r', alpha=0.05) plt.show()
Resulting in.
That looks promising. But can we just conclude that younger people score higher NPI?
What if most respondent are young, then that would make the picture more dense in the younger end (15-30). The danger with your eye is making fast conclusions.
Luckily, NumPy can help us there as well.
print(np.corrcoef(npi_score, age))
Resulting in.
Correlation of NPI score and age: [[ 1. -0.23414633] [-0.23414633 1. ]]
What does that mean? Well, looking at the documentation of np.corroef():
Return Pearson product-moment correlation coefficients.
It has a negative correlation, which means that the younger the higher NPI score. Values between 0.0 and -0.3 are considered low.
Is the Pearson product-moment correlation the correct one to use?
Step 4: (Optional) Let’s try to see if there is a correlation between NPI score and time elapsed
Same code, different column.
import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt('data.csv', delimiter=',', dtype='int') # Skip first row data = data[1:] # Extract all the NPI scores (first column) npi_score = data[:,0] elapse = data[:,41] elapse[elapse > 2000] = 2000 # Scatter plot them all with alpha=0.05 plt.scatter(elapse, npi_score, color='r', alpha=0.05) plt.show()
Resulting in.
Again, it is tempting to conclude something here. We need to remember that the mean value is around 13, hence, most data will be around there.
If we use the same calculation.
print("Correlation of NPI score and time elapse:") print(np.corrcoef(npi_score, elapse))
Output.
Correlation of NPI score and time elapse: [[1. 0.0147711] [0.0147711 1. ]]
Hence, here the there is close to no correlation.
Conclusion
Use the scientific tools to conclude. Do not rely on you eyes to determine whether there is a correlation.
The above gives an idea on how easy it is to work with numerical data in NumPy. | https://www.learnpythonwithrune.org/numpy-analyse-narcissistic-personality-indicator-numerical-dataset/ | CC-MAIN-2021-25 | refinedweb | 920 | 70.7 |
Text processing package
After we’ve written the first package, let’s take a look at some examples of other packages that we can write. This section will guide you to create a simple command to replace the selected text with ASCII art. When you run example should show you how to do basic text manipulation in the current text buffer and how to handle selection.
The last bag is in View in.
Basic text insertion
Press first
cmd-shift-PTo pop up the command panel. Then enter “generate package” and select the “package generator: generate package” command, as we did in the “package generator” section. input
ascii-artAs the name of the package.
Now let’s edit the files in the package to let our character painting package do something interesting. Since this package does not need any UI, we can remove all view related ones, so we can safely delete them
lib/ascii-art-view.coffee、
spec/ascii-art-view-spec.coffeeand
styles/。
Next, open
lib/ascii-art.coffeeAnd remove all view code, so it looks like this:
{CompositeDisposable} = require 'atom' module.exports = subscriptions: null activate: -> @subscriptions = new CompositeDisposable @subscriptions.add atom.commands.add 'atom-workspace', 'ascii-art:convert': => @convert() deactivate: -> @subscriptions.dispose() convert: -> console.log 'Convert text!'
Create command
Now let’s add a command. It is strongly recommended that you take a namespace for your command, followed by a package name
:。 So you can see in the code, we call the command
ascii-art:convert, and when it calls
convert()method.
So far, it’s only recorded in the console. Let’s start by inserting some characters into the text buffer.
convert: -> if editor = atom.workspace.getActiveTextEditor() editor.insertText('Hello, World!')
As in word count, we use
atom.workspace.getActiveTextEditor()To get the object that represents the currently active editor. If
convert()Method is called when there is no editor to get focus, it simply returns a blank string, so we can skip the next line.
Next we use
insertText()Method to insert a string into the current text editor. No matter where the cursor is currently in the editor, text is inserted at the cursor. If any text is selected, the selected text is replaced with “Hello, world!” text.
Reload package
Before we can trigger
ascii-art:convertBefore, we need to reload the window to load the latest code of our package. From the command panel or press
ctrl-alt-cmd-lTo run the window: reload command.
Trigger command
Now you can open the command panel and search for the ASCII Art: convert command. But not at all. To fix it, turn it on
package.jsonAnd find
activationCommandsProperty. Active commands speed up atom startup by delaying the loading of commands when they are not in use. So remove the existing command and
activationCommandsAdd to
ascii-art:convert:
"activationCommands": { "atom-workspace": "ascii-art:convert" }
First, reload the window through the window: reload command in the command panel. Now you can execute the ASCII Art: convert command, which will output “Hello, world!”.
Add shortcut key
Now let’s add the trigger “ASCII”- art:convert ”Shortcut key for the command. open
keymaps/ascii-art.cson, add a key binding to
ctrl-alt-alink to
ascii-art:convertOn command. Since you don’t need default key bindings, you can delete them.
When it’s done, it should look like this:
'atom-text-editor': 'ctrl-alt-a': 'ascii-art:convert'
Now reload the window and verify that the shortcut works.
Add character painting
Now we need to convert the selected characters into character paintings. In order to complete it, we use the
figletNode module. open
package.json, add the latest version of figlet to
dependenciesMedium:
"dependencies": { "figlet": "1.0.8" }
Run update package dependencies: update from the command panel after saving the file. This will automatically install the node module dependency of the package, in this case only figlet. Whenever you update
package.jsonIn the file
dependenciesField, you need to run the “update package dependencies: update” command.
If it doesn’t work for some reason, you will see the message “failed to update package dependencies”, and you will find a new one in your directory
npm-debug.logDocuments. This document will tell you exactly where there is an error.
Now in
lib/ascii-art.coffeeRequest in
figletNode module, and converts the selected text to character drawing instead of inserting “Hello, world!”.
convert: -> if editor = atom.workspace.getActiveTextEditor() selection = editor.getSelectedText() figlet = require 'figlet' font = "o8" figlet selection, {font: font}, (error, art) -> if error console.error(error) else editor.insertText("\n#{art}\n")
Reload the editor, select some text in the editor window, and press
ctrl-alt-aInstead, it will be replaced with a funny character drawing version.
In this case, we need to see something new quickly. First of all
editor.getSelectedText(), as you guessed, returns the currently selected text.
Then we call figlet’s code to convert it to something else and use the
editor.insertText()Replace the currently selected text with it.
Summary
In this section, we write a package without UI to get the selected text and replace it with the processed version. It may be helpful to create text prompts and check tools. | https://developpaper.com/translation-of-atom-flight-manual-3-4-text-processing-package/ | CC-MAIN-2020-24 | refinedweb | 867 | 50.33 |
Hello.
I have strange behavior in new 96.115 release with imports completion. Consider samples below.
1. Nested modules:
root
__init__.py
nested_mod.py
client_mod.py
Code in client_mod.py:
import ro<Ctrl-Space> -> import root (OK)
import root.<Ctrl-Space> -> import root.nested_mod (OK)
But:
form ro<Ctrl-Space> -> from root (OK)
from root.<Ctrl-Space> -> no suggestion for nested_mod (F)
import root.nested_mod
ro<Ctrl-Space> -> root
root.<Ctrl-Space> -> no suggestion for nested_mod
2.
import module
module.<ctrl-space> -> Sometimes(!) __init__.py and some other py files are shown in the list. Not all of them.
Should I create issue for 1? For 2 I can't make sample to reproduce at this moment.
Thanks again for (I hope) best IDE for Python in future.
---
wbr, Serge Travin.
Hello Serge,
You don't have to ask in the forums before filing YouTrack issues. :-) Please
do.
--
Dmitry Jemerov
Development Lead
JetBrains, Inc.
"Develop with Pleasure!"
Hello Dmitry.
I've decided to ask since this feaure (completion for modules) was inroduced (fixed) in new relase.
And I was thinking that might I'm missing smth in options or completion concept. =)
New issue -
Also, please, close this one - since it seems to be fixed in new release.
I've tried to mark it as duplication, but stuck with issue id in command.
Version 96.115 is not avaliable in "Affected version" field. Is it normal?
---
wbr, Serge Travin.
Hello Dmitry,
Sorry avout posting in this thread.
I'm stuck wih following two problems in PyCharm:
1. IDE often refuses to open "Find usages" and "Find in path" dialogs and reports about internal error in status bar. Restarting solves this problem, but it happens in about 40% of starts.
2. Follwing sequence hangs IDE with 100% CPU on one of the cores:
a. Open js-file.
b. Find some function and call "Find usages".
c. In the results window double-click on any of the found usages.
Result - IDE hangs and do not repond to any actions. (E.g click close btn)
I've tried to do the same actions in WebStorm beta, but got the same result. (I mean only second problem).
Could u suggest smth to collect more info about these issues?
Thanks in advance!
---
wbr, Serge Travin.
Hello Serge,
Could you please post a YouTrack issue and include the stacktrace of the
internal error?
Could you please file a YouTrack issue and attach the contents of %USERHOME%\.PyCharm10\system\log\threadDumps-xxx
from the session in which you experienced the hang?
--
Dmitry Jemerov
Development Lead
JetBrains, Inc.
"Develop with Pleasure!" | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206583595-Imports-completion?sort_by=created_at | CC-MAIN-2020-34 | refinedweb | 432 | 71.21 |
Sun 1 Jul 2012
A Simple SqlAlchemy 0.7 / 0.8 Tutorial
Posted by Mike under Python, SqlAlchemy
[10] Comments
A couple years ago I wrote a rather flawed tutorial about SQLAlchemy. I decided it was about time for me to re-do that tutorial from scratch and hopefully do a better job of it this time around. Since I’m a music nut, we’ll be creating a simple database to store album information. A database isn’t a database without some relationships, so we’ll create two tables and connect them. Here are a few other things we’ll be learning:
- Adding data to each table
- Modifying data
- Deleting data
- Basic queries
But first we need to actually make the database, so that’s where we’ll begin our journey. Note that SQLAlchemy is a 3rd party package, so you’ll need to install it if you want to follow along.
How to Create a Database
Creating a database with SQLAlchemy is really easy. They have gone completely with their Declarative method of creating databases now, so we won’t be covering the old school method. You can read the code here and then we’ll explain it following the listing. If you want a way to view your SQLite database, I would recommend the SQLite Manager plugin for Firefox. Or you could use the simple wxPython application that I created a month ago.
# table_def.py from sqlalchemy import create_engine, ForeignKey from sqlalchemy import Column, Date, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref engine = create_engine('sqlite:///mymusic.db', echo=True) Base = declarative_base() ######################################################################## class Artist(Base): """""" __tablename__ = "artists" id = Column(Integer, primary_key=True) name = Column(String) #---------------------------------------------------------------------- def __init__(self, name): """""" self.name = name ######################################################################## class Album(Base): """""" __tablename__ = "albums" id = Column(Integer, primary_key=True) title = Column(String) release_date = Column(Date) publisher = Column(String) media_type = Column(String) artist_id = Column(Integer, ForeignKey("artists.id")) artist = relationship("Artist", backref=backref("albums", order_by=id)) #---------------------------------------------------------------------- def __init__(self, title, release_date, publisher, media_type): """""" self.title = title self.release_date = release_date self.publisher = publisher self.media_type = media_type # create tables Base.metadata.create_all(engine)
If you run this code then you should see the following output sent to stdout:
2012-06-27 16:34:24,479 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("artists")
2012-06-27 16:34:24,479 INFO sqlalchemy.engine.base.Engine ()
2012-06-27 16:34:24,480 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("albums")
2012-06-27 16:34:24,480 INFO sqlalchemy.engine.base.Engine ()
2012-06-27 16:34:24,480 INFO sqlalchemy.engine.base.Engine
CREATE TABLE artists (
id INTEGER NOT NULL,
name VARCHAR,
PRIMARY KEY (id)
)
2012-06-27 16:34:24,483 INFO sqlalchemy.engine.base.Engine ()
2012-06-27 16:34:24,558 INFO sqlalchemy.engine.base.Engine COMMIT
2012-06-27 16:34:24,559 INFO sqlalchemy.engine.base.Engine
CREATE TABLE albums (
id INTEGER NOT NULL,
title VARCHAR,
release_date DATE,
publisher VARCHAR,
media_type VARCHAR,
artist_id INTEGER,
PRIMARY KEY (id),
FOREIGN KEY(artist_id) REFERENCES artists (id)
)
2012-06-27 16:34:24,559 INFO sqlalchemy.engine.base.Engine ()
2012-06-27 16:34:24,615 INFO sqlalchemy.engine.base.Engine COMMIT
Why did this happen? Because when we created the engine object, we set its echo parameter to True. The engine is where the database connection information is and it has all the DBAPI stuff in it that makes communication with your database possible. You’ll note that we’re creating a SQLite database. Ever since Python 2.5, SQLite has been supported by the language. If you want to connect to some other database, then you’ll need to edit the connection string. Just in case you’re confused about what we’re talking about, here is the code in question:
engine = create_engine('sqlite:///mymusic.db', echo=True)
The string, ‘sqlite:///mymusic.db’, is our connection string. Next we create an instance of the declarative base, which is what we’ll be basing our table classes on. Next we have two classes, Artist and Album that define what our database tables will look like. You’ll notice that we have Columns, but no column names. SQLAlchemy actually used the variable names as the column names unless you specifically specify one in the Column definition. You’ll note that we are using an “id” Integer field as our primary key in both classes. This field will auto-increment. The other columns are pretty self-explanatory until you get to the ForeignKey. Here you’ll see that we’re tying the artist_id to the id in the Artist table. The relationship directive tells SQLAlchemy to tie the Album class/table to the Artist table. Due to the way we set up the ForeignKey, the relationship directive tells SQLAlchemy that this is a many-to-one relationship, which is what we want. Many albums to one artist. You can read more about table relationships here.
The last line of the script will create the tables in the database. If you run this script multiple times, it won’t do anything new after the first time as the tables are already created. You could add another table though and then it would create the new one.
How to Insert / Add Data to Your Tables
A database isn’t very useful unless it has some data in it. In this section we’ll show you how to connect to your database and add some data to the two tables. It’s much easier to take a look at some code and then explain it, so let’s do that!
import datetime from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from table_def import Album, Artist engine = create_engine('sqlite:///mymusic.db', echo=True) # create a Session Session = sessionmaker(bind=engine) session = Session() # Create an artist new_artist = Artist("Newsboys") new_artist.albums = [Album("Read All About It", datetime.date(1988,12,01), "Refuge", "CD")] # add more albums more_albums = [Album("Hell Is for Wimps", datetime.date(1990,07,31), "Star Song", "CD"), Album("Love Liberty Disco", datetime.date(1999,11,16), "Sparrow", "CD"), Album("Thrive", datetime.date(2002,03,26), "Sparrow", "CD")] new_artist.albums.extend(more_albums) # Add the record to the session object session.add(new_artist) # commit the record the database session.commit() # Add several artists session.add_all([ Artist("MXPX"), Artist("Kutless"), Artist("Thousand Foot Krutch") ]) session.commit()
First we need to import our table definitions from the previous script. Then we connect to the database with our engine and create something new, the Session object. The session is our handle to the database and let’s us interact with it. We use it to create, modify, and delete records and we also use sessions to query the database. Next we create an Artist object and add an album. You’ll note that to add an album, you just create a list of Album objects and set the artist object’s “albums” property to that list or you can extend it, as you see in the second part of the example. At the end of the script, we add three additional Artists using the add_all. As you have probably noticed by now, you need to use the session object’s commit method to write the data to the database. Now it’s time to turn our attention to modifying the data.
A Note about __init__: As some of my astute readers pointed out, you actually do not need the __init__ constructors for the table definitions. I left them in there because the official documentation was still using them and I didn’t realize I could leave them out. Anyway, if you leave the __init__ out of your declarative table definition, then you’ll need to use keyword arguments when creating a record. For example, you would do the following rather than what was shown in the previous example:
new_artist = Artist(name="Newsboys") new_artist.albums = [Album(title="Read All About It", release_date=datetime.date(1988,12,01), publisher="Refuge", media_type="CD")]
How to Modify Records with SQLAlchemy
What happens if you saved some bad data. For example, you typed your favorite album’s title incorrectly or you got the release date wrong for that fan edition you own? Well you need to learn how to modify that record! This will actually be our jumping off point into learning SQLAlchemy queries as you need to find the record that you need to change and that means you need to write a query for it. Here’s some code that shows us the way:
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from table_def import Album, Artist engine = create_engine('sqlite:///mymusic.db', echo=True) # create a Session Session = sessionmaker(bind=engine) session = Session() # querying for a record in the Artist table res = session.query(Artist).filter(Artist.name=="Kutless").first() print res.name # changing the name res.name = "Beach Boys" session.commit() # editing Album data artist, album = session.query(Artist, Album).filter(Artist.id==Album.artist_id).filter(Album.title=="Thrive").first() album.title = "Step Up to the Microphone" session.commit()
Our first query goes out and looks up an Artist by name using the filter method. The “.first()” tells SQLAlchemy that we only want the first result. We could have used “.all()” if we thought there would be multiple results and we wanted all of them. Anyway, this query returns an Artist object that we can manipulate. As you can see, we changed the name from “Kutless” to “Beach Boys” and then committed out changes.
Querying a joined table is a little bit more complicated. This time we wrote a query that queries both our tables. It filters using the Artist id AND the Album title. It returns two objects: an artist and an album. Once we have those, we can easily change the title for the album. Wasn’t that easy? At this point, we should probably note that if we add stuff to the session erroneously, we can rollback our changes/adds/deletes by using session.rollback(). Speaking of deleting, let’s tackle that subject!
How to Delete Records in SQLAlchemy
Sometimes you just have to delete a record. Whether it’s because you’re involved in a cover-up or because you don’t want people to know about your love of Britney Spears music, you just have to get rid of the evidence. In this section, we’ll show you how to do just that! Fortunately for us, SQLAlchemy makes deleting records really easy. Just take a look at the following code!
# deleting_data.py from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from table_def import Album, Artist engine = create_engine('sqlite:///mymusic.db', echo=True) # create a Session Session = sessionmaker(bind=engine) session = Session() res = session.query(Artist).filter(Artist.name=="MXPX").first() session.delete(res) session.commit()
As you can see, all you had to do was create another SQL query to find the record you want to delete and then call session.delete(res). In this case, we deleted our MXPX record. Some people think punk will never die, but they must not know any DBAs! We’ve already seen queries in action, but let’s take a closer look and see if we can learn anything new.
The Basic SQL Queries of SQLAlchemy
SQLAlchemy provides all the queries you’ll probably ever need. We’ll be spending a little time just looking at a few of the basic ones though, such as a couple simple SELECTs, a JOINed SELECT and using the LIKE query. You’ll also learn where to go for information on other types of queries. For now, let’s look at some code:
# queries.py from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from table_def import Album, Artist engine = create_engine('sqlite:///mymusic.db', echo=True) # create a Session Session = sessionmaker(bind=engine) session = Session() # how to do a SELECT * (i.e. all) res = session.query(Artist).all() for artist in res: print artist.name # how to SELECT the first result res = session.query(Artist).filter(Artist.name=="Newsboys").first() # how to sort the results (ORDER_BY) res = session.query(Album).order_by(Album.title).all() for album in res: print album.title # how to do a JOINed query qry = session.query(Artist, Album) qry = qry.filter(Artist.id==Album.artist_id) artist, album = qry.filter(Album.title=="Thrive").first() print # how to use LIKE in a query res = session.query(Album).filter(Album.publisher.like("S%a%")).all() for item in res: print item.publisher
The first query we run will grab all the artists in the database (a SELECT *) and print out each of their name fields. Next you’ll see how to just do a query for a specific artist and return just the first result. The third query shows how do a SELECT * on the Album table and order the results by album title. The fourth query is the same query (a query on a JOIN) we used in our editing section except that we’ve broken it down to better fit PEP8 standards regarding line length. Another reason to break down long queries is that they become more readable and easier to fix later on if you messed something up. The last query uses LIKE, which allows us to pattern match or look for something that’s “like” a specified string. In this case, we wanted to find any records that had a Publisher that started with a capital “S”, some character, an “a” and then anything else. So this will match the publishers Sparrow and Star, for example.
SQLAlchemy also supports IN, IS NULL, NOT, AND, OR and all the other filtering keywords that most DBAs use. SQLAlchemy also supports literal SQL, scalars, etc, etc.
Wrapping Up
At this point you should know SQLAlchemy well enough to get started using it confidently. The project also has excellent documentation that you should be able to use to answer just about anything you need to know. If you get stuck, the SQLAlchemy users group / mailing list is very responsive to new users and even the main developers are there to help you figure things out.
Source Code
Further Reading
- SQLAlchemy official documentation
- wxPython and SQLAlchemy: Loading Random SQLite Databases for Viewing
- SqlAlchemy: Connecting to pre-existing databases
- wxPython and SqlAlchemy: An Intro to MVC and CRUD
- Another Step-by-Step SqlAlchemy Tutorial (part 1 of 2)
Pingback: Code! Code! Code!
Pingback: Python and SQLAlchemy 0.8 example | Thomas Spycher | http://www.blog.pythonlibrary.org/2012/07/01/a-simple-sqlalchemy-0-7-0-8-tutorial/ | CC-MAIN-2014-42 | refinedweb | 2,412 | 66.54 |
geocoding and navigation let you add turn-by-turn directions right in your app, so users don’t need to switch apps to get where they need to go. Take advantage of built-in maps designed especially for navigation, focusing on roads and traffic conditions and highlighting key landmarks.
Directions
With our Directions library, you can add driving, walking, and cycling routes to your app and draw it on a map.
Geocoding
Our Geocoding library lets you turn coordinates into addresses or addresses into coordinates.
Offline maps
Maps no longer need a data connection. Both our Android and iOS SDKs iOS and Android SDKs are 100% open source, licensed under BSD with all development and discussions happening on GitHub. Read more about our approach to open source at Mapbox.Mapbox GL Native on Github
The Mapbox iOS and Android SDKs are in stable production with frequent releases.
The Mapbox Cocoa API works just like Apple's MapKit — swap out
MKMapView for
MGLMapView and make the switch to Mapbox.
To start developing, create a Mapbox account to get an access token and install Mapbox. Our guide First steps with the Mapbox iOS SDK will help you install the SDK, initialize a map, and more.
import Mapbox let mapView = MGLMapView(frame: view.frame) let coordinate = CLLocationCoordinate2D(latitude: 38.9128971, longitude: -77.0326169) mapView.setCenterCoordinate(coordinate, zoomLevel: 15, animated: true) view.addSubview(mapView)
Mapbox on Android works just like Google Maps — swap out
com.google.android.gms.maps.MapView for
com.mapbox.mapboxsdk.maps.MapView and make the switch to Mapbox.
To start developing, create a Mapbox account to get an access token and install the SDK. Our guide First steps with the Mapbox Android SDK will help you install the SDK, initialize a map, and more.
import com.mapbox.mapboxsdk.maps.MapView; MapView mapView = (MapView) findViewById(R.id.myMapboxMapView); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback()); | https://www.mapbox.com/mobile/ | CC-MAIN-2017-04 | refinedweb | 314 | 57.98 |
Opened 11 years ago
Closed 11 years ago
Last modified 46 years ago
#388 closed bug (Rejected)
Incorrect "Defined but not used"
Description
This is johndetr@microsoft.com. When I compile the following function: 150 hexArg :: P Hex 151 hexArg = do MyState i n <- getState 152 let i = i + 1 153 setState (MyState i n) 154 x <- hexNumber 155 if i < n then do { char ','; return () } 156 else do { char ')'; eof } 157 return x I get the following messages: Vesta.hs:151:20: Warning: Defined but not used: `i' Vesta.hs:152:16: Warning: This binding for `i' shadows an existing binding In the binding group for: i The second is correct, if course, but the first is not. If I change the new binding to i' instead of i (and the references below, of course) *both* messages go away! Please let me know if you'd like more information, a shorter error case, etc.
Change History (1)
comment:1 Changed 11 years ago by simonpj
- Status changed from assigned to closed
Note: See TracTickets for help on using tickets. | https://ghc.haskell.org/trac/ghc/ticket/388 | CC-MAIN-2016-18 | refinedweb | 180 | 63.73 |
Resources
Debugging Race Conditions in C/C++
Bugs that are hard to reproduce suck up time and energy of any software development team. One cause of these bugs can be race conditions, which can cause erratic and confusing behavior and make getting a reliable bug report nearly impossible.
But there are ways of solving race conditions, either using a careful strategy or adding some useful debugging tools and this can save a huge amount of time and money. We'll cover both the best strategy and the best time saving tools in this post.
What are race conditions?
Race conditions in software or any system occur when the desired output requires that certain events occur in a specific order but that the events don’t always happen in that order. There is a ‘race’ between the events and if the wrong events win, the program fails.
For example, if your code works out a discount by applying a fixed discount of $1 and then a 10% discount on top of that, it's important that those discounts are worked out in that order. But if the $1 discount and 10% discount sometimes happen in the reverse order, the discount will sometimes - apparently randomly - be different:
50 - 1 * 0.9 = 44.1
50 * 0.9 - 1 = 44
Any complex piece of software is going to make extensive use of threads and other causes of concurrency, such as microservices, and so race conditions become more common as systems become more complex. Race conditions are, by their nature, hard to debug because they cause erratic and apparently random behavior which can vary across systems and with different inputs.
Which event wins the race may be determined by external data, memory or some other non-deterministic factor which means unless you are able to reproduce the exact input and timing for both cases, you won't get the same exact output.
Added to this, race conditions don't just cause crashes, they may just change the behavior of the program in tiny and sometimes innocent ways, such as a $0.10 difference in a discount or the program sometimes hanging randomly. When all a software engineer wants is a good description of the bug, a reliable way of reproducing it and an idea of how to fix it, race conditions are a perfect storm of not enough information or certainty about anything.
A quick skim down Stack Overflow's race conditions tag gives an idea of the breadth of causes and pain race condition bugs bring. Googling or searching forums will bring the same sort of responses.
Is this a race condition?
Firstly, how do you know if some erratic behavior is caused by a race condition? Well, race conditions cause erratic behavior, but not all erratic behavior is caused by race conditions. Until you've found the underlying cause and confirmed that the order of two events are causing the race condition, you don't know for sure that it is a race condition. But there are some tells which you can feed into your differential diagnosis.
The bug is likely to be erratic, sometimes fixing itself or behaving differently but apparently at random. This can be enough to drive anyone completely mad.
The behavior may differ in dev, test and production. Production might have far more data, or dev might be running on more powerful machines. These subtle differences point to race conditions.
But really, there’s no way of knowing that race conditions are the cause upfront so you need to dive in and start debugging. There are two fixes: one using traditional debugging tools and the other using time travel debugging.
How to find and fix race condition bugs in C/C++ the hard way
Your starting point is likely to be the program entering a confusing state or just crashing, which may give you a value, some text or a code reference. From this starting point, you need to extract an idea and form a hypothesis about how the program got into this state.
A typical strategy that you can find suggested on many forums on the web is to add extensive extra logging to the program, effectively print out almost every variable so you can map what you expect to what's happening.
At some point, you'll hit upon a critical data structure which is being affected by the race condition - this is your first smoking gun. The data structure will send the program into an unwanted series of events which result in it crashing or some weird state happening.
If you don't have time travel debugging - which I'll explain in a moment - then you need to use this knowledge of the data structure to find out what other parts of the program are likely to be affecting it.
You next need to find the parts of the program which are racing to change the data structure, hopefully leading you to successfully find and fix the race condition. The name of the data structure and the contents can be useful in finding these parts of the program.
The name of the data structure may be referred to throughout the rest of the program, perhaps leading you to find a few places which are racing and independently changing the value. But the contents of the data structure may also help you. For example, in the discount calculation example I gave it could be that you can simply look at the rest of the calculation and form an idea about where in the program discounts are calculated and simply walk through each of them. While this is methodical, it’s painstaking, expensive and prone to human error when you miss the bug in hours of reading over code.
When you have an idea about where the race conditions are coming from, it's time to test your theory; put in a breakpoint and step through until you see the race happening which will be where one part of the code runs before you expect it to or a value isn’t what you expect. If you have an idea of what the right values in the data structure are then you could set a conditional breakpoint which will speed things up.
Through one of these means - recognizing the unexpected data, finding some likely candidates for code that's corrupting data or setting conditional breakpoints - you will find a candidate for the code which is breaking things. However, because this is a race condition you might not be able to replicate the issue easily - so, even with the best information you might still have to resort to running a test many times until you've found the underlying cause.
How to find and fix race condition bugs in C/C++ using time travel debugging
There is another way which involves using time travel debugging (a.k.a. reverse debugging).
Reverse debugging is the ability of a debugger to stop after a failure in a program has been observed and go back into the history of the execution to uncover the reason for the failure.
Without a good debugging tool, there's no simple method to attack hard to reproduce bugs and it can quickly descend into a brute force attempt to log ever more values until you can see what's happening in the program. You may have to execute the code multiple times in the hope of seeing the bug, perhaps introducing randomness in the inputs or guessing at what the underlying cause is.
Time Travel Debugging
Find and fix test failures in minutes - save time on debugging C/C++. Try for yourself.
Get Free Trial >>
So, for hard to reproduce bugs like race conditions, reverse debugging allows you to start from the point of failure and step back to find the cause. This is a very different and much more satisfying method, which is worth walking through to see the impact time travel debugging has on debugging race conditions.
We’re basing this on an example program you can grab from the end of this post.
First, you don't necessarily even need to identify where the program fails. You start UDB (our time travel debugger), pointing it at the program:
./udb race
Start by running the program and see where it goes wrong:
not running> run ... threadfn1: i=20000 threadfn1: i=30000 race: race.cpp:47: void threadfn1(): Assertion `g_value == old_value + a' failed. [New Thread 108.120] [New Thread 108.119] [New Thread 108.121] Thread 2 received signal SIGABRT, Aborted. [Switching to Thread 108.120] __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51 51 }
In our example, the error is all about the
Assertion `g_value == old_value + a' failed
We want to know why one thread expects one value but gets another. We use
reverse-finish to step back out of the C standard library until we arrive at a line in our program:
recording 9,241,049> reverse-finish 0x00007f5b70bf191c in __GI_abort () at abort.c:79 79 raise (SIGABRT); 99% 9,241,043> reverse-finish ... 92 abort (); 99% 9,241,040> reverse-finish ... 101 __assert_fail_base (_("%s%s%s:%u: %s%sAssertion `%s' failed.\n%n"), 99% 9,240,636> reverse-finish 0x00005601508016ee in threadfn1 () at race.cpp:47 47 assert(g_value == old_value + a);
This brings us to where our program aborted, but doesn’t tell us why. We know that when this line executes the value of
g_value won’t be equal to
old_value + a so we want to find out what other part of the program altered the value. At this point, we can start to see that it’s a race condition. The few lines leading up to the assert should see
a be added to
g_value but by the time we hit the assert this isn’t the case, so another thread must have changed
g_value at the same time. So, it must be a race condition.
int a = random_int(5); g_value += a; assert(g_value == old_value + a);
We find this out by putting a watchpoint on
g_value:
99% 9,240,591> watch g_value
Now we’re paused at the point before the program aborted and we know that the cause of the problem is
g_value. Remember the approach before - wading through the code to find references to
g_value. Contrast this with what we do next which is to run the program in reverse (automatically, not manually) watching for where
g_value is changed:
99% 9,240,591> reverse-continue Continuing. Thread 2 hit Hardware watchpoint 1: g_value Old value = 756669 New value = 756668 0x00005601508016bc in threadfn1 () at race.cpp:46 46 g_value += a;
UDB pauses the program, but looking at the context shows that this is just the line before in the same thread so isn’t that interesting:
99% 9,240,591> list 41 std::cout << __FUNCTION__ << ": i=" << i << "\n"; 42 } 43 /* Increment . Should be safe because we own g_mutex. */ 44 int old_value = g_value; 45 int a = random_int(5); 46 g_value += a; 47 assert(g_value == old_value + a); 48 49 (void)old_value; 50 }
...so we type
reverse-continue again:
99% 9,240,591> reverse-continue Continuing. [Switching to Thread 218.231] Thread 4 hit Hardware watchpoint 1: g_value Old value = 756668 New value = 756667 0x000056015080179e in threadfn2 () at race.cpp:62 62 g_value += 1; /* Unsafe. */
Now, the "Unsafe" comment isn't going to be in a real system but you get the idea. We have arrived at the line which is causing the race conditions:
99% 9,240,581> list 57 { 58 if (i % (100) == 0) 59 { 60 std::cout << __FUNCTION__ << ": i=" << i << "\n"; 61 } 62 g_value += 1; /* Unsafe. */ 63 usleep(10 * 1000); 64 } 65 }
And that’s it! We’ve found the offending line.
To recap, that took just 5 steps:
1. Run the program in UDB
2. The program aborted
3. We type
reverse-finish to get back into the program and discover that there are race conditions on
g_value
4. We set a watch point on
g_value and...
5.
reverse-continue until we find the offending line
Of course this is a tiny program, but the principle of time travel debugging is true for larger programs. Rather than wading through lines of code and guessing at what line is accessing what variable, we find the problem and step back until the cause is found.
To get started with time travel debugging, try UDB or read more about how time travel debugging (also called reverse debugging) dramatically reduces debugging times on hard to reproduce problems.
The code we used
#include <assert.h> #include <unistd.h> #include <iostream> #include <mutex> #include <random> #include <thread> /* * Returns a random integer in the range [0, max] */ static int random_int(int max) { static std::random_device rd; static std::mt19937 generator(rd()); static std::uniform_int_distribution<int> distribution(0, max); return distribution(generator); } static int g_value = 0; static std::mutex g_mutex; void threadfn1() { for (int i = 0;; ++i) { /* Take ownership of g_mutex for the duration of this scoped block. */ const std::lock_guard<std::mutex> lock(g_mutex); if (i % (10 * 1000) == 0) { std::cout << __FUNCTION__ << ": i=" << i << "\n"; } /* Increment <g_value>. Should be safe because we own g_mutex. */ int old_value = g_value; int a = random_int(5); g_value += a; assert(g_value == old_value + a); (void)old_value; } } void threadfn2() { for (int i = 0;; ++i) { if (i % (100) == 0) { std::cout << __FUNCTION__ << ": i=" << i << "\n"; } g_value += 1; /* Unsafe. */ usleep(10); } } int main() { std::thread t1(threadfn1); std::thread t2(threadfn1); std::thread t3(threadfn2); t1.join(); t2.join(); t3.join(); return EXIT_SUCCESS; }
Learn more about UDB's reverse debugging capabilities. | https://undo.io/resources/debugging-race-conditions-cpp/ | CC-MAIN-2022-05 | refinedweb | 2,262 | 60.04 |
Type: Posts; User: ertss
Hi, I have met a confusing problem.
For example, one square can have 5 states: labeled 1, labeled 2, labeled 3, empty, blocked.
They theoretically I could just use 3 bits to hold the information...
Thanks nuzzle, I will give the two bitset way some thoughts.
If I understood it correctly, are you saying creating a new class object which include two bitset to represent the bits?
For...
TheGreatCthulhu, thanks for helping me to explain this. Yes, i am using the "combined" form to represent
both input at once such that this could be used in the next steps of the alogorithm.
...
3 just represent the bit that could be either 1 or 0. We just don't care this bit because either choice will yield the same output result.
Sorry for the confusing part.
For example, for a boolean function, there are 4 inputs ABCD, one output K;
if for both the input patterns 1000 and 1001, the output is 1.
Then we say we 'dont care'...
Hi all,
I'm programming an algorithm which needs to operate on bits. I know C/C++ has bitset class. But it is not enough for
me. Because I also need to do the operation with x(don't care) bit...
Problem solved, thanks a lot.
I write my code like this.
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
Could you write a small example code showing me how to provide < operator for node_info?
Is that something called operator overload?
I will try to look up the book for that part.
I got it Russco,
Thanks a lot!
Hi all,
I have got a list of class type that I need to do list.sort() on.
the class type is
class node_info{
public:
node_number;
node_gain;
}
And it looks like the second sort cannot be used on list type.
If i do something like this, it doesn't work... why is that?
#include <algorithm>
#include <list>
... ...
list<int> ilist;
......
Hi all,
Could any tell me what's the difference between the two kinds of sorting function listed below?
Do they all have nlogn time complexity? It looks like the later one is in the algorithm...
Thanks a lot Philip!
u r the best.
Hi all,
I have a small piece of code that I want to do a series of function of while(cin>>temp) kind of operation.
But if i input 8 and 9 then enter an non-integer number, the program run past the...
Thanks a lot Paul, Best to you!
Hi All,
I want to write a func to generate all the permutations of L[1,2,3,4], once at a time and output it in an array...
For example, the first time the func called, it outputs a pointer to...
Thank you Eri523! That helps a lot!
But I met another problem with my code using getline(cin,temp);
I changed my code to this. The thing is, the first time in the do...while loop, everything is...
Thank you Drmmr.
But I still didn't get how to use push_back when you are dealing with a vector of class type.
For example, in my code, the class type has two private members 'price' and 'title'....
Hi all,
I built a class type 'books' which includes the title and the price of a particular book. And I want to use vectors to store all the books information I have. This code should be able to get...
OK, thanks!
I tried
getline(cin,temp)
And it worked.
How to use the getline?
I tried
string temp;
cin.getline(temp,20);
Should I include a header file to make that work?
Hi all,
When the following code is executed, we cannot input any string with white-space.
What if I actually want to input several words separated by white-spaces? How should I do that
Thanks in...
yes... GCDEF, I know what you mean. I'm now reading C++ Primer, although it seems to be a little bit hard for me...
Paul, I don't think it's because of the use of char[] or string type;
Because the same error still pointed to the constructor usage after I changed the type.
I still cannot figure out what's the problem...
I think I must have misused the default constructor... I did it following a youtube tutorial...
I attached the code from the tutorial and could you... | http://forums.codeguru.com/search.php?s=73030bfa31b934c27be2426bc9985bad&searchid=4874263 | CC-MAIN-2014-35 | refinedweb | 745 | 85.18 |
The Right to Food
of Milk and Maize
Farmers
Report of an investigative mission to Uganda
FIAN INTERNATIONAL
Willy-Brandt-Platz 5
69115 Heidelberg, German
Tel.:+49-6221-6530030
Consumer Education Trust (CONSENT)
1st floor Office D7, Ambassador House,
Kampala Road, Kampala
GPO Box 1433, Kampala - Uganda.
Tel.: +256-75-1502441
+256-772-502441
+44-7872-272246
Author:
Gertrud Falk
Editors:
Henry Richard Kimera
Rolf Künnemann
Kerstin Lanje
Armin Paasch
Photos:
Gertrud Falk
This document has been produced with the financial assistance of the European Union.
The contents of this document is the sole responsibility of the project partners and can
under no circumstances be regarded as reflecting the position of the European Union.
The Right to Food
of Milk and Maize
Farmers
Report of an investigative mission to Uganda
Table of Content
Acronyms 6
Acknowledgements 7
1. Introduction 8
1.1 Background
1.2 The Right to Adequate Food
1.3 Uganda
2. Methodology 10
3. Uganda’s Agricultural Policy 10
3.1 Structural Adjustment Programmes and the Ugandan agricultural sector
3.2 Impact of Structural Adjustment Programmes on Agriculture
3.3 The Poverty Eradication Action Plan
3.4. Farming in Uganda
3.5 Dairy
3.6 Maize
4. Uganda’s trade policy since 1996 16
4.1 Uganda’s trade relation with the European Union
4.2 Dairy sector and trade relations
4.3 Maize sector and Trade relations
5. Uganda’s negotiations on an Economic Partnership Agreement 20
5.1 Negotiations between the EU and EAC
5.2 EU position
5.3 Civil society position on EPA
6. Dairy farming in Mbarara District 22
6.1 Dairy Supply Chain
6.2 Development of Prices and Costs
6.3 Gender
6.4 Food Security
6.5 Findings in Mbarara
7. Maize farming in Bugiri District 27
7.1 Maize Supply Chain
7.2. The World Food Programme
7.3 Development of Prices and Costs
7.4 Gender
7.5 Food Security
7.6 Findings Bugiri
8. Impact of EU Agricultural and Trade Policies 32
9. Recommendations 33
References 34
Annex I: Questionnaire 36
Questionnaire for semi-structured interviews
Statistical data required (1990 – 2008)
Annex II: Persons interviewed 38
Acronyms
ACORD
Agency for Cooperation and
Research in Development
FAO
Food and Agriculture Organisation
of the United Nations
ACP
AU
BUDAC
CBO
CESCR
COMESA
CONSENT
CPA
DCL
DDA
EAC
EBA
EC
EDF
EPA
ERP
ESA
African, Caribbean, and Pacific
African Union
Bugiri District Advocacy Coalition
Community Based Organisation
United Nations’ Committee on
Economic, Social, and Cultural
Rights
Common Market for Eastern and
Southern Africa
Consumer Education Trust
Cotonou Partnership Agreement
Dairy Corporation Limited
Dairy Development Authority
East African Community
Everything But Arms
European Commission
European Development Fund
Economic Partnership Agreement
Economic Recovery Programme
Eastern and Southern Africa
FIAN
GDP
GSP
ha
ICESCR
IDA
IDP
IMF
ISFG
kg
l
LDC
MAAIF
NAADS
Food First Information and Action
Network
Gross Domestic Product
Generalised System of Preferences
hectare
International Covenant on
Economic, Social and Cultural
Rights
International Development
Association
Internally Displaced People
International Monetary Fund
Integrated Support for Farmers
Groups
kilogramme
litres
Least Developed Country
Ministry of Agriculture, Animal
Industry and Fishery
National Agricultural Advisory and
Development Service
ETO
EU
Extra Territorial Obligations
European Union
NDTPF
National Development and Trade
Policy Forum
6 The Right to Food of Milk and Maize Farmers
Acknowledgements
NEMA
NGO
PEAP
PMA
PMB
PRSP
RNF
SAP
UDC
UGS
UNDP
USD
WFP
WTO
National Environmental
Management Authority
Non-Governmental Organisation
Poverty Eradication Action Plan
Plan for Modernisation of
Agriculture
Produce Marketing Board
Poverty Reduction Strategy Paper
Regional Negotiating Forum
Structural Adjustment Program
Uganda Dairy Corporation
Uganda Shilling
United Nations Development
Program
USDollar
World Food Programme
World Trade Organisation
FIAN would like to extend its appreciation to Mr. John
Mwemba, of the Magoye Smallholder Dairy Farmers
Cooperative Zambia, and to Mrs. Caroline Adio of
Acord Uganda for taking part in the investigative
mission. Specific thanks go to Henry Richard Kimera
and the team of the Consumer Education Trust Uganda
for organising the investigative mission and giving the
mission team all the necessary support and service.
Further thanks go to Gershom Matsiko from Food Rights
Alliance Mbarara and to Mugoya Awali Ogonzaki from
Food Rights Alliance Bugiri for organising our field visits.
FIAN also thanks all interview partners for their input
and contribution, namely:
Geoffey Bakunda, George Walusimbi-Mpanga
NGO Trade Forum, Mbarara District Farmers
Association, Uganda Crane Creameries Cooperative
Union Ltd., Mbarara, Patrick Byaruhanga, Benon
Bwemgye, Eduardi Nyamahinja, Moses Rhambarara,
Community of Nyakisharara, Bubaare Sub-County,
Mbarara District, Bugiri District Farmers Association,
Paul Oteba Orisai, George Migero, Community of
Bukyansiko, Kasita parish, Nabokalu Sub-County, Bugiri
District, Millers Association Bugiri, EU Office Uganda,
Ministry of Agriculture, FAO Office Uganda. All other
interview partners and supporters
7
1. Introduction
1.1 Background
In the course of globalization, the impact of international
trade has gained overwhelming importance. To guarantee
the global flow of goods, the World Trade Organisation
(WTO) strives for reduction of import tariffs for all goods
in all member States. Developing countries demonstrated
resistance against a far reaching multilateral agreement
on tariff reduction on agricultural trade during the socalled
Doha Round under the umbrella of the WTO,
because most developing countries rely on agriculture
as a main contributor to their Gross Domestic Product
(GDP). Developing countries fear import surges from
industrial countries which have the potential to severely
damage their agricultural production. Most farmers
in developing countries cannot compete with the
subsidized and highly mechanised mode of production
in industrial countries like the US and EU.
Agriculture, however, is not only relevant for macroeconomic
policies of developing countries. It is even more
important for the food security of farmers and of the
general population. Most agricultural producers, particularly
in sub-Saharan African countries, are smallholder
farmers who produce at least partly for subsistence.
In the past, the EU granted one-sided tariff free imports
of goods from African, Caribbean, and Pacific developing
countries (ACP countries) into the EU under the Lomé
Conventions (1975-1999). As this practice is not
permitted under WTO rules of reciprocal market access
arrangements, the Cotonou Agreement, which followed
the Lomé Conventions, provided for the negotiation of
Economic Partnership Agreements (EPAs). With EPAs,
the European Union strives for mutual tariff reductions
down to zero in mostly all trade between the EU and the
ACP countries. According to the Cotonou Agreement,
all ACP countries should have negotiated EPAs with
the EU from 2000 until December 2007. However, this
period has been too short to allow for the developing
countries to finalize the negotiations. Especially among
West African countries, there is resistance against EPAs
since they see them as unfavourable for their economic
and social development. The EU took this into account by
adding the step of EPA interim agreements/Framework
EPAs which are not as detailed as comprehensive EPAs.
In November 2007, Uganda initiated a Framework EPA
as a member of the East African Community (EAC).
From a human rights perspective, free trade agreements
between industrial and developing countries are
criticized, since these agreements often lead to import
surges in the developing country- severely affecting
its industry or other economic sectors. By doing so,
smallholders or workers in the respective developing
country lose their market access or their job, and thus
their income. This may affect their enjoyment of social
and economic human rights in the sense that they may
no longer be able to buy enough food, pay school fees
for their children and/or pay for health care.
This report highlights the findings of an investigative
mission to Uganda from the 14th to the 26th of April
2008. The mission team investigated the impact of
agricultural trade policies of the EU on the right to food
of smallholder farmers in Uganda. The mission has been
part of the project “African Smallholders in focus – a voice
in EU trade policy” conducted by the non-governmental
organisations (NGOs) Germanwatch, FIAN, UK Food
Group, BothENDS, Send Foundation, Civil Society Trade
Network, and CONSENT. The Ugandan mission was the
third within the project. Similar missions were conducted
in Ghana and Zambia 1 . The mission in Uganda focussed
on the two products: milk and maize. The following
person participated in the mission: Caroline Adio
(Acord Uganda), Geraldine Galvaing (UK Food Group),
Gertrud Falk (FIAN Germany), Henry Richard Kimera
(Consent Uganda), John Mwemba (Magoye Small Holder
Dairy Farmers Cooperative Zambia), and Armin Paasch
(FIAN Germany).
1.2 The Right to Adequate Food
The human right to food is enshrined in article 11 of
the International Covenant on Economic, Social and
Cultural Rights (ICESCR) and is mentioned there as
part of the right to an adequate standard of living.
The United Nations Committee on Economic, Social
and Cultural Rights has interpreted its legal scope in its
General Comment No. 12. :
“The right to adequate food is realized when every
man, woman and child, alone or in community with
others, has physical and economic access at all times to
adequate food or means for its procurement.”
This means that food has to be available, accessible,
culturally accepted, and safe. The Committee interprets
the right to food far beyond a purely technical
understanding:
“The right to adequate food shall therefore not be
interpreted in a narrow or restrictive sense which
equates it with a minimum package of calories, proteins
and other specific nutrients. The right to adequate food
will have to be realized progressively.” [CESCR 1999,
Italics in original]
The Right to Food implies access to productive resources
and an environment, which enables people to feed
themselves in dignity. For small-scale farmers, who represent
half of the people affected by hunger globally,
access to land, water, seeds, extension services and markets
are crucial to the enjoyment of their right to food.
“The strategy should address critical issues and measures
in regard to all aspects of the food system, including
the production, processing, distribution, marketing and
consumption of safe food, as well as parallel measures
in the fields of health, education, employment and social
security.” (CESCR 1999; Italics in original)
1 See:
and
others/right-to-food-of-milk-and-honey-farmers-report-of-an-invesitagtive-missionto-zambia/pdf
8 The Right to Food of Milk and Maize Farmers
A human right implies the States’ obligations to respect,
protect, and fulfil the enjoyment of this right. Human
rights and States’ obligations are two sides of the same
coin. Failure to comply with these obligations is called
a violation of human rights. The obligation to respect
the enjoyment means that States should not undermine
the enjoyment of the respective human right. The
obligation to protect means that they should prevent
destruction of the enjoyment of the respective human
right by third parties like companies or foreign States.
The obligation to fulfil enjoyment of a human right of
a person or group who lacks enjoyment of the right in
question means that States should take measures to the
full extent of their available resources, and as expeditiously
as possible, in order to establish the enjoyment
for this person or group.
Although states are responsible for guaranteeing human
rights to the people in their territories, human rights
are not a domestic issue alone. States also have human
rights obligations to persons outside their territories
– extraterritorial obligations (ETOs). International
assistance and cooperation are important tools to
implement these ETOs. The ICESCR, for example, obliges
countries to realize human rights through international
assistance and cooperation. Article 2.1 reads:
.”
Regarding the right to food, states are obliged to assist
each other in a number of ways, for example in times
of famine or in other emergencies which might lead to
national food shortages. Extraterritorial obligations to
respect the enjoyment of the right to food are relevant in
the context of trade agreements as they imply that states
must not harm the right to food of people through their
trade policies. Governments have to ensure that their
trade policies do not have negative effects on the right
to food of vulnerable people living in other countries.
In his report to the Human Rights Council in February
2009, Olivier De Schutter, the United Nations Special
Rapporteur on the Right to Food, explicitly referred to
international trade in agriculture as a cause of hunger
for poor farmers. In the instance that international trade
agreements do not respect the human right to food, he
states: “Trading more food will not help them if they are
excluded from production and have no means to buy
the food which arrives on the markets.” Countries must
make sure that farmers are not pushed out of markets,
nor that they lose their income and face hunger.
Furthermore, international and bilateral trade
agreements should not hinder developing countries’
obligation to respect, protect and fulfil the right of
food of its inhabitants. “States have to ensure that the
right to food is adequately considered in international
agreements.” (FIAN International 2003). Jean Ziegler,
former UN Special Rapporteur on the Right to Adequate
Food, insisted that: “States should also refrain at all
times from policies of which the effects can be foreseen
or that they are aware will have negative effects on
the right to food.” (Ziegler 2005) This is also valid for
agricultural trade policies of the EU and EPAs.
1.3 Uganda
Uganda is a landlocked country in Eastern Africa and is
classified by the United Nations Development Program
(UNDP) as a least developed country (LDC). The grade of
urbanisation is low: only 12 percent of the population
lives in urban areas. The income of 80 percent of the
Ugandans depends on agriculture. Approximately 80
percent of the supplied food is produced by small-scale
farmers who cultivate between one and two acres of
land per household. Primary traditional export crops are
coffee, tea, and cotton. Primary non-traditional export
crops are cereals, fish, cut flowers, fruits and vegetables.
While the total food production has continiously
increased since 1999, the per capita production has
decreased due to population growth and shortage of
arable land per capita. An estimated 40 percent of
the population are food insecure and live in absolute
poverty (Kintu 2007, Bertow/Schultheis 2007, Werth et
al. 2005).
After its independence was declared in 1962, the country
suffered from several internal wars and dictatorships. The
current President ,Yoweri Museveni, came to power in
1986 through a military coup but converted the political
system into a multi-party democracy. However, there are
complaints from the opposition parties and from civil
society organisations that democratic procedures are
not always followed.
Uganda ratified the International Covenant on Economic,
Social and Cultural Rights in 1986 and is therefore
obliged to respect, protect and fulfil the right to food
of its population. The Right to Food was enshrined
into the National Food and Nutrition Policy in 2003.
However, the percentage of the population which is
undernourished has remained at 19 percent since 2002.
More than 38 percent of the children aged 6-59 month
have experienced stunted growth, which indicates
chronic malnutrition (Rukundo 2008, FAO interview).
The most vulnerable groups are internally displaced
people, female-headed households, HIV/AIDS affected,
disabled, pastoralists in Karamoja and the urban poor.
At the same time, Uganda has very high soil fertility,
a favourable climate for agriculture, and produces 95
percent of its food within the country, mainly at the
hands of small-scale farmers (FAO interview).
The government has established mechanisms to
implement food security, but it lacks funds to put those
mechanisms into practice. In 2001, the government
started a pilot project in 16 districts. In a first step,
advisory services were provided. Currently, these advisory
services have extended to all 79 districts. In a second
step, ISFG programmes (Integrated Support for Farmers
9
Groups) were started. These programmes give grants
to sub-counties to establish farmer managed credit
schemes for procurement of technologies and inputs.
These programmes have extended to 20 districts. But
the funds are limited. The Government spends only 4
percent of its budget on the agricultural sector. Higher
priorities are human security in the north, peace, energy,
education, and health. The budget for agriculture
is mainly financed by donors. The overall budget has
decreased because of limited contribution from the
government 2 .
Uganda is member of the African Union (AU), the
East African Community (EAC), Common Market for
Eastern and Southern Africa (COMESA) and the World
Trade Organisation (WTO). Under the WTO regulations,
Uganda is treated as a Least Developed Country (LDC)
and granted Most-Favoured-Nation status by all trading
partner countries (RATES 2007). Uganda is also eligible
to benefit from the Everything but Arms (EBA) initiative
of the EU.
2. Methodology
The investigative mission to Uganda was conducted
under a rights-based approach focussing on the human
right to adequate food which is enshrined in article 11
of the International Covenant on Economic, Social and
Cultural Rights (see Chapter 1.2).
The dairy and maize sectors were chosen for four
reasons:
a. maize and milk are both produced in Uganda and
imported from the EU;
b. both are relevant sectors for rural development, food
security, contribution to employment and income
(thus also for livelihood sustainability) (DENIVA
2006);
c.
both are produced by small-scale farmers;
d. for both sectors, necessary data is available.
The following are underlying questions of the mission:
• Have trade policy measures such as dumping or
market deregulation significantly contributed to
sharp increases of imports of dairy products and
maize from EU countries into Uganda?
• Did or do these imports have a negative impact on
the incomes of the families of small-scale farmers to
such a degree that their access to food is destroyed
or limited?
• Has the state of Uganda breached its legal obligation
to respect, protect and fulfil the human right to
adequate food of the peasant families as the result
of its trade and agricultural policies?
2 European donors add a maximum of 50% as development aid to sector
budget. Hence, if a govnement of a developing country reduces a sector budget
those donors reduce their development aid for the respective sector.
• Have EU member states breached their extraterritorial
obligations to respect and protect the right to food of
these communities through unfair dumping practices,
or through pressuring Uganda to reduce support to
the farmers or to open up its domestic markets to
imports?
• Will the EPA (interim agreement) lead to increased
imports of dairy products and maize under unfair
conditions, negatively affecting the right to food of
peasant families?
To answer the questions raised, the research team has
applied a fivefold approach:
• Research studies were used to get relevant background
information.
• Focus group discussions, gender-mixed and genderseperated,
were held to get the experience and
opinions of members of networks, associations and
farmer communities.
• Individual interviews were conducted to verify general
findings in individual cases.
• Expert interviews were held to get deeper insights
in issues and to cross-check information from focus
groups and individual interviews.
• Observations on site helped to complement the
information given during the discussions and
interviews.
A questionaire with guiding questions was used to
structure focus group discussions and interviews (see
Annex I).
The researchers were a mixed gender team (three women,
three men) comprising two people from Uganda, one
from Zambia, two from Germany and one from the UK.
Five team members were NGO representatives, one was
a farmer.
The investigative mission was organised and conducted
in cooperation with local partner organisations. Based
on terms of reference, the local partners gave advice on
the identification of the two crops, the two regions and
the two villages chosen for the mission.
3. Uganda’s Agricultural Policy
Agriculture is the main economic sector in Uganda. It
accounts for 38.5 percent of the GDP, 69 percent of
employment and 48 percent of export earnings (Werth
et al. 2005). The majority of the output is produced by
smallholder farmers who produce with little technical
support. 71 percent of the value of agricultural production
is provided by food crops, 5 percent by export crops, 4
percent by fisheries and 3 percent by forestry, and 17
percent by livestock (Werth et al. 2005).
Due to fertile soils and a favourable climate, with temperatures
between 15 and 30°C and annual rainfalls of
750-2000 mm, Uganda’s farmers produce a wide range
of cash and food crops and livestock. Primary traditional
10 The Right to Food of Milk and Maize Farmers
cash crops are coffee, cotton, tea and tobacco. Nontraditional
cash and food crops are root crops, grains,
legumes, oilseeds, fruits, vegetables, spices and flowers.
Livestock production comprises cattle, goats, sheep,
poultry and pigs. The most important agricultural export
crop is coffee accounting for almost 20 percent of the
total foreign export earnings, followed by cotton, tea
and tobacco. The EU is the main export market of Uganda’s
agricultural sector and accounts for 33 percent of
exports followed by COMESA with 27 percent (Werth
et al. 2005).
Maize ranks the second most produced crop in terms of
planted area. In 2002, 676,000 ha were planted with
maize. With a production of 1,217 thousands tons in
2002, it is the most produced cereal in Uganda. 10,609
USD of maize was exported in 2002, while a value of
5,938,335 USD has been imported into Uganda. The
crop ranks second in terms of imports in value from
the EU. But its revenue contribution for Uganda is low.
From 1999 until 2004 the revenue authority received
only 457,991 USD in tax from maize production out
of export revenue of 573,750,436 USD from 25 top
products (Werth et al. 2005).
In 2003, dairy farmers produced 1,100 million litres (l)
of milk. From this quantity, 70 percent (770 mio. l) are
marketed, while 30 percent (330 mio. l) are retained for
domestic consumption. Out of the 770 mio. l of milk
marketed, only 154 mio. were processed and 616 mio.
were sold unprocessed through the informal market.
From 2000 to 2003, the sales of milk have increased
from 700 mio. l to 1,100 mio. Post-harvest losses along
the market chain total 25 percent per year which led
to an average loss of value of 23,000 USD in the years
2000-2003 (DDA 2004).
3.1 Structural Adjustment Programmes and
the Ugandan agricultural sector
The first structural adjustment program (SAP) with
a long-term impact on the agricultural sector was
implemented in Uganda from 1987 to 1995 under the
Economic Recovery Programme (ERP). At that time, the
Ugandan population and economy had been severely
harmed by several wars and dictatorships. “Production
was low, the transport system was in disarray, the social
infrastructure had collapsed, inflation was over 150 per
cent, foreign exchange was limited, the budget was out
of control, corruption and black marketeering was wide
spread, and skilled personnel had migrated.” (Baffoe,
2000) Through the ERP, the Government tried to create
a stable macroeconomic environment.
The ERP followed conditions of the International Monetary
Fund (IMF) and the World Bank to stabilize monetary
and fiscal policies, to deregulate the Ugandan economy
and to fight poverty. It prioritised public spending
into rural infrastructure, primary education, primary
health, and agricultural reseach and extension (SEATI-
NI, 2005a). Between 1991 and 1993, trade-liberalizing
policies were introduced into the agricultural sector to
increase production. Parastatal marketing and extension
services were abolished. Input and output prices were
adapted to the world market through deregulation of
the exchange rate and drastic reduction of subsidies.
Measures were taken to rehabilitate the infrastructure,
which had been destroyed during the wars.
Positive effects of the ERP were a decline of inflation
from 200 to 7 percent between 1987 and 1996, an
increased Gross Domestic Product (GDP) by an average
of 6.5 percent, as well as an increased agricultural
output by an average of 5.1 percent especially in food
crop production. Public investment increased by a
remarkable 30 percent and private investment increased
more than100 times its original amount between 1987
and 1994. Export revenues increased from 406 million
USD to 555 million USD with a decrease in 1993 to only
169 USD due to falling world market prices on coffee –
the main export crop.
On the other hand, the increase of imports and external
debts led to an increasing trade deficit ranging from
194 million USD in 1987 to 625 million USD in 1996.
While 39 percent of the households were defined as
absolutely poor by a household survey in 1989/90, this
percentage raised slightly to 40 percent in 1992/93.
Inequality measured by the GINI Coefficient rose in this
period from 0.38 to 0.41, with the strongest increase in
urban areas (Baffoe, 2000).
3.2 Impact of Structural Adjustment
Programmes on Agriculture
Before the ERP, the parastatal Produce Marketing
Board (PMB) controlled marketing of agricultural food
crops and their pricing. The PMB also had to sell those
commodities to deficit areas within Uganda to guarantee
food security. Only surpluses were exported (Bakunda
2006). But due to late or non-adequate payment by
cooperatives some farmers also sold their harvest outside
the formal channels. The Government of Uganda, on the
other hand, subsidised agricultural inputs. Nevertheless,
there was a need to modernize production techniques
and to improve extension services.
Through the ERP, the Government addressed those
shortcomings by setting up the Agricultural Sector
Policy Agenda in 1991. The programme was financed
by the International Development Association (IDA) and
implemented by the Agricultural Policy Committee. It
had six major objectives:
• intensifying agricultural production and processing
• increasing agricultural producer prices
• restructuring the finance of production cooperatives
• deregulating agricultural trade
• reorganizing agricultural marketing institutions
• improving agricultural research and extension
services.
11
During the implementation phase of the agenda, all
markets for food crops were deregulated and farmers’
cooperatives were dissolved. As a result, private traders
entered into rural markets. Prices went up. The price for
maize increased from 48 UGS per kg in 1992 to 126
UGS (0,12 USD) per kg in 1997.
According to the Ministry of Agriculture, the Government
of Uganda destroyed the cooperatives by raising
awareness of farmers that they were being exploited by
the cooperatives. Cooperatives were poorly managed
and the managers tried to profit from their positions.
In the dairy sector, the dairy corporation plant and milk
collection centres were reinstalled and the sector opened
to private entrepreneurs. Veterinary services were
privatised under a Livestock Services Project to improve
delivery of their services to small livestock farmers. In
the initial step, milk collection and processing increased
from 50,000 l in 1990 to 1.2 million l in 1995. This
increase occurred mainly due to acreage expansion and
increased number of cattle rather than as the result of
increased productivity. However, nothing was done to
reform land rights to ensure that farmers had access to
land, nor to introduce adequate technologies to increase
productivity. Price increases of many agricultural inputs
made them unaffordable for most farmers. To make it
worse, the deregulation of markets led to significant
increases in consumer prices, which negatively affected
the marketing of dairy products. These developments
reduced the net-income of farmers and their families.
Bakunda summarizes that, “liberalisation has contributed
to the deepening of rural poverty” (Bakunda 2006).
3.3 The Poverty Eradication Action Plan
The ERP was followed by the Poverty Eradication
Action Plan (PEAP) 1996, which is the Ugandan version
of a Poverty Reduction Strategy Paper (PRSP). It was
developed as a response to a debt relief requirement of
the World Bank and IMF. Within the PEAP-framework,
the Plan for Modernisation of Agriculture (PMA) was
developed as the strategy on the agricultural sector. The
objective on poverty reduction outlined in the PEAP is
to reduce the percentage of poor people among the
population to less than 10 percent by the year 2017.
Trade policies are not prioritised under PEAP policies
(SEATINI 2005a). Only some sector strategies like the
PMA contained trade-related aspects.
The PMA strives for commercialisation of agrarian
production. In this context, the extension service
for farmers was privatized and became the National
Agricultural Advisory and Development Service
(NAADS). NAADS was founded in 2001 under
Ugandan government legislation. It was created to
empower farmers to demand services for payment.
The Government of Uganda had planned to set up a
procurement committee in each sub-county. But donors,
who refused to provide the necessary money, opposed
this. Now the district boards perform the procurement
without having adequate knowledge (focus group civil
society). At the same time, when NAADS started its
work, production started to decrease. Today only 14
percent of the farmers use fertilizers. Farmers can hardly
afford veterinary services any more (focus group civil
society). According to Bakunda, the PEAP and the PMA
have not been realized since most of the processing
industries are imported.
Still today, the World Bank and IMF strongly influence
Ugandan policies. Since the state is heavily indebted,
both organisations have a say in national policies (focus
group civil society).
3.4. Farming in Uganda
Nowadays Ugandans do not have a positive impression
of farming. There is a Ugandan proverb that says: “It
is better to be an American cow than to be an African
farmer.” The youth, in particular, do not see a future in
farm life. Many of the rural young migrate to urban areas.
The word “farmer” is even used as a threat to children:
“If you do not go to school you will end up as a farmer!”
This expresses that most of the farmers are illiterate or
not well educated even though agriculture is the backbone
of the country (focus group civil society). Farmers
in remote areas like West Nile, especially, lack sufficient
knowledge on farming. Many of them do not produce
enough food to feed their families (focus group civil society).
Most small-scale farmers do not view farming as a
business, but as a way of life. Furthermore, they have the
feeling of being ripped off by the private sector.
The Government of Uganda spends only 4 percent of
its budget in agriculture. Thus, it does not fulfil the
Maputo protocol of the African Union in which States
have pledged to spend a minimum of 10 percent of
their budget on agriculture. The major part of Uganda’s
budget is spent on roads, education, public sector
management, healthcare and on the armed conflict in
the northern region (Rukundo 2009).
Farmers can receive price information on commodities
by text message pm mobile phones, but since they do
not have bargaining power they often sell at lower prices
(focus group civil society). Since the co-operatives have
been destroyed, there is hardly any solidarity or trust
among farmers. They hesitate to market collectively.
As many of them have bad experiences with the
Government in the previous co-operatives, they have
become very suspicious (focus group civil society).
Small-scale farmers face a dual disadvantage. Developed
markets do not favour them, thus they deal with
middlemen who also do not favour them (Expert EU).
One of the major problems is the poor quality of production
inputs. While initially all seeds were produced
in Uganda, they are increasingly imported from foreign
countries like from India (focus group civil society).
Furthermore, the deregulated market does not reward
good quality. The Ministry of Agriculture recognizes the
responsibility of the government to enact laws that address
this issue. The government should improve monitoring
mechanisms and install systems to trace the origin
of inputs. According to the FAO, the Government of
12 The Right to Food of Milk and Maize Farmers
Uganda has addressed this problem by supporting the
National Agricultural Research Organisation (NARO) to
improve the quality and diversity of seeds and livestock.
Another constraint is extension services. In the past,
extension services have been financed and implemented
by the government. While the Ministry of Agriculture
praised the high quality of the service in the past
(since all staff members at least held a diploma), the
FAO criticized a lack of efficiency. In 2003, NAADS was
introduced. NAADS is financed by public funds but
services are delivered by the private sector. Farmers
form groups at the community level and select three
key enterprises (crops). These steps are repeated at the
parish and then at the sub-county level. The government
provides the necessary money to hire services from
the private extension sector and channels the services
through the district and sub-county authorities to
the community. If the service is bad, the farmers can
cancel the agreement. The government’s intention in
introducing this system was to create a demand and
to place a value on extension services. The FAO views
NAADS as a better alternative than the previous system,
but also still sees it as a constraint.
According to civil society, farmers are not aware of EPAs.
The Commissioner for Crop Production and Marketing
of the Ministry of Agriculture was also not aware of
the content of the EPA framework at the time of the
interview during the investigative mission.
From a gender perspective, it is important to note that
the majority of Ugandan women do not own land even
though they perform the primary agricultural work
(focus group civil society). Traditionally, women do not
inherit land and there is nothing that contradicts this
in national law. Thus, only rich women can manage to
own land by purchasing it outright.
Before deregulation, the parastatal Uganda Dairy
Corporation (UDC) operated under near monopsony
conditions as it was the only institution in the formal
market which bought milk from farmers’ cooperatives
and which supplied milk to the formal market. The
cooperatives could bargain the selling price and
since there were hardly any competitors, UDC could
agree on a price that also benefited the farmers.
Generators for cooling the milk were subsidized by the
Government. When subsidies were removed, farmers
and their cooperatives could not cover the costs and
the infrastructure collapsed. As another consequence of
liberalisation, the prices for imports of inputs like drugs
for treatment of cows rose tremendously, some even
doubled. Veterinary services were privatized and the
government stopped offering extension services free of
charge. Trainings were offered by NGOs or CBOs only,
and they did not operate in all regions.
3.5 Dairy
Milk has always been both a food crop and a cash crop
in Uganda. In 1992, the parastatal Uganda Dairy Cooperative
was privatized and transformed into the company
Dairy Corporation Limited (DCL). At this time, the
first major private companies entered the dairy sector,
which was completely liberalized in the mid nineties.
According to a study based on data from the 2002/03
Uganda National Household Survey, the average number
of cows per dairy farm was 19 and they produced 113 l
of milk per day, of which 78 l were sold. This means that
each cow produced an average of 6 l per day of which 4
were sold. Most of the farms (82 percent) were located
in rural areas and the majority of the farmers sold to
local markets. Large-scale farmers with more than 50
cows received higher prices per litre than small-scale or
medium-scale dairy farmers. They could sell a litre for up
to 900 UGS (0,52 USD) while the average price was 316
UGS (0,18 USD) (Mwebaze 2004). Since the majority
of cows were grass fed, production of milk fluctuated
between wet and dry seasons. Production during wet
season was much higher than during the dry season.
In the course of deregulation, dairy companies were
allowed to purchase milk from individual farmers, not
just from farmers’ cooperatives. This was attractive for
farmers since they received only vouchers from UDC
and had to wait for payment. The opportunity for
farmers, as individuals, to sell milk led to a collapse of
the cooperative system. But the emerging companies
did not invest in collecting and cooling infrastructure.
Consequently, there is no guarantee that the farmers
will be able to sell their entire production of milk, nor is
there a guarantee that they will be paid at the market
price for their milk. “The collapse of the cooperatives
meant that the voice of farmers has been removed from
the marketing system.” (Bakunda 2006) Furthermore,
the quality control systems broke down which led to a
deterioration of the quality of milk.
As a response to the lack of quality, the Dairy Industry
Act was enacted in1998, and in 2000 the Dairy
Development Authority (DDA) was established to
regulate the sector. But even today, the DDA hardly
possesses any infrastructure outside Kampala.
13
In response to the signals of market deregulation, dairy
farmers either successfully changed their herds from indigenous
to exotic breeds or cross-bred to get higher
yields. Between 1992 and 2004, milk production almost
tripled from 511 million to 1,450 million l. This positive
development was undermined by a lack of corresponding
expansion of the processing and marketing
sub-sectors. Especially during wet seasons, dairy supply
was much higher than demand. In Mbarara, this gap led
to the closure of most of the milk processing factories
(Bakunda 2006).
The deregulation of the milk sector also led to a decline
of milk the farm gate price 3 . Milk buyers did not consider
the production costs of farmers as the UDC did.
While in 1995 the farm gate price for one litre of raw
milk was 200 UGS (0,20 USD), in 2004 farmers received
only 200 UGS (0,11 USD) due to inflation. Farmers can
hardly cover their production costs by this price. At the
same time, consumer prices for pasteurized milk went
up from 600 UGS (0,60 USD) per litre in 1995 to 1,200
UGS (0,64 USD) per litre in 2004. Thus, dairy farmers
were at a double disadvantage resulting from deregulation.
They lost the guarantee to sell all their milk and
they received lower prices. In reaction to falling prices at
farm gate, new dairy cooperatives emerged from 2004
onwards (Bakunda 2006). On August 1 st , 2006, UDC
was taken over by Sameer Ltd. Since this takeover, the
farmers’ cooperatives generally sell to Sameer.
During the wet season, when raw milk is abundant,
farmers sometimes throw the milk out since they cannot
sell all the milk which they produce, not even on the
informal market. Experts estimate that a daily average
of 100,000 l of milk is wasted because of inadequate
cooling and processing capacities (Interview Bakunda).
Recently, local micro markets and informal markets have
gained more importance. Experts estimate that 80 percent
of the milk produced is sold through these channels
(Bakunda 2006). However, this milk is not processed,
which can pose health risks for the consumers (Interview
Bakunda). While the informal sector helps the farmers
sell their products, cooperatives complain that low
prices on the informal market undermine prices on the
formal market. Firstly, to maximise profits, many traders
mix milk with water before they sell it to the consumer.
Secondly, cooling, storing and packing systems in the
informal market are poor. Since milk is a highly perishable
good, it often perishes before the consumer reaches
home. Thirdly, during the wet season, when milk is
abundant and the price is low, informal traders often
sell at an even lower than average price. These trading
practices have led to the collapse of some processing
plants and discourage potential formal investors.
The Ministry of Agriculture sees a big potential in dairy
farming to contribute to the alleviation of poverty,
since dairy is not a seasonal business. According to the
Commissioner for Crop Production and Marketing, the
national market is more promising compared to the
external market. The Commissioner is not aware that
imports may harm the development of the internal
market. Neither does he see any way to prevent
potential impacts due to Uganda being bound by
international law under the WTO. But he is aware of
the government’s responsibility to develop the dairy
sector. The commissioner believes that the sector
should develop cattle breeds that can best adapt to
the Ugandan environment. Furthermore, it should train
farmers, support proper transport facilities, processing
and marketing. At the same time, he states that he is
unable to facilitate this due to the general policy of the
government to fully liberalize the Ugandan economy.
In the big supermarkets in Kampala, milk products from
various processing companies and various countries are
sold. Fresh and UHT milk from Ugandan and Kenyan
companies are offered. Among the suppliers of milk
powder, Nestlé possesses the biggest share with its
product “Nido”, followed by Pearl from New Zealand
and Hassani Baby Food and Milk Powder, with its
product “Safa”, from the United Arabic Emirates. The
Ugandan branch of the Kenyan-based dairy Company
Sameer, started milk powder production only in May
2008 4 . Its product is offered in big supermarkets for
a slightly cheaper price than its competitors Quoted
prices at Shoprite from January 5 th , 2009: Nido: 10,000
UGS/500g (6 USD/500g); Safa: 8,000 UGS/500g (4.80
USD/500g); Sameer: 7500 UGS/500g (4.50 USD/500g)).
Cheese is produced by the dairy company Paramount and
imported from EU countries. Milk, in general, is hardly
processed and exported. When it is, export countries are
the neighbouring countries of Kenya, Sudan, Rwanda,
Burundi and Congo.
Milk consumption in Uganda per capita is 50 l per year,
which is relatively low. But the demand for milk powder
and fresh milk has increased since 2006. The local
dairy companies cannot always supply the demand,,
especially not during peak seasons like the beginning of
school terms. Imports are necessary to fulfil the demand
and discourage local companies to invest in processing
plants and milk collecting centres. The prices of dairy
products have increased, while they have increased more
slowly for fresh milk slower than for other milk products.
Unlike at farm gate, there is hardly any seasonal price
fluctuation for the supermarkets.
3 The farm gate value of a cultivated product in agriculture).
The farm gate value is typically lower than the retail price consumers pay in a store
as it does not include costs for shipping, handling, storage, marketing, and profit
margins of the involved companies. ()
4 NewVision, 6th May 2008
14 The Right to Food of Milk and Maize Farmers
3.6 Maize
Traditionally, maize has not been a staple food in Uganda.
It was typically seen as a food that serves institutions –
like boarding schools, orphanages or prisons - and as
an export to Kenya and Tanzania. This tradition has
changed, but maize is still mainly a commercial crop. In
the early 1980s, the Government of Uganda identified
maize as one of five non-traditional agricultural export
crops for promotion. The government offered Export
Guarantee Schemes to promote export, which were
supported by the Bank of Uganda and USAID (RATES
2003). The Produce Marketing Board (PMB), established
as a state-trading enterprise in 1968, procured, stored,
graded and marketed the commodities. All maize was
sold to the PMB 5 . Furthermore, the PMB sold maize to
areas in Uganda suffering from food shortages in order
to guarantee food security. Procurement prices were
discussed with the farmers and fixed for one season.
Only after serving the national markets and needs was
the surplus was exported. Nevertheless, among the
main shortcomings of the PMB was an inability to reach
rural farmers and lack of prompt payment to farmers
(Bakunda 2006).
In the framework of the ERP, the Ugandan Government
started to deregulate the maize sector in the early
1990s. This policy was aimed at increasing efficiency
and at restoring price incentives. The PMB was
privatised in 1993 through the Public Enterprise
Diversification Program (PEDP), which was set-up under
the Privatisation Unit of the Ministry of Finance. After its
dissolution, many companies have stepped into trade.
The market was opened to any person or company who
wanted to step in. As a consequence, the number of
traders increased drastically. The increased demand has
impacted traditional food consumption patterns in that
nowadays more people eat maize as a staple food.
5 This has not been confirmed by farmers in Bugiri. See chapter 8
Since the trade sector has been under-capitalized and
faces shortage of liquidity, small-scale traders mainly appeared
on the market scene who did not invest in infrastructure
and storing facilities. Those small traders offer
low prices and cannot purchase all available quantities
for sale. Furthermore, post-harvest losses are high and
reach approximately 20 percent (Bakunda 2006).
At the same time Government did not set any
standard regarding maize grading and classification.
Consequently, the quality of maize declined. This is an
obstacle to the export opportunities for Uganda’s maize
and for approaching the largest buyer in the region: the
World Food Programme (WFP). The WFP has certain
procurement criteria on quantities and quality. Although
WFP’s procurement of Ugandan maize has increased
from 20,000 metric tons in 1995 to approximately
60,000 metric tons in 2003, small-scale farmers have
not benefited due to low quantities and poor quality of
their own production (Bakunda 2006).
The maize sector was totally deregulated in the midnineties.
The area planted with maize increased between
1999 and 2004 from 608 thousand hectares to
750 thousand hectares and production increased from
1,053 metric tonnes (t) to 1,330 metric tonnes (2004
figures estimated, Werth et al. 2005). This increase
was possible due to an expansion of land sizes of farmers
and the use of improved technologies, mainly ox
ploughing. But the market for the increased quantities
had not been developed.
Maize provides an income or contributes to food security
for approximately 2.5 – 3.0 million Ugandan households.
The crop is predominantly grown by small-scale
farmers who cultivate 0.2 – 0.8 ha and medium-scale
farmers who cultivate 0.8 – 2.0 ha. Maize production
in Uganda is generally characterized by low yields
(Bakunda 2006).
The price for maize at farm gate has been declining
since the mid 1990s, while price volatility has increased.
Farmers could sell one kg of maize for 300 – 350 UGS
(0,30 – 0,35 USD) in 1995, and currently they receive
only 80 – 100 UGS (0,04 – 0,06 USD). At the same time,
costs for inputs, labour and livelihood have increased.
While in the past farmers paid a worker 1,000 UGS
per day, today the worker receives between 1,500 and
2,500 UGS per day. The costs for maintenance of ox
ploughs have increased from approximately 80,000 UGS
(52 USD) in 2000 to 200,000 UGS (114 USD) in 2005.
However, while farmers complain about low farm gate
prices they appreciate that they are paid cash directly
since the abolition of the PMB.
Despite declining farm gate prices, the consumer price
for maize flour has continuously increased. In the year
2008, one kg of maize flour was sold for 1,000 UGS
(0,60 USD), while the milling and transport costs remained
relatively low at 100 UGS/kg (0,06 USD/kg) and
50 UGS/kg (0,03 USD/kg), respectively. Thus it is obvious
that the traders are benefiting at the expense of the
farmers. Farmers need to sell all of their maize produc-
15
tion to gain money for basic goods like salt and soap.
They cannot wait for the off-season to get a higher price.
One NGO representative who tried to organise farmers
to bargain collectively has received threats by traders
and claims that she may unorganise farmers since they
refuse to sell. NGOs are convinced that there is political
power behind the maize traders, and that this power is
determining prices (focus group civil society).
A positive impact of deregulation of the maize sector
can be seen in the appearance of mills, which add value
to the crop by processing maize flour. Due to the large
number of mills, competition has reduced the milling
costs for farmers. This development not only diversified
farmers’ markets but also their diets. Before opening up
the market, farmers could eat only maize cobs, but now
can eat more maize-based products (Bakunda 2006).
Agrofuels
Maize is not yet exported for production of agrofuels.
However, according to the Ministry of Agriculture, an
Indian investor has already announced interest to grow
maize for agrofuel production in Uganda. The Ministry of
Agriculture and civil society organisations fear that farmers
will sell all maize and will not have food if the agrofuels
boom reaches Uganda. This happened when vanilla
production was introduced as a cash crop in Uganda a
few years ago. But the Ministry does not see any way
to stop investors from carrying out their plans. The only
solution the Ministry strives for is to increase production.
Civil society organisations refer to the example of a palm
oil plantation at Sese Islands when they complain about
the lack of transparent information on agrofuel projects.
This project has been promoted by the Government, which
states that a) the palm oil is meant for cooking oil (instead
of agrofuels) and b) that due to palm oil production, every
Ugandan will become rich (focus group civil society).
In the course of liberalisation, Uganda has stopped storing
grain in centralized silos of the PMB, which previously
served the needs of Ugandans in times of food
insecurity. The silos, constructed in Jinja in 1990 with aid
from the Danish Development Agency, lost their function
as a national food security institution due to privatisation
policies of the PEAP “as a condition of multinational
finance institutions – the World Bank and IMF”
(Rukundo 2009). Today, they are leased to private companies.
Instead, the Government now promotes storing
food households. The export ban has been lifted and
Uganda sells maize to neighbouring countries. However,
due to lack of quality standards maize is exported mostly
through informal channels (Bakunda 2006).
4. Uganda’s trade policy since 1996
Uganda has been a member of COMESA since its
foundation in 1994. In compliance with WTO rules,
COMESA members strive for preferential treatment in
the form of duty reductions on imports to each other on
a reciprocal basis.
Uganda became a member of the WTO in 1995. The
Ugandan Government has adopted the policy of
deregulation in all sectors, including agriculture. The
Government implemented the WTO Agreement on
Agriculture (AoA) and the Agreement on Customs
Valuation – using transaction value as the first method
for assessing taxes on importers. The current bound
tariff 6 for Uganda under the WTO for milk products
(tariff lines 401 to 406) and for maize (tariff lines under
1005) is 80 percent. On the applied level, parastatal
marketing institutions and so-called trade barriers have
been abolished or reduced one by one. In 1998, the
Government reduced tariff bands to two (0.7% and
15%) and lifted almost all import bans.
An important step took place in 2005: the East African
Community Customs Union entered into force. Within
the Union, Uganda adopted the common external tariff
(CET) system with two bands: 0.10 percent on raw material
and capital goods and 25 percent on intermediate
goods and finished products (DENIVA 2006). The applied
tariffs for most milk products are 25 percent. According
to the WTO, two tariffs are applied to maize: 25 percent
for tariff line 100510 (maize seed) and 50 percent
for tariff line 100590 (all maize except seed corn) (WTO
Consolidated Tariff Schedules Data Base).
Currently, Uganda has the lowest tariffs in Africa and the
lowest among LDCs. The average tariff for agricultural
crops is 11 percent. From 2010 onwards, trade within
the EAC will be tariff free (Interview Bakunda).
6 Bound tariff is the maximum rate of tariff allowed by the WTO to any member
state for imports from other member states.
16 The Right to Food of Milk and Maize Farmers
4.1 Uganda’s trade relation with the
European Union
The European Union (EU) is a major export market
for Ugandan products. It accounts for 47 percent of
all exported goods. Main destinations are the United
Kingdom, Germany and the Netherlands (DENIVA 2006).
At the same time, the EU also exports many goods to
Uganda. Between 2000 und 2004, Uganda imported
from the EU maize (corn) totalling a value of 11,748,036
USD and dairy products totalling a value of 3,408,760
USD (DENIVA 2006, calculations of the author)
The EU is also a primary external supplier of agricultural
products for Uganda. EU exports have a huge impact
on the Ugandan Economy since there is a tremendous
imbalance between the agricultural sectors in the EU and
in Uganda. The EU exports products in approximately
150 tariff lines and hence discourages value additions
within Uganda. Small-scale farmers and those who
have invested in processing cannot compete with EU
products. Thus, the local market share of agro-processing
industries is declining in Uganda (Interview Bakunda).
For example, while the EU is the biggest milk producer
worldwide, the dairy sector is still developing in Uganda.
Despite the set limitation of maximum quantities, the
EU produces a surplus of milk that is exported mainly
to developing countries where it is processed into
milk powder or butter. EU dairy exports are generally
subsidised to be competitive on the world market, while
Ugandan dairy farmers do not receive any support from
their Government.
4.1.2 Trade under the Everything But Arms
Initiative
Parallel to the CPA, the EU started the Everything But
Arms (EBA) Initiative in 2001.
The EBA is part of the EU Generalised System of
Preferences (GSP) to least developed countries. Currently
it offers duty- and quota-free access to the EU market
for all products of LDCs except arms, ammunition, rice
and sugar. The tariffs for rice and sugar were reduced
to zero until 2009, and then only arms and ammunition
will continue to be excluded. Uganda already exports
goods under the EBA. It is a unilateral offer of the EU
to LDCs and not a bilateral agreement. Therefore it may
not provide the same level of legal predictability as EPAs
would (DENIVA 2006, Werth et al. 2005).
4.2 Dairy sector and trade relations
In the dairy sector, the EU is the biggest external
supplier 7 to Uganda. Together with the Middle East and
South Africa, the EU supplies 50% of the market with
increasing tendency to supply more. Additionally, the EU
exports to Uganda via South Africa (with which the EU
has a Free Trade Agreement) (Interview Bakunda). The
total value of imports of dairy products into Uganda in
the years 2005 and 2006 averaged 289 mio. USD. The
value of direct imports of dairy products from the EU fell
between 2005 and 2006 from 488,000 USD to 289,000
USD. The primary imported dairy product from the EU is
milk powder. In 2006, its import value was 273,810 USD
(Reichert et al 2009).
4.1.1 Trade under the Lomé Conventions
Uganda is a least developed country (LDC) and a member
of the group of Africa, Caribbean, and Pacific countries
(ACP countries), which had special trade agreements
with the EU. Under the four Lomé Conventions, between
1975 and 2000 all ACP countries were been granted
duty-free access to the EU on most of their products (except
sugar andrice). Under the Lomé Conventions, these
non-reciprocal preferences were not in conformity with
rules of the World Trade Organisation (WTO) on mostfavoured-nations
and non-preferential treatment. Thus
in 2000, EU and ACP countries established a new trade
agreement providing for negotiations on reciprocal trade
rules between the two parties. This so-called Cotonou
Partnership Agreement (CPA) is valid for 20 years and
provides the framework for negotiations and implementation
between EU and ACP countries on Economic Partnership
Agreements (EPAs). It arranges for negotiations
on EPAs between 2000 and 2007 and for an implementation
phase from January 2008 onwards (CPA Art. 37).
EPAs should be compatible with WTO regulations, thus
providing for reciprocal market access arrangements.
7 “External” refers to countries outside the EAC countries.
17
4.2.1 Ugandan dairy imports from the EU
The data on dairy exports from the EU to Uganda reflect
the increasing prices at the world market since 2004
and the parallel emerging dairy production in Kenya and
South Africa:
Export of dairy products from the EU to Uganda
by value (USD) and net weight (kg)
TARIFF LINE 2007 2006 2005 2004 2003 2002 2001 2000
401 milk & cream not concentrated or
sweetened
402 milk & cream concentrated or
sweetened
3459 $
1600 kg
38,844 $
8,413 kg
40221 milk powder 38,789 $
8,400 kg
403 buttermilk, curdled milk and
cream, yogurt, kephir and other
fermented or acidified milk
and cream
13,039 $
16,300 kg
9,603 $
5,011 kg
214,539 $
54,100 kg
193,359 $
47,200 kg
2,275 $
300 kg
3,750 $
400 kg
538,439 $
150,800 kg
497,346 $
141,200 kg
no data 147 $
100 kg
654,685 $
208,300 kg
650,742 $
205,700 kg
no data 36,888 $
36,000 kg
404 whey no data no data no data 11,728 $
900 kg
405 butter and other fats and oil
derived from milk
76,562 $
7,100 kg
406 cheese and curd 363,098 $
52,912 kg
5,028 $
700 kg
57,104 $
9,432 kg
767,831$
260,600 kg
762,272 $
258,300 kg
58,227 $
62,500 kg
no data no data 5,140 $
1,700 kg
76,994 $
15,161 kg
22,386 $
2,300 kg
22,772 $
17,400 kg
674,127 $
277,500 kg
641,515 $
250,200 kg
1,711 $
600 kg
no data
973,112 $
371,100 kg
972,118 $
370,800 kg
17,416 $
16,700 kg
no data
493,417 $
230,900 kg
483,644 $
229,100 kg
no data
no data no data no data 32,456 $
16,000 kg
64,703 $
14,219 kg
no data no data no data
383,028 $
74,100 kg
2,748 $
600 kg
15,888 $
3,607 kg
Source:
4.2.2. Recent developments in EU milk policy
While during the time of the Investigative Mission, there
was little evidence that EU imports have a major impact
on marketing opportunities of domestic milk producers
in Uganda, there are reasons to fear that this might
change in the future:
1. Milk quota: In April 2008, the EU decided to increase
its milk quota (the ceiling for milk production in the
EU) by 2 percent. In November, in its “Health Check”
decision, the EU council agreed to further increase
this quota annually by one percent until 2013, after
which the quota would be abolished entirely. “In general
terms,” according to the EU Commission, “the
phasing-out of milk quotas would expand production,
lower prices and increase the competitiveness of
the sector.” (European Commission 2008: 9). The EU
hopes to increase exports, not least for skimmed milk
powder, which in the past has often been sold in great
quantities on African markets. A change as little as 0.3
percent, according to the estimates of the Dutch bank
Rabobank, can determine whether the world market
price is ruinous or bearable (Reichert 2008). If production
increases, according to the calculation of the
Commission, the European milk price will sink, and European
milk products will find their way into the world
market even without export subsidies.
2. Export subsidies: Since mid-2007 the EU had not paid
export subsidies on dairy products. However, in January
2009, the EU Commission took the decision to reintroduce
such export subsidies on butter, cheese and
milk powder. While shortly after the announcement
of new export subsidies, the German Minister of Agriculture
promised that these would not be granted
for exports to poor countries, the actual list of excepted
countries reveals the opposite: While countries
like the US, Australia and Canada are exempted, all
developing countries but South Africa are not. Thus,
there is nothing that prevents the EU from granting
export subsidies to ACP countries, including Uganda.
The statement of the EC that only very few dairy exports
end up in poor countries, is not true. Instead, in
2007, 68 percent of EU exports reached developing
countries. 13 percent of EU exports ended up in ACP
countries (Oxfam 2009).
3. International prices: The main reason for the EU not
providing export subsidies for awhile, was the high
level of world market prices for dairy products, especially
in 2007. However, since 2007, prices have fallen
dramatically. According to the FAO, skim milk powder
(SMP) prices fell to USD 3,025 per tonne in September,
41 percent below their peak in mid 2007, and whole
milk powder prices fell to USD 3,262 per tonne, 34
percent below their previous peak. In November 2008,
the FAO warned: “An important issue will be if prices
decline much further, as export prices for the European
Union may again fall below intervention levels and
induce a reinstatement of export subsidies. Previous
experience suggests that if this were to occur, price
declines could then accelerate as other exporters try to
compete with subsidized product.” (FAO 2008)
18 The Right to Food of Milk and Maize Farmers
4.2.3. Trade on dairy products with Kenya
Uganda also exports and imports milk powder to and
from Kenya. Since the EAC Customs Union has been
launched in 2005, trade of milk powder has increased
between the two countries.
Specific Exports of Milk Powder from
Kenya to Uganda
Year Total Exports in Kg Infant Formula in Kgs
2007 429,288 384,731
2006 375,335 353,334
2004 278,153 287,153
2003 2550 2000
Exports of dairy products
from Uganda to Kenya
Year
Total imports in litres
2007 230,120
2006 442,298
2005 400,760
2004 0
2003 0
Source: Kenya Dairy Board
Source: FAO 2008
Meanwhile, what the FAO had feared has become a
reality. The decline of international prices has accelerated,
especially since the reintroduction of export subsidies
from the EU. Comprehensive studies of the FAO on
import surges suggest that these surges have generally
occurred in times of low world market prices. Thus the
danger of such import surges is increasing, not least
in African countries, which have generally been most
affected by import surges in the past (FAO 2006).
• As a reaction to the reintroduction of export subsidies,
countries like Russia have increased their import
tariffs on dairy products to protect their farmers from
dumping. Such an increase of tariffs will no longer
be possible in Uganda under the EPA framework
agreement (see chapter 5).
4.3 Maize sector and Trade relations
Uganda’s maize exports and imports enjoy lower tariffs
within the COMESA countries (RATES 2003). As a member
of the East African Community (EAC), together with the
other four EAC members, Uganda strives for the establishment
of a common customs union. Uganda offers preferential
tariffs on maize imports from Kenya and Tanzania
ranging between 0 and 4 percent. Maize has become the
most traded commodity within the EAC and COMESA
(Bakunda 2006). But the increase in trade has not led to an
increase in the price farmers received for selling their crop.
Uganda imports some maize seeds and maize/corn from
the EU, but the majority of its imports are for food aid for
internally displaced people (IDP) who live in camps in the
war regions in Northern Uganda as well as in Rwanda
and the Democratic Republic of Congo. The World
Food Programme (WFP) implements the distribution of
the food aid. At the same time, the WFP is the main
maize buyer in Uganda. According to the Ministry of
Agriculture, Uganda does not compete in maize exports/
imports with the EU (Interview MAAIF).
Since the WFP buys only the best maize, some traders
developed the strategy to follow the WFP trucks to
buy maize from internally displaced people (Interview
Bakunda).Hence, although unintended, maize supplied
as food aid reaches the local markets. This could cause
dumping effects on the Ugandan maize market since
those traders can offer high quality maize for low prices.
Maize is also exported to neighbouring countries like
Sudan and Kenya. Due to the political crisis in Kenya in
the first months of 2008, agricultural production went
down. Since maize is a staple food in Kenya, Kenyan
19
traders bought huge quantities in Uganda. But despite
this increased demand, Ugandan farmers did not receive
a higher farm gate price.
The import data for maize show volatility in weight and
value 8 .
Maize Imports from EU by Weight (Kg) & Value (UGX)
Tariff line Product 2000 2001 2002 2003
1005.10.0 Maize Seeds 500
556,849
1005.90.00 Other maize (not seeds),
and corn
4,012,030
1,530,340,230
2,168,200
889,836,148
4,904,102
1,347,525,589
5,044,692
4,253,833,937
10,988,561
8,342,206,321
999,028
759,560,327
9,105,800
4,209,892,829
Tariff line Product 2004 2005 2006 2007
1005.10.0 Maize Seeds 668,000
356,539,112
1005.90.00 Other maize (not seeds), and corn 3,231,000
1,563,475,137
Source: Uganda Bureau of Statistics
226,741
585,427,294
7,907,610
4,148,725,054
no data
3,722,400
1,844,894,385
no data
no data
5. Uganda’s negotiations on
an Economic Partnership
Agreement
Uganda started the first phase of its EPA-negotiations
within the regional group of East and Southern African
countries (ESA 9 ) on February 7 th , 2004. At that time, the
Government of Uganda did not have an explicit national
trade policy 10 (SEATINI 2005a). ESA had agreed on a
three step process towards EPAs:
1. March – August 2004: setting of priorities and
negotiation procedures; (Preparatory period according
to CPA Chapter 2, article 37 (3));
2. September 2004 – December 2005: substantive
negotiations in the six clusters (Development Issues,
Market Access, Agriculture, Fisheries, Trade in Services
and Trade-Related Issues) with the aim to have a draft
EPA at the end of the period;
3. January 2006 – December 2007: solving issues of
disagreement, finalising and ratifying the EPA.
4. In eac country, the ESA States agreed to set-up a
multi-stakeholder National Development and Trade
Policy Fora (NDTPF) representing the public and
private sectors, civil society and academia. The idea of
the NDTPF was to develop national positions, which
would then be presented at the Regional Negotiating
Forum (RNF) by three representatives per country. The
RNF would meet at least quarterly to find common
positions. A Brussels-based Ambassador and a
Minister led negotiations on each of the six clusters.
8 The data are questionable, for example the incresase of value for maize seeds
from 2004 (534 UGX/kg) to 2005 (2582 UGX/kg)
9 ESA countries comprise Burundi, Comoror, Democratic Republic Congo,
Djibouti, Eritrea, Ethiopia, Kenya, Madagascar, Malawi, Mauritius, Rwanda,
Seychelles, Sudan, Uganda, Zambia and Zimbabwe.
10 The first draft of a national trade policy was elaborated by Premium Consulting
Limited and presented in April 2005.
Uganda organised its NDTPF accordingly and invited
representatives of the four stakeholder groups
(DENIVA 2006).
5.1 Negotiations between the EU and EAC
Due to the diverging interests of the 16 ESA countries
on sensitive products, no agreement was reached. Due
to this reason, the EAC 11 started to negotiate on its
own. Lead negotiator for the Ugandan Government
was the Ministry of Foreign Affairs (MFA). On November
14 th , 2007 the EU and EAC concluded, at a meeting in
Brussels, that they would finalize an EPA framework no
later than only 9 days later on November 23rd. The EPA
framework “fell from the sky” as a Ugandan civil society
representative described it, “it was not negotiated”. In
Uganda, the framework EPA has been initialled by the
Cabinet. The Parliament Committee on Trade had been
briefed but not consulted. Parliament would only later
ratify the comprehensive EPA.
Civil society organisations assume that the EAC, itself,
might have been interested in this EPA framework since
its members have not been in line with the ESA. There
are speculations that the private sector (the East African
Business Council), and mainly the flower and fish exporters
within the private sector, pushed the framework
through in order to safeguard their favourable access to
the European market (focus groups civil society).
The framework EPA provides a transition period of 15
years that should begin 7 years after the signing of the
comprehensive EPA, which is scheduled for July 2009
11 EAC members are Burundi, Kenya, Rwanda, Tanzania and Uganda
20 The Right to Food of Milk and Maize Farmers
(MTTI 2008). From 2015 to 2030, substantially all trade
(82 percent of the tariff lines) will be affected. The EAC
agreed on a list of sensitive products, amongst which
are dairy products and maize (Reichert et al. 2009). With
the framework EPA in force, the EAC cannot offer better
conditions to the EU than to EAC partners (Interview
Bakunda).
The EPA framework leaves the EAC with limited policy
space to negotiate mainly because of:
• the stand still clause (article 13) which does not
allow for the increase of tariffs after the signing
of the framework except to prevent dumping and
comparable policies and to apply safeguard measures
for a limited time period. In any case, the EU has to
agree to the measures taken. By accepting this rule,
the EAC loses its policy space provided under the
WTO to increase its tariff up to the bound tariff of 80
percent if a national economy sector is threatened.
• the prohibition to negotiate any other free trade
agreement with more favourable conditions for the
EAC (article 16). This might mean that the EAC will
have to consult the EU before it can sign agreements
with other countries 12 .
According to trade experts, the Interim EPA is not
favourable for Ugandan farmers. In the long run it may
impoverish them (Interview Bakunda).
5.2 EU position
According to the EU office in Uganda, the EU perceives
the overall impact of an EPA to be positive for Uganda
because it would create opportunities for the Ugandan
economy, since the EU is the biggest export market for
Uganda. An EPA would create a legal basis for trade
between the two regions and simplify the rules of origin.
64 percent of the 80 percent of commodities that
have to be liberalized under EPA already, reach the EAC
tariff free. However, one has to take into account that,
despite the Lomé Conventions, Uganda exports mainly
raw products. It remains unclear how an EPA would help
Uganda to export processed goods since the EU continues
to demand high quality standards for imports.
According to the EU, most agricultural products and
value additions are listed as sensitive products in the
Interim EPA. At the same time, Uganda is not among
the main future target markets of the EU. Instead, these
target markets areare the US, Japan and Australia.
Thus, the very limited space to adjust tariffs due to the
stand still clause of the Interim EPA , would not have
a major impact on Uganda. The interest of the EU is
to support development via trade and to encourage
European companies to invest in developing countries
like Uganda. The EU expert does not see a solution in a
more protective policy since Uganda has been protecting
its economy in the past, without progressing it.
12 It can be supposed that this clause has been integrated for geoplitical reasons,
to prevent that EAC signes favorable contracts with China (Interview Bakunda).
Internal constraints of the Ugandan economy would
be addressed under the European Development Fund.
Among these problems are how to organise farmers to
increase their bargaining power and how to improve
the overall infrastructure. The EU expert does not see a
link between internal constraints and any impact on EU
exports to Uganda.
The EU already supports the solution of internal
constraints by funding 70 percent of the PMA and 80
percent of NAADS. At the time of the interview, the
EU office in Uganda was finalizing the Uganda country
strategy within the 10 th European Development Fund
(EDF). Approximately 435 mio. Euro will be provided
for five years for budget support and for development
projects on infrastructure, rural development and other
sectors. The priorities have been discussed with the
Government of Uganda.
The EU office in Uganda sees a significant problem in
that political leaders mislead farmers. Their claims do
not merge with the capacities of farmers and markets.
The message of the Government of Uganda is to “go
big”. But there is still a lack of demand within the national
market, which hinders the growth of the processing
industries.
According to the EU expert, import shares of milk powder
from the EU are currently below 1 percent and there will
be no significant increase in imports in the course of the
EPA. The EU expert is also not aware of maize imports
from EU. However, he does not realize that even a slight
increase in imports might harm Ugandan dairy farmers
and discourage national dairy companies to invest, since
dairy farming in Uganda is neither mechanised nor
subsidised like it is in the EU.
The key issue for the negotiation on a comprehensive
EPA will be market access in the course of sanitary and
phytosanitary standards (SPS) for EAC exports, since the
standards of supermarkets regarding documentation of
production within the EU are high.
5.3 Civil society position on EPA
The strategy of the Ugandan civil society coalition
regarding the EPA negotiations was to convince the
Government not just to sign an EPA, but also to cooperate
with civil society during the preparation phase. The
coalition demanded that the Parliament stand up and
insist to be involved in the negotiations. Furthermore,
civil society undertook efforts to raise public awareness
on the EPA.
NGOs presented three petitions on the EPA. The first one
was presented to the Parliament on October 1 st ,2007
(Action Aid International Uganda et.al. 2007). In that
petition, CSOs expressed their concern about the potential
negative impact of an EPA on Uganda’s development,
mainly on livelihoods, employment, and regional
integration. They pointed out that Uganda’s exports
continue to be unprocessed goods, despite the longterm
preferential trading relationship with the EU. At the
same time, the share of EU imports coming from ACP
21
countries has declined. Hence, CSOs do not see how the
EPA will change this. Instead they fear a negative impact
on livelihoods and employment, which is an obstacle to
regional integration. They demanded Parliament to engage
itself more actively in trade related policies, and to
scrunitize the EPA negotiations to ensure that the Government
protects the livelihoods of Ugandans.
The second petition of the CSOs was addressed to the
meeting of the EAC and EU on EPA negotiations in Brussels
on November 14 th , 2007 (Uganda Joint Christian
Council et.al. 2007 13 ). CSOs expressed their concern
regarding the agreements on market access and development,
mainly that the EAC had offered to deregulate
81 percent of its imports from the EU after a certain transition
period, without a commitment of the EU to reduce
their export subsidies and other non-trade barriers and
to provide a precise commitment to development cooperation.
The signing organisations forecasted deindustrialisation
and further impoverishment of EAC inhabitants
and economies due to the EPA. They recognise the offer
of the EU to guarantee duty-free and quota-free market
access, but they do not see anything new about this
offer since this was already guaranteed to ACP countries
under the Lomé Conventions. They demand that
development should be a core issue of EPAs and point
out that EU had repulsed all stakeholders who reject the
proposed EPA framework.
The third petition was handed in to Parliament on March
11 th , 2008 (Oxfam GB in Uganda et.al. 2008). It criticised
the content of the EPA framework, as did the petition of
November 14 th , and the Rendez-vous Clause (article 37)
which provides for the continuation of negotiations on
wide-ranging areas which will limit Government’s policy
space to realize development. They conclude that the
EPA is not only in line with SAPs, but it will even be more
harmful for the country than SAPs, since the EPA strives
not only for tariff reduction, but also for irreversible
tariff elimination. The undersigning NGOs do not think
the sensitive products are protected enough since the
provided trade defence measures like antidumping and
countervailing measures have been adapted from the
WTO. According to them, most developing countries
had difficulties applying them in the past.
In article 16(2) of the framework EPA, the CSO see a
threat to regional trade integration since this commits
EAC to avoid making better trading arrangements with
other trading partners.
Furthermore, CSOs expressed their concerns about a
lack of democratic procedures since stakeholders, such
as Parliaments, have not been consulted. Thus they
demanded Parliament to debate the agreement and to
monitor the developments in the negotiations.
Later, CSOs organised a peace march, three radio talk
shows and a workshop (focus group civil society) to raise
awareness on the devastating effects of EPAs on Uganda.
Civil society organisations predict that the full
implementation of the EPA will lead to the death
of the farming sector, because the farming sector
cannot compete with imports from the EU. They fear
that Genetically Modified Organisms (GMO) will enter
through the back door and create dependency. Farmers
will not be in a position to determine what they sell
(focus group civil society).
6. Dairy farming in Mbarara
District
Mbarara is a district in Western Uganda. Its capital is
also called Mbarara. Mbarara known in Uganda as the
main cattle raising area t It is even called the “home of
milk”. Milk is an important income earner in this region.
While in the past, cattle were mainly held to show the
status of a farmer they are now kept for business. Most
farmers do mixed farming. Apart from cattle raising,
they grow mainly millet, groundnuts, maize and matoke
(banana). The majority of farmers have only small plots
for cultivation. They do not use preservation technologies
and face food scarcity from October to December.
Due to land scarcity, Mbarara dairy farmers had crossbred
the traditional cattle breed, the Ankole Long Horn
Cattle, by artificial insemination with exotic breeds.
Crossbreeds produce more milk than the traditional
breed. Thus the farmers need fewer acres of pasture
to produce the same amount of milk. Dominant is the
black and white breed (Friesen/Schleswig Holsteiner), for
which farmers use sperm from Germany. Other breeds
are Usher and Jersey. The disadvantage of the black and
white is that it is not resistant against droughts.
According to dairy farmers, production has increased
during the last years because of high yielding cows.
Cows are generally fed with grass. Farmers have not yet
adopted the techniques of haymaking. Only 400 cows
in Mbarara are on zero grazing - not fed by grass but by
grain. The average price for one Jersey cow is 1 million
UGS (600 USD). Friesen cows cost a bit less.
13 Uganda Joint Christian Council et.al. 2007;.
asp?id=499 , [28.01.2008] )
22 The Right to Food of Milk and Maize Farmers
Nyakisharara Village
Nyakisharara is a small village with 34 farms 16 km away
from the town of Mbarara. On average, seven people
live on every farm. The village has a local council with
a chairman and an executive committee comprising 9
people.
Nyakisharara is not connected to the national electricity
network. Only 4 farms have running water as the result of
to their own efforts. The village has a primary school. The
next hospital is 16 km away. By tradition, all households
are headed by men.In Nyakisharara, all land is owned
individually. The average acreage per farm is 50 acres.
Farmers calculate that 1 acre is need for every 2 cows.
Most of the farms have less than 100 cows. Out of the
34 farms, a maximum of 3 households have only up to
3 cows, 5 households have between 4 and 10 cows, 10
households have between 11 and 20 cows. All the others
own anywhere up to 200 cows. But there is a tradition
in Ankole not to talk about the number of cows a farmer
owns: “Never mention the number of your animals,
otherwise they will die.” Farmers perform farming in a
semi-commercial way. None of them is a member of a
cooperative.
In the village the main human diseases are malaria and
anaemia from which mainly the children suffer. Medicine
to treat malaria is available at the hospital. HIV/AIDS and
tuberculosis are not common, nor is there a high child
mortality rate.
Most processing materials have to be imported from
other countries. Packing papers, for example, are
imported from Kenya. During the Kenyan political crisis
in January/February 2008 it was difficult to get those
packaging materials. Also liquid nitrogen, which is
needed to clean the flasks for the milk, is scarce due to
the Kenyan crisis.
But the main bottleneck for the farmers is the marketing
of milk. Marketing is difficult since the important market
in Kampala has been flooded with milk from farmers
around Kampala. To be closer to the main market, some
farmers have moved from Mbarara to Kampala. This
indicates that cooling and transporting infrastructure is
a major problem within the supply chain.
The dependence on grass to feed their cows makes
farmers easily affected by the seasons and other climate
conditions. During the rainy season their milk abounds.
Cows may deliver 10 l per day. Then the buyers say:
“Coolers are full, do not bring milk tomorrow.” In the
dry season a cow delivers between 0 and 7 l per day.
In 2005, the Uganda Crane Creameries Cooperative
Union Ltd. was founded to market milk collectively. The
cooperative members see a high potential to increase
milk production and consumption in Uganda. Production
is already steadily growing. The following quantities of
milk are sold in the formal markets of the districts:
• Bushenyi: 150,000 l/day
• Mbarara: over 150,000 l/day
• Ibanda: over 160,000 l/day
In the informal markets, where most people buy milk,
almost the same quantities are sold
Members of Cooperative Union see imported milk as
a threat to their business. Ugandan farmers cannot
compete with imported milk powder, because they do
not receive subsidies. According to the members of
the cooperative, most farmers are not well-educated.
They do not incorporate modern technology into their
farming practices.
Members of cooperatives and farmers in the village
prefer the system, when the Uganda Dairy Cooperative
was active and bought the milk. Compared to today,
farmers had the following advantages:
• they could approach the management, while today
management does not listen to them;
• the price was fixed and fair; the working environment
was positive;
• due to fixed prices production went up;
• each collection point had to handle fewer farmers
On the other hand, members mentioned a negative
aspect of working under the Uganda Dairy Cooperative
was that that they had no bargaining power. Farmers in
the village have the opposite view. Before deregulation,
farmers’ representatives were active in the cooperative
and bargained with Government in the interest of
farmers, while today they have no bargaining power.
The price of milk is just set by the trader.
The farmers in the village find extension services
inadequate since they were privatised. The Government
provides extension services if the farmers ask and pay
for them, but the services are weak. Farmers also have
to pay the veterinary and transport costs. Furthermore,
there is only one veterinary at the sub-county level.
Dairy farmers in Nyakisharara
Most of dairy farmers in Nyakisharara hold land as
customary tenants. The majority of their cows are
cross-bred. In dairy farming, the farmers all depend on
seasons. No farmers use the zero grazing method for
dairy production. On average, during the wet season,
their cows produce between 5 and 8 l per day. During the
dry season they produce less, and some cows even dry
up. None of the farmers sell to the formal market. Many
of them employ farm workers. Apart from dairy farming,
the families grow bananas for commercial purposes and
beans, maize, cassava, groundnuts, soybeans and sweet
potatoes for home consumption.
Their farming costs are higher during the dry season than
during the wet season because the cows need to be watered
during dry periods. The farmers do not receive any
support from the Government. Those who have the necessary
knowledge even vaccinate their cows themselves.
23
6.1 Dairy Supply Chain
Farmers who are members of a cooperative bring their
milk to a milk collection centre. Those centres are, on
average,5-6 kilometres away from the farms. Farmers
have to cross that distance by bike. From there, the milk
is brought to the District Dairy Farmers Cooperative
Union and then brought to the umbrella organization,
the Uganda Crane Creameries Cooperative Union Ltd.
The latter cooperative markets the milk.
One problem is that milk is highly perishable. Bacteria
begin affecting the quality of the milk after 6 hours and
the milk also loses quality via the bike transport.
A major marketing problem is the fact that farmers do
not collect all milk produced during the wet season when
there is surplus. They sell the surplus to informal traders
at low farm gate prices. In April 2008 the price of milk at
the informal market was 100-150 UGS/litre (0.06 – 0.09
USD/l) while the cooperative price was 300 UGS/litre (0.18
USD/l). In Kampala, one litre of pasteurised and packaged
milk is sold at 1,500 UGS/litre (0.90 USD/l). While the trader
in the informal market sets the price, the cooperative
negotiates and prices are fixed for three months.
During the wet season, the price per litre of milk paid
to cooperatives is higher than the price on the informal
market,. This can switch during the dry season. In this
case, the cooperative renegotiates the price.
On its way from the farm to the consumer, the milk sold in
the formal sector is tested three times. To avoid that farmers
dilute the supplied milk, the cooperatives test temperature,
alcohol, and water when they receive the milk at the
collection centre. Before the collected milk is loaded into a
tanker it is tested again. And a third test is made when the
tanker reaches the processing plant in Kampala.
Main processors are the private companies Sameer Agricultural
Livestock Processors, JBK Processing and Alpha
Dairies. Farmers claim that they are at the mercy
of those processing companies. The companies do not
honour different qualities. In 2007, two months of production
were lost due to poor processing. The cooperative
does its own lactoscan, but when the milk reaches
the processors they often report that water has been
added. One cooperative member claimed: “They cheat
farmers just to discourage them.” One farmer from
Nyakisharara had tried to sell to Alpha Dairies but he
stopped when the company offered a lower price than
the vendor. However, the non-organised farmers did not
experience cheating by processing companies. It seems
that the companies uses this practice only on cooperatives,
which might become competitors in future.
To produce better quality milk, farmers see the need
to have processing plants closer to production sites.
That is why the Uganda Crane Creameries Cooperative
Union Ltd. plans to set up its own processing plant. The
business plan is in place. The National Environmental
Management Authority (NEMA) has already awarded
the certificate. Members of cooperatives are convinced
that a successful dairy sector needs to hold production,
processing and marketing in one hand.
Sumpca Dairies
Sumpca Dairies is a milk trading company. The company
runs one collection point and three selling points in
Mbarara and has 11 employees. Sumpca only cools
the milk; it does not process it. The company buys from
farmers and vendors and sells to private people and to
the dairy companies Paramount, Alpha and others. In one
of their selling points they have a tank with a capacity of
800 l and sell up to 1,000 l per day from 7 am to 8 pm.
The other two selling points have capacities of 500 and
400 l. They buy milk for 300 UGS/litre (0.18 USD) and sell
it at selling points for 400 UGS/litre (0.24 USD/l) during the
wet season. To the dairy companies they sell 1 litre for 420
UGS (0.25 USD). During the dry season they buy 1 litre for
400 UGS (0.24 USD) and sell it for 500-600 UGS (0.30 –
0.36 USD). According to one of their employees, the price
of milk has not changed during the last four years.
Since the privatisation of the Uganda Dairy Cooperation
in 1992, all the farmers in Nyakisharara sell their milk
to local vendors in the informal market. Those vendors
sell to families, coolers, restaurants and the factories of
the dairy processing companies GBK, Alpha and Sameer.
The vendors are not organised. Everybody works on his
own. Therefore, it is very important for the vendors to
keep good relations with their farmers and customers.
Otherwise, they might lose business due to high
competition. The vendors have to guarantee the farmers
that they will collect the milk every day. If they are sick,
they need to find someone to replace them. If they do
not collect the milk, they have to refund the farmer his
loss of income. From the surpluses, the wives of milk
farmers make butter mainly for home consumption.
The vendors sell milk on the open market in Mbarara for
500 UGS/l (0.30 USD/l) during wet season and for 700
UGS/l (0.42 USD/l) during dry season. Some of them see
supermarkets as a competitor.
Vendor A
Vendor A buys milk from three farmers only in the morning
and sells the milk in Mbarara. During the wet season he
buys 150 l/day and he pays 250 UGS/l (0.15 USD/l).
He sells the milk for 300 UGS/l (0.18 USD/l). During the
dry season he buys 100l/day and pays 300 UGS/l. He
sells at 400 UGS/l (0.24 USD/l). He collects the milk by
motorcycle and always buys all the milk the three farmers
are willing to sell. He sells to hotels, private families and
coolers. All his customers pay the same price. He pays
7,000 UGS (4.20 USD) for fuel per day. Thus, his daily
profit during the wet season is 500 UGS (0.30 USD), and
during dry season it is 3,000 UGS (1.8 USD). He uses his
own lactometer to test the quality of the milk. The time he
needs for buying and selling is 3 hours per day, from 7h
to 10h am. He pays the farmers every 10 days. He gets
paid by hotels and families once a week and by coolers
every 5 days.
Apart from trading milk, he works as a carpenter in his
own workshop in Mbarara. From carpentry work he gets a
daily income of approximately 8,000 UGS (4.80 USD).
His customers determine the price, and he calculates
it according to demand. He does not compete with
supermarkets since his customers prefer raw milk.
24 The Right to Food of Milk and Maize Farmers
6.2 Development of Prices and Costs
Before deregulation the farm gate price was stable. According
to farmers, one could earn enough income from
six cows to feed a family and to pay school fees up to
the university level. But according to a dairy farmer “the
good old days have gone by.” 15 years ago farmers got
50-80 UGS/litre (0.05 – 0.08 USD/l) while production
costs remained steady at around 40-50 UGS/litre (0.40
– 0.50 USD/l). But in the last couple of years costs for
drugs have increased faster than farm gate prices. At
first glance, when only considering the farm gate prices,
which have increased to 300 UGS (0.18 USD), farmers
should be better off today (at the time of publication, 1
USD was equivalent to 1,700 UGS while 15 years ago, 1
USD was equivalent to 500-600 UGS). However, considering
the increase of living and production costs, it is obvious
that farm gate prices have decreased dramatically
in real value.15 years ago, 1litre of fuel was 200 UGS
(0.20 USD). Today the price is 2590 UGS (1.56 USD) for
1 liter of fuel. 15 years ago, 100 kg of maize was 1,000
UGS (1 USD), today 1 USD can only buy 1 kg of maize.
According to the members of the Crane Creameries
Cooperative Union, in 2003 costs of milk production
averaged 150 UGS/litre (0.09 USD/l). The farm gate price
was 200-250 UGS/liter (0.12 – 0.15 USD/l). Currently,
costs of production are 200-225 UGS/litre (0.12 – 0.14
USD/l), while the cooperative receives 300 UGS/l (0.18
USD/l). Since part of the overall price of a liter of milk is
kept by the cooperative, the overall profit of the farmer
who sells to the cooperative makes is 50 UGS/litre (0.03
USD/l). Only the hope that they will someday own
their own processing plant makes the members of the
cooperative stay members. Meanwhile, some farmers
have already shifted from dairy to beef. Those who still
produce butter can sell 1kg for 6,000 UGS (3.60 USD).
On the open market in Mbarara, butter is sold for 7,000
UGS/kg (4.20 USD/kg) during the wet season, and for
8,000 UGS/kg (4.80 USD/kg) during the dry season.
Main factors of milk production costs are:
• drugs for medical treatment of cows
• food supplements
• iinjectables
• vaccinations
• acaricides (pesticides that kill mites)
Farmers in Nyakisharara do not belong to a cooperative.
They do not have the same opinions on cooperatives
as people in Mbarara. Some famers in Nyakisharara
think that their profits would rise if they had a national
cooperative that could subsidise vaccines and other
production factors. Others still remember the past
when farmers were not paid in a timely fashion. They
are also aware that the cooperatives need to pay their
staff, which reduces the farmer’s income. The farmers
interviewed in Nyakisharara are not aware of their
production costs. They estimate that they spend half of
their money on farm costs, but they do not calculate
costs of their own labour.
Besides the production costs, members of the cooperative
rank the costs which take up most of their income in the
following order:
1. education;
2. medical care
3. transportation
4. telecommunication
Housing is not a significant cost for them and clothes are
bought only seasonally (e.g., at Christmas and Easter).
Still, farmers cannot cover just the costs listed above.
They commonly borrow money from different sources.
Some farmers are heavily indebted since interest rates
from banks are high.
6.3 Gender
In the village men traditionally head the family. When
a head of a family dies, the family sits together and
decides on a successor, which is typically one of the sons
of the deceased. The new head of the family can sell
the land only if the widow of the former head of the
household agrees.
Farm work is shared between men and women but
each has his/her special tasks. The men do the milking,
the watering of cattle, the fencing and the general
maintenance, and they sell the milk. Women do the
churning of butter and crop husbandry. In the past,
women have produced and sold ghee (butter), but
nowadays men sell all milk and receive all the money
earned by dairy production.
Besides the dairy production, women grow bananas,
cassava, sweet potatoes, groundnuts, peas, beans,
millet, maize, oranges, watermelon and mangoes. The
farmers sell only the milk, livestock and bananas. All
other crops are for home consumption. Thus, women
contribute mainly to the food security of the family.
6.4 Food Security
The members of the cooperatives stated that dairy
farmers do not face food shortages since they also have
banana plantations and gardens. Small farmers cultivate
sweet potatoes and cassava. Only the landless do not
enjoy food security.
Some farmers in the village face hunger during the dry
season. Among the individually interviewed farmers, two
were obviously exposed to food shortages. Especially
small-scale farmers, who have only 3 cows, have no
milk during the dry season. They may also borrow a cow
from their neighbours and milk it until it dries up. While
farmers were able to save money before deregulation,
incomes are currently too low for the farmers to save
money. Therefore they cannot compensate for their
lower income during the dry season. Products that
have become too expensive for farmers to be able to
afford them during the dry season are sugar, bread and
meat. The Government does not help in those times.
25
Therefore, the Ankole Food Security Network, of NGOs,
plans to introduce food collection centres to prevent
food shortages in future.
Farmer B
Dairy Farmer B is 35 years old. He is married and has
five children. The economic basis of the family is dairy
farming. They have 10 cows of which 5 produce milk in
the rainy season. Today, the cows produce 17 l of milk
in total. B sells all this milk for 300 UGS /liter to a private
vendor who sells the unprocessed milk directly to local
people in the villages. According to B, there is no contract
between himself and the vendor that would guarantee a
stable and secure market. Sometimes the vendor does
not stop by B’s farm on his rounds. B then has no income
for that day.
B complains that the dairy business does not provide
him enough income to feed his family. Without his small
cultivation of banana, sweet potato and beans, the family
would suffer from hunger throughout the year. In the dry
season, the harvest is still not big enough to feed his
family. These are the times when the family is forced to
buy maize flour for 800 UGS/kg. As this is too expensive,
the family must reduce the number of meals to two.
The main reason for low incomes and food shortage
are low farm gate prices, the small number of cows and
high living and production costs. Every three weeks B
spends 15,000 UGS for paraffin. He spends 10,000 UGS
per trimester on school fees for his two eldest children.
Currently he has to pay high fees for malaria treatment for
his 8-year-old daughter. “In the hospital, last time, they
asked almost 30,000 UGS”, he says.
Furthermore, problems are caused by storms that
sometimes occur in September/October and destroy
banana gardens. According to the farmers, this problem
has been considered by the Government, which plans to
set up a drying plant to produce banana flour to make
banana bread.
6.5 Findings in Mbarara
There is no direct competition between local milk
production in the Mbarara village and imports from
the EU. The local production reaches the informal
market while imports reach the formal market. Only
the members of cooperatives may be affected by
imports since they supply the formal market chain. The
farmers fear that imports reduce prices and discourage
investments in processing plants. The Uganda Crane
Creameries Cooperative Union’s plan to set up their
own processing plant might be threatened by the EPA
since an increase of imports of dairy products might
undermine the building up of their new business.
Even if there is no direct competition of imports with
local products in the local markets, imports might
affect marketing opportunities of farmers in Mbarara.
According to expert interviews, imports occupy a large
share of the formal market and might be one of the
reasons why local milk is not processed and does not
ultimately enter the formal market.
Dairy farming is associated with some accumulation of
wealth. Nevertheless the investigative team observed
that hunger occurs amongst dairy farmers, as well. The
team found evidence that some dairy farmers suffer
food shortages. One of the four farmers interviewed
said that he faces food shortages during the dry season.
The paradox exists of a growing production of milk, a
growing demand of dairy products and at the same time
a growing poverty among dairy farmers. This situation
can be attributed to two main factors. First, the increase
of production required considerable investment to
replace indigenous cows by crossbreeds and Friesian
cows. Second, following the deregulation and the
privatisation of processing and marketing since 1992,
farmers have entirely lost access to the formal dairy
supply chain and only sell their milk to local informal
vendors. According to the farmers, for the last 15 years,
the nominal average price per litre of milk, during wet
season, has increased only from 50 to 200 UGS, which
in real terms means a drastic decrease in purchasing
power due to inflation, and increasing consumer prices
for daily needs like medicine, school fees, food, and
increasing production costs.
Farmers reported that more milk collecting points
were in place before privatisation of the Uganda Dairy
Corporation. Farmers could sell all their milk to UDC,
received a higher and more stable price while production
costs were lower than today. Thus the farmers were
better off before deregulation. New private companies
entering the sector have not been motivated or forced
by law or other governmental regulations to invest in
this infrastructure.
The level of financial recordkeeping is low at the village.
Farmers do not know and/or record their costs of
production. They have not developed techniques (like
making hay) to become more independent from the
effects of the seasons and the environment, which is
necessary to ensure the food security of the poorest of
the farmers. Government has released farmers into the
deregulation climate without preparing and assisting
them properly in coping with the new situation, in
which everybody struggles on his own.
The women have lost access to milk, markets and
income due to privatisation of UDC and deregulation
of the sector. While they usually received a share of the
milk to produce and sell butter, the men now sell all
marketable milk. Thus the women have lost a source
of income.
While experts and members of Uganda Crane Creameries
Cooperative say that milk is poured at the farms, this
was not reported by any of the farmers in Nyakasharara.
Two factors might explain this: the farmers sold only to
the informal market and the village is relatively close
to the market in Mbarara town. Due to the fact that
milk is a perishable good, the distance to the market is
probably a crucial factor. Farmers who live far away from
Mbarara or from a cooling facility may not be able to sell
all the milk. Thus, there is a need for the Government to
invest more in infrastructure like roads and electricity.
26 The Right to Food of Milk and Maize Farmers
Dairy farmers have not experienced any real bargaining
power in the last 20 years. Since the production of
good quality milk is not honoured by the market, the
Government should introduce a regulation on quality
and assist farmers to bargain a price accordingly.
“Cheating” of farmers by processors has not been experienced
by the community and the vendors, but only by
the cooperative (bulk selling). The reason for this might
be the fact that the cooperative is a future competitor
for the processors since it plans to build its own processing
plant. Government should not view farmers’ cooperatives
only as economic actors on the market like they
view solely commercial companies since the cooperatives
contribute to food security. Instead, Government should
set rules to strengthen the cooperatives and make them
more attractive to farmers. Part of this strengthening
could come fromoffering the farmers legal advice and
improving the judicial system so that cooperatives and
their members have easier access to courts and receive
judgments in a reasonable time frame.
7. Maize farming in Bugiri
District
Bugiri, a district in Southeast Uganda, is one of the
main maize growing regions of the country. It extends
to the Uganda-Kenya border in the east and to Lake
Victoria in the south. It has a total population of
413,477 people. According to the findings of the Bugiri
District Advocacy Coalition (BUDAC), 86 percent of the
households are food insecure for four to six months
per year. Approximately 40 percent of the households
have access to safe water. Most of the farmers practice
subsistence farming (BUDAC 2007). Farmers themselves
call Bugiri a food basket due to its fertile soil. Since
2003, farmers have struggled against Stryga, a disease
that affects maize.
Farmers in Bugiri have formed an association, which is
called Bugiri Farmers District Association. In 1993 they
started to organise themselves at the village level, in
1998 at the district level and finally joined the Uganda
Farmers Federation. In 2008, the association had 4,950
individual members, men and women, incorporated
into 132 community-based groups. In addition, farmers
are grouped according to the crops they produce. The
association undertakes surveys, capacity building and
advocacy on production and marketing. The construction
of its office has been funded by DANIDA, the Danish
development organisation; the district authorities have
donated the compound. The NGO VECO supports them
with seeds, goats and coffee plants. Together they
address issues of food security and household income.
The majority of the farmers (approx. 60 percent) are
small-scale farmers who cultivate less then 2 acres. 30
percent have between 2 and 15 acres of arable land and
10 percent cultivate more than 15 acres. For commercial
purposes, farmers produce maize, coffee, rice and some
plan to start dairy farming. Maize is a cash crop and a
food crop. Almost every farmer in Bugiri grows maize.
Farmers do not do monocropping. They plant only
certain shares of their land with maize. Since the year
2000, the members of the farmers association have been
growing maize commercially and using oxen to plough.
They would like to produce more but they lack skills and
are discouraged by bad roads and poor transport, which
lowers the farm gate price. Furthermore, the market
chain is too long due to middlemen.
Farmers have been encouraged by a rural farmers’
project scheme of the Ministry of Agriculture to produce
maize. At the time of that project there was a demand
on maize. But farmers did not benefit from lending
schemes to invest in the new crop. Loans had to be
paid back during the off-season. The farmers also felt
that bank policies on lending were unfavourable for
farmers. Their interest rates are very high, reaching up
to 30 percent, and loans have to be paid back within 6
months. One of the interviewed farmers was harassed
by his bank to force him to pay back his credit. “The
bank came with policemen even at night.” Microcredit
agencies are also active in Bugiri. They offer loans for
farmers, but according to those interviewed, the farmers
remain indebted.
Some farmers use hybrid seeds. In 2003, when Uganda
Seed was still under the Ministry of Agriculture, they
grew the brand 2b. Since 2005, Uganda Seed has
been privatised and called FICA. President Museveni,
of Uganda, owns FICA. In 2008, some farmers used
hybrid seeds grew Long 6h and 6h7, which did not
germinate. Thus the farmers will have to buy new seeds
every season. Since deregulation, the quality of seeds
has dropped while the price has increased. There are
projects to introduce high yielding maize, but those
projects have failed to create markets. Thus farmers do
not see an incentive to use them.
The farmers wish that Government would retain the
manufacturing of seeds and fertilizers since the quality
of those products was better under the Government.
They appreciate that the Government did not work on a
profit-oriented level. They also wish that the Government
would introduce irrigation to them. Farmers wish to
receive subsidies from the Government so that they can
compete with subsidized crops from other countries.
One big buyer of crops is the World Food Programme
(WFP), but it is hardly possible for small-scale farmers to
sell to the WFP due to its specific criteria (see chapter 8).
Farmers could take out credits from banks to meet the
WFP criteria, but the banks demand repayment after six
months. Due to late payment by the WFP, farmers are
not yet able to refund the banks on time.
Farmers are aware of the maize imported into the US
in 1980, from Zimbabwe between 1990 and 1993 and
from South Africa in 1997. They have never heard of
maize imports into the EU. GMO maize is imported from
South Africa and the US. Farmers have not heard about
agrofuels.
27
Bukyansiko village
110 families, with an average of five household members
in each family, live in Bukyansiko, which is 9km 2 large.
Women head ten of the households. The village has
a chief and a local council.The village does not have a
school, but it has a health centre. The next school is 2 km
away. People get water from 5 boreholes. Bukyansiko is
not connected to the electricity network. The inhabitants
faced droughts and famines in 1939/40, 1980 and 1990-
93 that led to migration. In the past, they also suffered
from sleeping sickness.
There are two types of land ownership: customary owned
land and bought land Neither group holds formal land
titles. 90 out of 110 families cultivate their own land. 60
percent of the farmers own less than 2 acres.
70 percent of the land is cultivated with maize. Other crops
are rice, groundnuts, cotton, coffee, beans, cassava,
sweet potatoes and soya beans. The whole village
produces approximately 500 t of maize per season. All
farmers sell maize to middlemen. There is no maize mill
in the village.
60 farmers are members of the farmers’ association. Only
these members get support from the Government through
its extension services (NAADS). Farmers have observde a
loss of soil fertility during the last 20 years. Additionally,
the Stryga disease reduced the harvest.
Farmers have never sold to the Ugandan Produce
Marketing Board.
7.1 Maize Supply Chain
Maize farming in Bugiri has two seasons. The first is from
January to July and the second from July to December.
January is the time of ploughing. In February the seeds
are planted. Farmers apply the fertilizer DAB in March
and the women weed in April and May. When the
maize is knee high they apply a fertilizer called Urea The
harvest starts in June and ends in July. After harvest the
farmers directly start to plough.
Maize is sold in three ways:
• as green corn within its leaves
• as whole corn
• as grain already shelled.
Farmers produce maize for consumption, either for their
families, for food aid or for the market. They do not mill
the maize. Milling is done exclusively by millers. Millers
produce maize flour for consumption and for animal
feed. They sell the maize flour back to the farmers, at
the time of the research at 1,000 UGS/kg (0.60 USD/
kg). Out of 100 kg maize, they get 75 kg of high quality
flour or 80 kg of lower quality flour.
Middlemen buy at farm gate. They know when farmers
are under pressure to sell and come, for example, at times
when parents have to pay school fees. Sometimes farmers
even sell to middlemen before harvest. “A farmer is like
a beggar. He cannot take a decision on the price he sells
the crop for. The middlemen dictate the price.” The price
also depends on the distance to the market in Bugiri.
Some farmers store maize, but only in small quantities,
which they sell during off season. The middlemen,
however, do the storing.
The main maize market had been shifted from Busia, a
town at the border to Kenya, to Jinja. According to the
farmers, the shift is due to political reasons. “People in
Busia do not respect the Government.” Farmers believe
that President Mujseveni’s daughter, Natasha, is behind
this shift. According to the farmers, she trades maize
in huge quantities even to Zambia. The FAO explains
that she is a middlewoman who manages to sell huge
quantities and supply the WFP.
In the past, some middlemen sold to the auction in
Busia. But during the political crisis in Kenya in 2007,
the market broke down. However, Kenyan traders do
not buy Bugiri maize ndirectly from the farmers. They
buy only from middlemen and the farmers do not know
at what price the traders purchase the maize.
Millers in Bugiri buy mainly from the middlemen. They
sell flour locally to shops, traders or boarding schools.
Only some bring it to Kampala. Their market in Bugiri
is limited and challenges are transportation, costs for
electricity, and lack of capital. A few of them do milling
and trading. The middlemen are independent, but
sometimes millers pay the middlemen to buy maize for
them. At the time of investigation, there were 15 millers
in Bugiri. According to some of the remaining millers,
seven had to close down prior to the investigation due
to power problems,.
The Bugiri District Commercial Office also sees the
marketing deficit. According to its staff, the main
problem is that the farmers cannot sell in bulk, neither
to the auction in Busia, nor to the WFP. Thus, farmers
depend on middlemen. They see the following main
challenges for farmers:
• Farmers do not control the weather, and insurance
against unfavourable weather does not exist.
• Farmers have to sell at low prices, which do not allow
them to buy seeds for the next season.
• Exploitation by middlemen occurs, since farmers
bargain individually.
• Harvest handling: farmers do not have proper storage
facilities.
• Some cooperatives do not pay immediately; therefore
farmers lose trust.
• Limited support: lack of training on value adding.
• Lack of access to loans with lower interest rates.
The district has a District Livelihood Support Programme
approach on natural resource management and
agricultural development. Farmers are also supported
by NGOs: mainly GOAL Uganda, and FOCRIF.
According to the commercial officers, production was
easier for farmers in the time of the Uganda Produce
Marketing Board because the UPMB connected smoothly
28 The Right to Food of Milk and Maize Farmers
with farmers. Today, a quality problem can be observed.
While the UPMB used to control quality, nowadays
everybody can sell bad quality maize, but for lower
prices. The officers blame corruption for the decease
of the cooperative system. One farmer said, “It died by
itself due to corruption.” Farmers sold their maize to
the cooperative but never got paid. Thus, they left the
cooperatives when the market was deregulated.
From the perspective of the local government, the
PMA functions but does not focus on the maize sector.
District authorities and NAADS support maize farmers,
but NAADS could create markets. For the years 2007/8,
Bugiri District received 215 mio. UGS (129,000 USD)
under the PMA. This amount will mainly be spent for
agriculture, roads, water and dairy. Before the money
arrived, sub-county chiefs were informed to consult the
farmers. Additionally, the district selected 30 villages
randomly for interviews. The NAADS approach is to
respond to farmers’ demands. The community has to
identify an enterprise (eg. maize). Local authorities can
use the money for needs they have identified. But one
does not feel that the funds will have a strong impact
on agriculture.
The farmers criticise the District Commercial Office
because it does not know their real problems. They also
see a lack of participation. Although Commercial Office
invites the farmers for consultation, the farmers are only
allowed to listen. Demands to also let the farmers talk
have been rejected. Additionally, those hearings are
announced only with short notice, approx. three days
in advance.
Maize farmer 1
He and his wife are customary tenants and cultivate
maize (hybrids), soy, groundnuts, beans and cotton on
11 acres. Out of these, they sell maize, soy and cotton.
For maize growing they use the fertilizers DAB and Urea.
The farmer sells the maize to different middlemen. The
family normally eats three times a day, but in May and
June they eat only twice a day. In contrast to the general
observation, their income generated by maize is better
now than it was during the 1980s. This might be because
the farmer always sold to middlemen and not to the
Produce Marketing Board.
7.2. The World Food Programme
A few farmers have sold to the WFP through commercial
farmers’ associations or private companies. But they do
not continue selling because of the late payment.
WFP has strict criteria on quality and quantity:
• The minimum quantity of maize, which WFP buys
from a supplier, is 50 t per season.
• The whole 50 t must be kept in one place.
• WFP does not pay on the spot, but only three months
later.
• The moisture of the grain must be within a certain
range.
• The grain needs to be uniform and whole.
• The grain must be free of insects.
Small-scale farmers can hardly comply with this criterion,
especially not with the quantity component.
One of the farmers sold 250 t in 2005 to the WFP, but
he did not continue because of the late payment by the
WFP. He had to take a credit to be able to supply the
WFP and the banks harassed him to pay the money back
even before the WFP paid him.
7.3 Development of Prices and Costs
Farmers complain about high costs of production. From
1999 to 2002, they harvested 18 to 22 bags (1 bag =
100 kg) per acre per growing season. For this harvest,
they needed 10 kg of seeds, 50 kg of DAB fertilizer and
50 kg of Urea fertilizer. They could sell a kilogramme (kg)
for 50 UGS (0.03 USD). Farmers estimate that they had
seasonal earnings of approximately 100,000 UGS (66
USD) per acre. In 2008, the members of the Bugiri District
Farmers Association received 200 UGS/kg (0.12 USD/kg),
but the outcome is only between 8 and 12 bags per acre
per growing season. Thus they have a seasonal income
per acre of 200,000 UGS (120 USD). Costs, however,
have increased faster than the selling price.
According to the farmers they would need:
10 kg of seeds 32,000 UGS
ox ploughing
DAB fertilizer
Urea fertilizer
40,000 UGS
85,000 UGS
85,000 UGS
2 x weeding labour 80,000 UGS
planting
harvesting
shelling
Total Amount
10,000 UGS
20,000 UGS
20,000 UGS
372,000 UGS (223 USD)
If the farmers would spend this on maize cultivation
they would make a loss of 172,000 UGS (103 USD) per
acre and season.
Farmers in the village Bukyansiko receive between only
100 and 150 UGS/kg (0.06 – 0.09 USD/kg) and harvest
only 7 bags per acre per season. None of the farmers
use fertilizers or pesticides and only two of them use
ox ploughing and buy hybrid seeds. They have seasonal
production costs of 40,000 UGS (24 USD). The selling
price at farm gate has remained stable since 2001, while
the buying price for maize flour has doubled from 500
UGS/kg (0.30 USD/kg) to 1,000 UGS/kg (0.60 USD/kg)
from the year 2007 to 2008. From 2005 – 2007 the
price was stable. Prices for maize flour have increased
tremendously from 2007 to 2008. While the price
for one kg levelled out to 600 UGS/kg (0.35 USD/kg)
in 2003, it increased suddenly to 1,000 UGS/kg in
2008. According to the FAO, this was caused by the
procurement of huge quantities of maize by Kenya and
Tanzania. Additionally, prices for energy and transport
have increased significantly.
29
The prices for non-hybrids have increased during the last
five years. While 1 kg of seeds was 700 UGS (0.41 USD)
in 2003, prices went up to 3,200 UGS (1.92 USD) in
2008. And the quality is sometimes bad. Hybrid seeds
were at 1,200 UGS/kg (0.84 USD/kg) in 1999, 2,000
UGS/kg (1.16 USD/kg) in 2002 and 2,800 UGS/kg (1.68
USD/kg) in 2008. The price of fertilizer followed a similar
pattern. While 1 kg was 500 UGS (0.29 USD) in 2003,
in 2008 the price was 1,900 UGS (1.14 USD). Fertilizers
are the inputs that cause the highest production costs.
Due to the negative relation between earnings and
production costs, many farmers have already dropped
out of commercial maize farming. They have diversified
to rice and groundnuts, which have a better market.
At the same time, the selling price at farm gate hasn’t
really changed since 2003. Since then it has stayed
at about 200 UGS/kg (0.12 USD/kg). Farmers get the
highest prices in March and September when the school
semester starts and the demand for maize is high,
because schools need it to prepare students’ meals.
But farmers cannot store maize until that time, because
insects easily invade it.
The millers buy one kg of maize for 450 UGS (0.27 USD)
during the off-season. During harvest season they pay
less 14 . Out of a bag of 100 kg, the middlemen make 1,000
UGS (0.60 USD) profit. Millers sell maize flour for 750-
800 UGS/kg (0.45 – 0.48 USD/kg). The price decreases for
larger quantities. For a bag of 100 kg, millers take 35,000
UGS (21 USD). Since boarding schools do not pay on time
of supply but only at the end of a term middlemen demand
a higher price of 900 UGS/kg from them (0.54 USD/
kg). In Kampala, they get 820 UGS/kg (0.49 USD/kg) cash.
Millers give a commission to young boys to sell the maize
flour. Millers are aware that there are many competitors.
They do not control the quality of maize flour and have
never sold maize to the WFP. Millers are aware that traders
from other countries buy maize flour in Kampala, but
according to them, they do not buy in Bugiri.
When a farmer brings maize, including maize bran, for
milling and takes it back to his farm then the price is 100
UGS/kg (0.06 USD/kg). When the farmer wants to leave
the maize bran, then the price is 80 UGS/kg (0.05 USD/
kg). A miller processes 80 bags per day (24 hours) – if
there is no loss of electricity. He employs three workers
for that the processing. None of the millers in Bugiri
has a generator. Costs for electricity are 500 UGS/unit
(0.30 USD/unit). They need 12 units to process 100 kg,
which costs6,000 UGS (3.60 USD). One of the millers
had a electricity bill for 70 mio. Millers get loans from
banks, but conditions of payment are not favourable for
them. Even the most successful miller had lost his house
to the bank due to high interest rates.
The highest household expenditures of farmers in
Bugiri district are medical care, followed by food and
education. Those three items consume 70 percent of
the farmers’ income.
7.4 Gender
In general, women do most work at the farm. While the
men do bush clearing, ox ploughing, planting, applying
of fertilizer, and harvesting, the women do planting,
weeding, harvesting, applying of fertilizer, drying and
shelling. But there are also families where the women
do all the work and men perform just the selling and
control the money. In most of the families, men make
the decisions on how the money is spent. Therefore,
women depend financially on their husbands.
According to the men, women want them to take the
lead in the family. “Women have the attitude to ask the
men to take decisions.” Women have a different view.
They are not satisfied with the situation that they bear
most of the workload, but earn only little money and
do not own land. Some women run a small business to
earn their own money. They sell tomatoes or cabbage.
Although women do most of the work on the field they
do not wear protective clothes like gumboots, while
some of their husbands do.
In the past, women organisations existed to support
women economically. But those organisations died off
due to low selling prices at the market. None of the
interviewed women are members of Bugiri District
Farmers Association, but some of their men are.
According to the women, domestic violence is common.
Many of the women are beaten when they use their
husband’s money to buy food or soap, even in times of
famine.
While the men stated, that during the meals at home
the husbands are served last, the women said that
the husbands are served first. Both agreed that his
plate is fuller than the plates of the other household
members. Women say that fill their mens’ plates higher
to encourage their husbands to buy more food.
To improve their situation, the women wish to have
improved seeds, oxen for ploughing, ox ploughs, land
rights and an available market for their products,which
includes a clear policy to defend them in selling and
keeping the price stable.
Female farmer A
“My husband, I, and our five children are landless. We
have leased 1.5 acres from a farmer to grow maize
and groundnuts. I use traditional seeds because I
experienced losses when I tried the hybrids. We harvest
7-8 bags of maize per season of which we use 4 for home
consumption. I never received any training on agriculture.
We face food shortages from April to June. During those
times we eat posho, potatoes and groundnuts only once a
day. Sometimes I can take only tea with roasted grundnuts
the whole day. My husband does not help me to cultivate.
But we are a group of women who help each other. When
I’m in the field my children are alone at home.”
14 The price they indicated (150 UGS) was too low to be reasonable; otherwise
middlemen wouldn’t benefit at all.
30 The Right to Food of Milk and Maize Farmers
7.5 Food Security
There is strong evidence that farmers and their families
face hunger. Main periods of food shortage are from
April to June, and from October to December. This has
been the case as long as our interview partners can
remember. According to the farmers, the families that
suffer from food shortages mainly live around Bugiri
town. Most of the farmers in the village still eat twice
a day, but out of 12, three eat only once a day. Famine
affects even medium-scale farmers. In times of famine,
poor farmers used to work for fellow farmers who were
faring better to sustain their livelihoods.
Total land area in relation to the population is low, and
therefore land sizes are often too small to feed a family.
Additionally, the crop disease Stryga 15 has affected
production. To be food secure, farmers plant cassava
and potatoes
Farmers in the village faced hunger even at the time of
the investigative mission. The harvest in December 2007
was poor. Therefore, many farmers didn’t earn enough
money to feed their families. “We used to have three
meals, but now we have only one.”
Members of Bugiri District Farmers Association, however,
claim to be food secure. Some said that they even assist
their hungry neighbours with food.
Poverty in Bugiri district forces young people to migrate
to urban centres to find employment in factories. “For
the youth, farming means to remain in poverty. And
when they go to the cities they never come back.”
Farmers from Bukyansiko reported that so far the young
people have not left the village. But they are aware that
the district faces this problem.
Millers reported that only those with large families suffer
from food shortages.
Small scale maize farmers’ desire the
following from the Government
The male farmers wish for:
• One tractor for the sub-county
• Supply of inputs (fertilizers, etc.)
• Better prices
• Better market access through processing, packaging,
etc.
• A food safety net scheme whereby Government buys
maize at minimum prices and redistributes it during
famine
• Reduction of high interest rates
The female farmers wish for:
• Improved seeds
• Oxen and oxploughs
• A policy to protect women against men so that they
can market their goods
• Land rights
• An available y market for their products
• Stable prices
7.6 Findings Bugiri
There is no impact of EU-policy on the Bugiri maize sector.
None of the interviewed persons had information about
imported maize from EU. They only suspected that the
WFP buys imported maize instead of local maize.
There is an alarmingly high level of hunger and malnutrition
among small-scale maize farmers in the village of
Bukyansiko in Bugiri District. Although small-scale farmers
acknowledge that there is a market for maize, they
express the wish to shift to other crops due to low farm
gate prices, which hardly cover their production costs.
Before harvest, between April and June, families of
smallholders suffer food shortages and hunger. Most of
those affected are women. They reportedly face discrimination
regarding food consumption while they shoulder
the biggest part of the workload in food production.
The consumer price of maize has doubled in the last year
while the price at farm gate has remained stable. This
causes a risk of food security. Medium- scale farmers do
not face hunger, but individual interviews showed that
they have to cut down on food before harvest. Small
scale farmers are disadvantaged since they get lower
prices for maize than medium-scale farmers.
Women hardly have access to land since they can neither
inherit it by tradition nor by law. As they lack the right to
inherit land they depend on their husbands or must lease
land to acquire it. Furthermore, they have no access to
the market since their husbands take all harvested maize
to sell it. Thus, they cannot generate income out of their
maize production. Additionally, they face domestic violence
even when they try to feed the family.
15 Stryga reduces nutrients in the soil. It can stay in the soil for over 20 years.
31
Production of maize has gone down due to the Stryga
disease and due to the deteriorating quality of seeds and
fertilizers since liberalisation of the market. At the same
time, production costs have increased tremendously
since privatisation of input supplies.
Furthermore, farmers do not have access to credits
since loan conditions are not favourable for them. That
is one reason why they cannot take advantage of the
purchasing policy of WFP.
There is a lack of market information for farmers. They do
not know the prices on the national level. Additionally,
since the cooperatives have been destroyed, every
farmer bargains on his or her own. Both factors diminish
the bargaining power of farmers. The governmental
programme to promote marketing organisations does
not reach the interviewed smallholder farmers yet. They
get lower prices than the medium-scale farmers.
Farmers are neither well informed about national and
international policies like the current boom of agrofuels.
Thus, they can hardly adapt timely to market demands.
Even the district administration concluded that
deregulation of the maize sector has failed.
Only large-scale farmers and traders seem to benefit
from the deregulation of the market - among them the
President’s family. While President Museveni himself
owns a company, which supplies farming inputs, one of
his daughters is a large-scale maize trader.
To summarize, in the course of deregulation, risks
within the maize supply chain and risks of food security
have shifted towards farmers and benefits have shifted
towards traders.
8. Impact of EU Agricultural and
Trade Policies
So far, a direct impact of EU agricultural trade policy
on the interviewed small-scale maize farmers could not
be found. Current imports of European dairy products
do not compete directly with the products of small
and medium dairy farmers, as these imported products
usually do not enter the informal markets. However,
studies as well as interviews with experts, retailers and
government officials indicate that imports of processed
dairy products like milk powder, butter, cheese and
yoghurt together already represent about 50 percent of
the formal dairy supply, partly as a result of the rise in
supermarkets in Kampala. The EU is the third biggest
external supplier of dairy products for Uganda.
The market for processed milk products have been
growing quite fast together with the growth of
supermarkets in Kampala. Supermarket managers
confirmed the sales of imported milk products are
increasing much faster than for local milk. It is difficult
to understand why milk products are imported in large
quantities, when 100,000 l of local milk are poured out
(wasted) on average every day. There is a danger that
imports impede the development of the domestic dairy
industry and thereby hinder the progressive fulfilment of
the right to food of smallholder dairy farmers.
Even though direct European imports are not the main
share of Ugandan imports, there is some evidence that
European imports in South Africa and Kenya indirectly
lead to an increase of Ugandan imports coming from
these countries as well. The fact that the EU has
increased and is further increasing the milk quota and
recently reintroduced export subsidies on dairy products,
raises fears that Ugandan dairy farmers will face more
competition from the EU in the future.
Dairy imports from the EU might significantly increase in
the future as a result of the ongoing reform of the EU
milk market regime and the framework EPA inititated in
November 2007 between the EU and the East African
Community (EAC). This might happen because:
• In 2008,the EU decided to increase its milk quota by
2 percent, which, according to its own projections,
will allow for a significant increase in milk powder
production and exports. In November 2008, the EU
Council decided to further increase the quota by 1
percent annually until 2013, after which the quota
system would be abolished entirely. This would
pave the way for unlimited production and exports.
It is especially concerning that, in the Health Check
decision in November 2008, the EC has kept the
door open for the maintenance of the instrument
of export subsidies even after 2013, even though
in the WTO negotiations, it had already committed
itself to end these subsidies by 2013. Contrary to this
commitment, the EC reintroduced export subsidies in
January 2009. The EC thereby accelerates the rapid
downwards trend of international dairy prices and
increases the danger of import surges.
32 The Right to Food of Milk and Maize Farmers
• Even though the EPA does not require a further
reduction of import tariffs on European dairy imports,
a standstill clause does not allow for increasing tariffs
in the future except with the consent of the European
Commission. This provision eliminates the policy
space previously granted within the WTO up to the
bound level of 80 percent. While other countries, like
Russia, as a reaction to the reintroduction of export
subsidies, have increased import tariffs, Ugandan
dairy tariffs will have to remain at the currently low
applied level of 25 percent. Uganda has lost the policy
space that might be necessary to properly protect the
market and the right to adequate food of Ugandan
dairy farmers in the near future.
9. Recommendations
Based on the findings, the recommendation to the EU
and EAC are:
1. to conduct a Human Rights Impact Assessment on
the EPA before any further negotiations are held –
as recommended by the Special Rapporteur on the
Right to Food, Oliver De Schutter, in his recent report
to the Human Rights Council on the relationship
between trade agreements under WTO and the
State’s obligation to respect the human right to food
(De Schutter 2009).
2. to revise the Interim EPA: Both the EU and the EAC
have to make sure that the EPA will not limit the
policy space of Uganda to protect and promote the
right to adequate food for small-scale farmers. No
liberalisation commitment or standstill clause shall
hinder the Ugandan Government to increase tariffs
whenever European imports threaten market access
and incomes of food insecure people. The revision
process, as well as further EPA negotiations, must
allow substantial participation of parliaments and
civil society organisations. We urgently request the
EU not to put pressure on the EAC to conclude a
comprehensive EPA, which would include services,
investment, intellectual property rights or public
procurement;
3. to revise the EU decision to increase the milk quota
by 2 percent. Furthermore, we recommend to
maintain the milk quota system beyond 2013 and to
phase out export subsidies immediately. The recently
reintroduced export subsidies need to be withdrawn.
The EU must make sure that surplus dairy products
are not exported to Uganda at dumping prices.
4. to support smallholder food production in its desire
for official development assistance. Smallholder
farmers feed the people and should get more support
from governments and donors.
The World Food Programme should increase its efforts
to purchase maize from Ugandan smallholder farmers.
Measures could be:
• to pay on the spot,
• to assist the Ugandan Government to set up a credit
scheme, which benefits smallholders, and which is
accessible to them
• to accept lower quantities than 50 t.
The Ugandan Government should:
1. increase the efforts to facilitate access to internal
markets through self determined marketing groups of
farmers. These marketing groups will likely strengthen
the bargaining power, especially of smallholders,
towards informal vendors or middlemen and facilitate
access to formal markets at fair prices that allow for a
life in dignity and free from hunger;
2. increase the public spending on agriculture from 4
to 10 percent, as agreed in the Maputo Declaration.
Uganda, with support of its development partners,
should put special emphasis on promoting the access
of smallholder farmers to inputs like high quality
seeds (locally adapted in close cooperation with local
communities), extension services, low interest loans,
storing and processing facilities at affordable prices.
3. guarantee women the right to inherit land by law.
This law should be developed together with women’s
rights organisations and be enforced by public
awareness raising campaigns and trainings for local
authorities and land registrars. Furthermore, a policy
needs to be put in place to fight domestic violence.
4. increase its efforts to improve quality of public schools
and to reduce or to abolish school fees of secondary
schools. School fees are the highest expenditures
of the farmers and might discourage them from
sending their children to secondary school. A higher
educational level will help the future generation of
farmers to improve their production and gain more
bargaining power against traders.
33
References
• Action Aid International Uganda et.al. 2007: CSO
Petition, Uganda Civil Society Organisations Petition
Presented to the Deputy Speaker of the Parliament
of the Republic of Uganda, Achieving sustainable
development through trade: Rethinking economic
partnership agreements, Kampala 1 st October 2007.
• Baffoe, John. K. 2000: Structural adjustment and
agriculture in Uganda, Working Paper 149, Geneva,
International Labour Office,
public/english/dialogue/sector/papers/uganstru/
index.htm#_Toc478975713 [12.08.2008].
• Bakunda, Geoffrey 2006: The Impact of Trade
Liberalisation on Poverty in Uganda, A Perception
Study on the Dairy and Maize Sub-Sectors, Final
Report submitted to DENIVA for CUTS-TDP Project.
• Bertow, Kerstin/Schultheis, Antje 2007: Impact of
EU’s Agricultural Trade Policy on Smallholders in
Africa, Bonn, Germanwatch.
• Blake, Adam/McKay, Andrew/Morrissey, Oliver
2007: The Impact on Uganda of Agricultural Trade
Liberalisation, Nottingham, Centre for Research
in Economic Development and International Tade
(CREDIT).
• Bugiri District Advocacy Coalition (BUDAC) 2006:
Summarized Baseline Survey Report on Food Security
Situatoin and Access to Market, aimed at Establishing
the Food Security Situation and Access to Market
Levels in Bugiri District.
• Committee on Economic, Social and Cultural Rights
1999: General Comment No. 12, The Right to
Adequate Food, Geneva, United Nations.
• Dairy Development Authority 2004: Annual Report
2003/2004, Ministry of Agriculture, Animal Industry
and Fisheries
• De Schutter, Olivier 2009: Promotion and Protection
of All Human Rights, Civil, Political, Economic,
Social and Cultural Rights, Including the Right to
Development, Report of the Special Rapporteur on
the right to food, United Nations, Human Rights
Council, 4 February 2009, A/HRC/10/5/Add.2.
• DENIVA 2006: Impact of the Economic Partnership
Agreement (EPAs) with the European Union on
the Ugandan Economy, A Synthesis of Existing EPA
Impact Studies.
• East African Community/European Community
2007: Agreement Establishing a Framework for an
Economic Partnership Agreement between the east
African Community Partner States on One Part and
the European Community and its Members States on
the Other Part,
framework_EPA_initialled.doc [02.04.2008].
• European Commission Directorate General for Trade
2007: Update: Interim Economic Partnership Agreements,
Trade Policy in Practice, 19 December 2007.
• European Commission 2008: Proposal for a council
regulation establishing common rules for direct
support schemes for farmers under the common
agricultural policy and establishing certain support
schemes for farmers. Brussels, 20/5/2008
•
en.pdf [20.08.2008]
•
• FAO 2006: Import Surges: What are their external
causes? FAO Briefs on Import Surges No. 3, Rome,.
pdf [02.03.2009].
• FAO 2008: Food Outlook November 2008, Rome:.
htm#31
• FIAN International 2003: Trade and Human Rights,
Human Rights Come Before Trade Agreements,
Heidelberg.
• Kintu, James 2007: Realization of the Right to
Adequate Food – the Case for Uganda, unpublished
background paper for the FIAN-seminar: Promoting
the Right to Food and the Right to Food Guidelines
- Concrete implications for national food security
efforts in Uganda.
• Ministry of Tourism, Trade and Industry (MTTI) 2008:
An Overview of the East African Community – EU
Framework Economic Partnership Agreement (EPA);
What is in it for Uganda?
• Mwebaze, Thomas 2004: Profitability of Dairy Farming
in Uganda, Focussing on the Factors of Production
and Marketing, Linz, Johannes Kepler University.
th
• NAADS 2006: Newsletter, December 20 , http://
naads.or.ug/manage/publications/newsletter%20
dec%202006.pdf [19.01.2009].
• Oxfam GB in Uganda et.al. 2008: Petition to
Parliament, Achieve Sustainable Development
Through Trade: Rethinking the Economic Partners
Agreements (EPAs), Kampala, 11 th March 2008.
• Oxfam Germany 2009: Fact Sheet: Hintergrundinfos
EU-Milch-Politik, Berlin.
• Paasch, Armin 2007: Agricultural Trade and the
Human Right to Adequate Food, Methodology
Guide for Human Rights based Case Studies on
Trade Policies, Draft, Geneva, Ecumenical Advocacy
Alliance.
• RATES Center 2003: Maize Market Assessment And
Baseline Study for Uganda, Nairobi.
34 The Right to Food of Milk and Maize Farmers
• Reichert, Tobias u.a. 2009: Entwurf des
Hintergrundpapier zu Interim EPAs mit Schwerpunkt
Afrika; Germanwatch.
• Rukundo, Peter Milton 2009: Empowering Civil
Society to Monitor the Right to Food; A Case Study
Report on the Ugandan Experience, FIAN/WHH.
• SEATINI 2005a: Achieving fair-trade through the
global partnership for development under the MDG
framework, A case for Uganda.
• SEATINI 2005b: Mainstreaming Human Rights and
Social Justice in the Multilateral Trading System
(MST).
• SEATINI 2008a: The Implications and Challenges of
Implementing an Economic Partnership Agreement
for Uganda with Particular Reference to the Market
Access Cluster.
• SEATINI 2008b: Implications of the EAC-EU Economic
Partnership Agreement for Uganda’s Fisheries Sector.
• Uganda Joint Christian Council (UJCC) et. al. 2007:
CSO statement on the Joint Conclusion of the 1tsd
East-Africa Community - European Commission
Meeting on Negotiations on an Economic Partnership
Agreement (EPA) 14 th November Brussels.
• Werth, Alexander a.o. 2005: Sectoral and Analytical
Studies to Guide Uganda in the EPA Negotiations,
Final Report submitted to Uganda Programme for
Trade Opportunities and Policy, Kampala.
• Ziegler, Jean 2005: Economic, Social and Cultural
Rights, The Right to Food, United Nations,
Commission on Human Rights, 24 January 2005, E/
CN.4/2005/47.
35
Annex I: Questionnaire
Questionnaire for semi-structured interviews
A) Interview with resource persons/experts
belonging to important reference groups outside
the community itself (“the most inside of the
outsiders”)
0. Personal data: Name, function, institution
1. Basic data on milk and maize: farming, commerce
and consumption
1.1 Agro-economic structure of production (per
regions & per type of producers)
1.2 Processing and marketing structure
1.3 Development of production, prices and
markets since the 1990s (including major
peaks)
1.4 Development of imports and their impact
on national prices (farm gate prices and
consumer prices)
1.5 Development of national consumption
1.6 Geographical origin of imports and possible
relevance of (trade in) agriculture policies
of the exporting countries (including
dumping).
2. Policies
2.1 Trade in agriculture policies: Liberalisation of
the milk and maize market (how and when)
2.2 Domestic agriculture policies: Protection of
the national producers (how and when)
2.3 Role of political actors and specific
responsibilities: (government, political
parties, influence of business, social groups,
international actors (World Bank, IMF, WTO,
others)
2.4 Trade Strategy (Uganda’s policy in EAC, esp.
common external tariff)
2.5 Food security strategy (and relation to EPA
negotiations)
3. Consequences and effects (in the past and
perception of future developments)
3.1 Beneficiaries of the policies described above
3.2 Effects of these policies on Ugandan
society (urban/rural segments of society,
gender effects, producers/consumers, most
vulnerable groups)
3.3 Effects on the community level: producers/
consumers
3.4 Hunger, malnutrition, food insecurity (when,
where, in which context) in relation to the
market liberalisation
Statistical data required (1990 – 2008)
- National production
- Destination of produce & processing
- National consumption
- imports & origin of imports
- exports
- prices (producer prices, consumer prices and import
prices)
- Tariffs and quota systems
- Poverty rates - for specific groups
- Food insecurity and chronic malnutrition – broken
down to vulnerable groups
B) Interview with experts/community leaders
inside the community
0. Personal data: Name, function, institution
1. General information
1.1 Name and location of the community
1.2 Formal status of the community and the
producers (cooperative, association etc.)
1.3 Number of persons/families living in the
community/belonging to the group
1.4 Total number of farmers in the community /
number of female producers. How many are
involved in milk/maize
1.5 Existing infrastructure: streets, schools,
health post, drinking water, sanitation,
electricity etc.
1.6 Community history (regional context,
migration, conflicts, natural disaster,
environmental problems etc.)
2. Community organization
2.1 Political organization / local authorities /
societal leadership
2.2 Organization of the milk/maize production
(including gender relations)
2.3 Production / Marketing
2.4 Collective / Individual (Mechanisms of
redistribution, collective assistance to the
most vulnerable)
2.5 Land tenure / conflicts
36 The Right to Food of Milk and Maize Farmers
3. Agricultural production
3.1 Quantity and value of milk/maize production
in relation to other agricultural products
3.2 Type of production (agro-industrial/
sustainable)
3.3 Aim of production (auto consumption /
market-oriented production)
3.4 Commercial & trade structure / buyers of the
milk/maize
3.5 Agro-technical assistance/credits/inputs
3.6 Marketing support programs
3.7 Profitability calculation
4 Change since 1990
4. 1 Development of production and marketing
since 1990
4.2 Collapse of production / farm gate prices
/ markets during 1990 – 2008, including
explication of the reasons from the
community’s viewpoint
4.3 Role of imports within the reasons
4.4 Have the collapses described above been of
general or of specific nature (describe how
the neighbouring communities / the region /
the nation have been affected)
4.5 Responsibilities and key factors for these
collapses
4.6 Alternative sources of livelihood / economic/
agricultural options for the community
5. Effects of the changing milk/maize market
5.1 At the economic/agro-economic level
(hunger / change in crops / land tenure)
5.2 At the social level (forms and functions
of organizational structures / migration /
gender / youth / elderly)
5.3 Vulnerable groups in the community
2. Production
2.1 Current milk/maize production
2.2 Development of production since 1990
2.3 Relationship between self consumption and
market oriented production
2.4 Collapse of production / farm gate prices
/ markets during 1990 – 2008, including
explication of the reasons from the viewpoint
of the family
2.5 Total family income / income from milk/
maize production and changes since 1990
2.6 Profitability calculation of milk/maize (if
possible: profitability in different periods
over the last years and in relation to market
liberalization)
2.7 Support, subsidies, extension services
provided by the government or other actors
3. Effects of the changing rice market
3.1 Hunger / malnutrition / food insecurity /
sources to get food
3.2 Consequences for production / impact on
rural development: changing crops, loss of
investments, loss of means of production
3.3 Purchasing power / change in consumption
patterns
3.4 Vulnerability of different family members
(men, women, boys and girls)
3.5 Economic alternatives inside and outside the
community / migration
C) Interview at the household level
0. Personal data: Name, sex, age, profession
1. Basic information
1.1 Family members, age, profession and sex
1.2 Since when you are living in the community
/ productive entity?
1.3 Size of productive land & where it is located
1.4 Type of land tenure / financial situation
(including possible indebtedness) / credits
1.5 Housing (house garden and agricultural land
nearby?)
37
Annex II: Persons interviewed
Expert Interview:
-- Geoffrey Bakunda
-- George Walusimbi-Mpanga
Focus Group Interview with Civil Society
-- Jacqueline Amongin, PAM
-- Miriam Talwisa, ACTADE
-- Mouson Rwakakamba, Uganda National Farmers
Federation
-- Happy James, Suswatch Network
-- Godfrey Ssali, SEATINI
-- Paul Walakila, UNBS
-- Caroline Mayiga Nabalema, Katosi Women
Development Trust
-- Olive Zaale Otete, LDR Consultants
-- Agnes Kirabo, VEDCO
-- Samuel Kasirye, SEATINI
-- Kaweese M.B., CAA
Focus Group Interview with Mbarara District
Farmers Association and Uganda Crane
Creameries Cooperative Union Ltd., Mbarara:
-- Tumwebaze Lauben, farmer
-- Rev. Canon Ganaafa, Rukaka d.f.c.s. ltd.
-- Dr. William Mwebembezi, vet. Officer
-- Moses Turyaramya, Chairman Uganda Crane
Creameries Cooperative Union
-- George Nuwagira, Vice Chairman Uganda Crane
Creameries Cooperative Union
-- Capt. Dick Kajugiira, treasurer Mbarara District
Farmers Association
-- Elly Karegire, Chairman Mbarara District Farmers
Association
-- Timothy K. Bitter, Chariman Kashari Dairy Farmers
Cooperative
Focus Group Interview with dairy farmers in
Nyakisharara
-- Edward Nyamalya
-- Peninah Besigye
-- A. Tibesigwa
-- Justus Mambo Kurinogira
-- Robert Kasasi Shokye
-- Benon Bwengye
-- Patrick Byaruhanga
-- Emmanuel Muzoora
-- Elly Beinomugisha
Expert Interview with representatives of Bugiri
District Farmers Association in Bugiri town:
Paul Oteba, Chairman
-- George Migero, Vice Chairman
-- James ?, Farmer
Focus Group Interviews with Bugiri District
Farmers Association in Bugiri town
-- Mugoya Awali Ogonzaki
-- Ekisa Longino, Hope Farmers Association
-- Nulu Namusoke
-- Rose Simuye
-- Joseph Wakhonya
-- Agnes Nangobi
-- Timothy Tibita
-- Sam Kyerekizibu
-- Awoli Mugoya, treasurer
-- Sulay Musenero, Tufungize farmers group
-- James Mangeni, advisor
-- Mutamba Mabango Twaha
-- George Migero
-- John Odongo
-- Richard Buyinza
-- Christopher Maka
-- Paul Oteba Opisai
-- Moses Makaka
-- Mutwalibu Kyebanbe
-- Henry Bageja
-- David Mudhalya
-- Sam Muhoya
-- Bane Nyende
Expert Interviews in Bugiri District Commercial
Office
-- Hussen Musikho (Commercial Officer)
-- Mulabya Esau (Assistant Commercial Officer)
-- Francis Ekiro Etomet (Chairman Production)
Focus Group Interviews in Bugiri with
representatives of small millers
-- Skiria Ddalaus Haji
-- Musoga Abdullah
-- Jakola Samwe
-- Hadji Asamwe
-- Lawrence Kiago
Expert Interviews in: Bukyansiko, Kasita Parish,
Nabukalu Sub-county, Bugiri District
-- George Migero, Vise Chairman of Bugiri District
Farmers Association
-- Musa Kabwangu, General Secretary of Local Council
and Chairman of Parish
Individual Interviews in: Bukyansiko, Kasita
Parish, Nabukalu Sub-county, Bugiri District
-- Skovia Timogiva
-- Acord Fatma
-- Mutumba Mohamad
-- Lukia Tibaga
38 The Right to Food of Milk and Maize Farmers
Focus group interviews in: Bukyansiko, Kasita
Parish, Nabukalu Sub-county, Bugiri District
-- with women:
Idah Mukama
Jane Mukana
Kekulina Mutumba
Fawuza Nawkreya
Zabiya Naigoga
Babuletenda
Fatuma Namuganza
Joy Mwondia
Pro Mutisi
Rose Namusabya
H. Nangobi
T. Namutamba
Zaniza Mutesi
Sarah Nabirye
Lulinja Musobya
-- with men
Lukungu Hussein
Bakumo Maliki
Kiremu Abumani
Mukama Jamal
Kaabwangu
Naluswa Senefansiyo
Mafaala Muhamad
Bagoye Wilson
Pasikali Katabagi
Were Fred
Wachana S.
Kasolo Mukamal
Kowa James
Ichuma
Migero George
Expert Interview: EU Office Uganda:
-- Alex Nakajjo
-- Uwe Bergheimer
Expert Interview: Ministry of Agriculture:
-- Kaasai Opolot, Commissioner for Crop Production
and Marketing
Expert Interview: FAO
-- Percy Msika
-- Charles Owach
39
FIAN INTERNATIONAL
Willy-Brandt-Platz 5
69115 Heidelberg, Germany
Tel.:+49-6221-6530030 | https://www.yumpu.com/en/document/view/27492830/the-right-to-food-of-milk-and-maize-farmers-uk-food-group | CC-MAIN-2019-43 | refinedweb | 25,402 | 54.02 |
TypeScript declaration file that allows using
import with
*.vue files. The primary use case is a bundler environment like Browserify with vueify. The file itself consists of 5 lines; this package is just for convenience.
This package requires TypeScript 2 and Vue.js 2, which ships with new type definitions in the Vue.js package itself. Both must be installed separately in your project, which allows choosing a suitable version.
Install:
npm install vue-typescript-import-dts --save-dev
Include it in the
types field of your
tsconfig.json
"compilerOptions":"types": "vue-typescript-import-dts"...
Then, it is possible to
import a
*.vue file:
Note: TypeScript will not type check, parse, or even verify the existence of the
.vue file: this project only instructs the TypeScript compiler to assume the import of 'something' that ends with
.vue succeeds and is a
Vue.ComponentOptions<Vue> object.
Please not that 3.0 of this package uses ES6
export default which also changes the import syntax to the example above. Please use version 2.0 if you prefer the CommonJS compatibility syntax:
// or
If you are using TypeScript 2 together with Vue.js 2, you might also be interested in | https://www.npmjs.com/package/vue-typescript-import-dts | CC-MAIN-2017-13 | refinedweb | 197 | 61.22 |
From ba7961f118f42ba9db7e5fba017270a257852ff3 Mon Sep 17 00:00:00 2001 From: Paolo Capriotti Date: Mon, 2 Jul 2012 11:52:39 +0100 Subject: [PATCH]. --- System/Posix/Unistd.hsc | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/System/Posix/Unistd.hsc b/System/Posix/Unistd.hsc index 7312dae..dfd2673 100644 --- a/System/Posix/Unistd.hsc +++ b/System/Posix/Unistd.hsc @@ -95,18 +95,28 @@ foreign import ccall unsafe "uname" -- | Sleep for the specified duration (in seconds). Returns the time remaining -- (if the sleep was interrupted by a signal, for example). -- --- GHC Note: the comment for 'usleep' also applies here. +-- /GHC Note/: 'Control.Concurrent. 'Control.Concurrent.threadDelay' has none of these shortcomings. -- sleep :: Int -> IO Int sleep 0 = return 0 sleep secs = do r <- c_sleep (fromIntegral secs); return (fromIntegral r) +#ifdef __GLASGOW_HASKELL__ +{-# WARNING sleep "This function has several shortcomings (see documentation). Please consider using Control.Concurrent.threadDelay instead." #-} +#endif + foreign import ccall safe "sleep" c_sleep :: CUInt -> IO CUInt -- | Sleep for the specified duration (in microseconds). -- --- GHC Note: 'Control.Concurrent.threadDelay' is a better choice. +-- /GHC Note/: 'Control.Concurrent.threadDelay' is a better choice. -- Without the @-threaded@ option, 'usleep' will block all other user -- threads. Even with the @-threaded@ option, 'usleep' requires a -- full OS thread to itself. 'Control.Concurrent.threadDelay' has @@ -134,6 +144,7 @@ foreign import ccall safe "usleep" -- | Sleep for the specified duration (in nanoseconds) -- +-- /GHC Note/: the comment for 'usleep' also applies here. nanosleep :: Integer -> IO () #ifndef HAVE_NANOSLEEP nanosleep = error "nanosleep: not available on this platform" -- 1.7.9.5 | https://ghc.haskell.org/trac/ghc/raw-attachment/ticket/7032/7032.patch | CC-MAIN-2015-40 | refinedweb | 253 | 52.26 |
Hi all,
We are having a problem with Axis Java (release 1.1) code that we re-use
in WSDL2Ws tool. The problem seems to be with symbolTable package.
Basically the problem is that when we have following segment of schema in
a wsdl
> <xsd:element
the BaseType created in the symbolTable will have namespaceURI as
"" where as it should be
""
But this problem does not occur in any of the following situations,
1. minOccurs attribute is not there
2. minOccurs not equal to "0"
3. there is maxOccurs= greater than "1"
see for complete WSDL.
but this happens for all basic types except "xsd:string".
Is this deleberately done ?. if so please explain why.
If this is a bug, is it fixed in latest Axis Java code ?
Your help is very much appreciated,
Thanks,
Susantha.
---------------------------- Original Message ----------------------------
Subject: RE: DOC/LIT : Some new patches
From: susantha@opensource.lk
Date: Fri, March 12, 2004 1:42 am
To: "Apache AXIS C Developers List" <axis-c-dev@ws.apache.org>
--------------------------------------------------------------------------
Hi Jean-Yves,
I ran WSDL2Ws tool with your wsdl and found that its strange. This happens
for all basic types except xsd:string. But if you remove minOccurs="0" or
make "1" or have maxOccurs="n" where n>1 it works fine.
I am looking at the problem and it seems something wrong with the Axis
Java libraries (.jars). I will let you know once debugged well.
Thanks,
Susantha.
> Hi,
>
> After looking about my JRE and classpath I finally found the condition
for this issue. This is this kind of declaration that failed with the
current CVS implementation :
>
> ...
> <xsd:element
> ...
>
> I don't know why the Axis Java runtime build a BasicType with a
> namespace uri ("") that difer
from the xsd declaration (""). I haven't
downloaded the whole java source from Axis Java (i used axis java 1.1
jars).
>
> Testcase here :
>
>
> So comparing namespaces will failed.
>
> Have you got an idea to solve this issue ?
> Should the jars from axis 1.2 alpha will correct this issue ?
>
> By now the only way to bypass is to comparing the name only.
>
> Regard,
>
> Jean-Yves
> | http://mail-archives.apache.org/mod_mbox/axis-c-dev/200403.mbox/%3C3583.203.94.74.174.1079077411.squirrel@webmail5.pair.com%3E | CC-MAIN-2018-30 | refinedweb | 354 | 76.42 |
WSFlush (C Function)
Details
- If you call WSNextPacket() or any of the WSGet functions, then WSFlush() will be called automatically.
- If you call WSReady(), then you need to call WSFlush() first in order to ensure that any necessary outgoing data has been sent.
- WSFlush() returns 0 in the event of an error, and a nonzero value if the function succeeds.
- Use WSError() to retrieve the error code if WSFlush() fails.
- WSFlush() is declared in the WSTP header file wstp.h.
Examples
Basic Examples (1)
#include "wstp.h"
/* send the expression Integrate[1/x^2,x] to a link */
void f(WSLINK lp)
{
if(! WSPutFunction(lp, "EvaluatePacket", 1))
{ /* unable to put the function to lp */ }
if(! WSPutFunction(lp, "ToExpression", 1))
{ /* unable to put the function to lp */ }
if(! WSPutString(lp, "Integrate[1/x^2, x]"))
{ /* unable to put the string to lp */ }
if(! WSEndPacket(lp))
{ /* unable to put the end of packet indicator to lp */ }
if(! WSFlush(lp))
{ /* unable to flush the buffered data in lp */ }
} | https://reference.wolfram.com/language/ref/c/WSFlush.html | CC-MAIN-2019-22 | refinedweb | 165 | 67.25 |
Recently Browsing 0 members
No registered users viewing this page.
Similar Content
- By dejhost
Hi.
I am trying to automate a software called "LabelImg" ().
My autoit-script is started once I selected a folder with images within LabelImg. Pressing the button "Next Image" or pressing the shortcut "d" () jumps to the next image in the selected folder. This shall happen once per second.
#include <Misc.au3> #include <MsgBoxConstants.au3> #include <AutoItConstants.au3> Opt("WinTitleMatchMode", 1) Local $hDLL = DllOpen("user32.dll") While 1 If _IsPressed("1B", $hDLL) Then ExitLoop Else Local $temp = WinActivate("labelImg") ConsoleWrite($temp & @CRLF) If WinActivate("labelImg") Then ConsoleWrite("All Set!" & @CRLF) EndIf ;Send("d") Local $temp = MouseClick($MOUSE_CLICK_RIGHT, 50, 200) If $temp <> 1 Then MsgBox(1, "$temp", $temp) ExitLoop EndIf Sleep(1000) EndIf WEnd DllClose($hDLL) So the Send ("d")-command and the MouseClick are alternative methods to jump to the next image. Both fail.
Both ConsoleWrite's deliver proper feedback (I continiously get the handle and "All set" ).
Could you tell me what I'm doing wrong?
Thank you.
-
-
Recommended Posts
You need to be a member in order to leave a comment
Sign up for a new account in our community. It's easy!Register a new account
Already have an account? Sign in here.Sign In Now | https://www.autoitscript.com/forum/topic/199492-mouse-click-doesnt-work-moved/ | CC-MAIN-2022-05 | refinedweb | 213 | 60.11 |
A multi-threading implementation of Python gzip module
Project description
mgzip
A multi-threading implement of Python gzip module
Using a block indexed GZIP file format to enable compress and decompress in parallel. This implement use 'FEXTRA' to record the index of compressed member, which is defined in offical GZIP file format specification version 4.3, so it is fully compatible with normal GZIP implement.
This module is ~25X faster for compression and ~7X faster for decompression (limited by IO and Python implementation) with a 24 CPUs computer.
In theoretical, compression and decompression acceleration should be linear according to the CPU cores. In fact, the performance is limited by IO and program language implementation.
Usage
Use same method as gzip module
import mgzip s = "a big string..." ## Use 8 threads to compress. ## None or 0 means using all CPUs (default) ## Compression block size is set to 200MB with mgzip.open("test.txt.gz", "wt", thread=8, blocksize=2*10**8) as fw: fw.write(s) with mgzip.open("test.txt.gz", "rt", thread=8) as fr: assert fr.read(len(s)) == s
Performance
Compression:
Decompression:
Brenchmarked on a 24 cores, 48 threads server (Xeon(R) CPU E5-2650 v4 @ 2.20GHz) with 8.0GB FASTQ text file.
Using parameters thread=42 and blocksize=200000000
Warning
This package only replace the 'GzipFile' class and 'open', 'compress', 'decompress' functions of standard gzip module. It is not well tested for other class and function.
As the first release version, some features are not yet supported, such as seek() and tell(). Any contribution or improvement is appreciated.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/mgzip/ | CC-MAIN-2021-04 | refinedweb | 292 | 58.69 |
public class Solution { int[] ori; int[] ran; public Solution(int[] nums) { ori = nums; ran = new int[nums.length]; for(int i=0;i<nums.length;i++) ran[i] = nums[i]; } public int[] reset() { return ori; } public int[] shuffle() { if(ori.length<2) return ran; int a = new Random().nextInt(ori.length); int b = new Random().nextInt(ori.length); int t = ran[a]; ran[a] = ran[b]; ran[b] = t; return ran; } }
Shuffling an array is not simply randomly swapping two positions... and of course it is faster than 87.5%.
@dingty Thanks for pointing out.
I was also not sure about the correctness of the algorithm, while it passed the OJ.
Can we get a proof of correctness of my algorithm, to say it is a valid/invalid randomization algorithm?
"about the correctness of the algorithm" there is no way to check randomness, only to make sure you are not returning unmodified array every time shuffle gets called.
"Can we get a proof of correctness of my algorithm," can you show the probability of each element in position i being stored in position j (j can be any position including i) is 1/n?
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/65191/my-21-line-simple-solution-faster-than-87-5 | CC-MAIN-2017-34 | refinedweb | 210 | 65.62 |
Street names in Poland
This map was simple to create but it was more difficult to obtain the data for it.
I downloaded the streets data from the polish Main Office of Geodesy and Cartography. I had sheets with thousands of rows containing street data for each voivideship (first level of adminsitration vision in Poland).
To count the number of each street for each region I wrote simple but dirty Python script.
It might be easier using library like Pandas but for such small task I decided not to use any external libraries.
Nothing special but with this script I managed to create this map in two hours.
Here's the script:
import csv import os csvDir = os.listdir(r"path_to_directory_with_csv_files\test") pathBase = r"path_to_main_project_directory\dane" directory = r"path_to_directory_with_csv_files\test" def writeCsv(name): with open(pathBase + '/test/' + name + '.csv') as csvInput, open(pathBase + '/result' + r'\edited_' + name + '.csv', 'w', newline='') as csvOutput: reader = csv.reader(csvInput, delimiter=';') writer = csv.writer(csvOutput, delimiter=';') streets = [] streetsCount = {} for row in reader: column = list(row[i] for i in [7, 8]) streets.append((f'{column[1]} {column[0]}').strip()) for street in streets: if street in streetsCount: streetsCount[street] += 1 else: streetsCount[street] = 1 for key in streetsCount: writer.writerow([key, streetsCount[key]]) for file in csvDir: filename = os.path.splitext(file)[0] writeCsv(filename)
| https://michalmuszynski.com/work/street-names-in-poland/ | CC-MAIN-2022-33 | refinedweb | 221 | 57.98 |
Gentoo Wiki:Suggestions
Feel free to add suggestions for our Wiki on this page. To add a new topic, click on the "Add topic" page tab. Remember to sign your suggestion with
--~~~~, or the "Signature and timestamp" button
in the editor toolbar. See Help:Signatures.
Archive
For completed discussion see Archive subpage.
Relationship with existing Gentoo documentation
Will it be possible to somehow incorporate the existing Gentoo documentation into this wiki, perhaps have this as the user editable version, with revisions pushed to the guidexml docs with are the official "reference" and are verified to be of a certain quality by the documentation team. --Mark alec 13:53, 26 September 2011 (UTC)
- I agree. This would relieve Gentoo Documentation from a majority of documentation, such as GCC Upgrade is a good example (although this upgrading has been resolved). This would also provide Gentoo users more recent and up-to-date documentation. The only documentation I see as toss-up, are the Gentoo Install documents and Ebuild Writing documents -- which should remain standardized. However, the pro with going Wiki on these, the Gentoo Documentation group would only need to take a snapshot of a current wiki -- similar to Gentoo and Sabayon or System RescueCD. ;-) This is really long over due, but not too late! Signed: Roger 19:00, 15 November 2011 (UTC)
- Keep in mind, that the doc team is not interested, see ML column at Gentoo Wiki:Progress#Content / Scope
- Astaecker 19:14, 15 November 2011 (UTC)
- It isn't about being against anything. License-wise, this should be okay, since the current license in use by the majority of documents is the same, just a lower version. From the legal document of the CC-BY-SA, it mentions something about allowing later versions so I believe that we can use the content of the gentoo documents and put it under the 3.0 version on the wiki. I also don't mind that this is done, but for a documentation development point-of-view, keeping the master in a wiki might not be a best option. There is quite some documentation development being done off-line (used to be even more offline than online, but things change ;-) I would personally rather see more specific documents be moved from the main site to the wiki (such as the logcheck one).
- --SwifT 17:11, 26 December 2011 (UTC)
- /start rant
- Okay, I am new to the Gentoo project and the conflicting/outdated documentation is driving me crazy, specifically all the X.org stuff only using nvidia-drivers and I apparently have to use nouveau since nvidia-drivers don't support GeForce2 according to some documentation, and I came across one document that said that it does support it. I could probably use the man pages, but the docs are supposed to make setup easy. There are a few other examples, but that one is the biggest.
- /end rant
- So, since there is no apparent page to explain this, I have set up a (hopefully) temporary "inconsistency-/differences-between-versions page" for the Documentation just before I wrote this comment. I am just posting to draw attention to it and let people know that it is there.
- post scriptum ad persona de Gentoo/Documentation: please, PLEASE, use this page to edit documentation -- Preceding unsigned comment by User:Jamiahx
- If you don't know which driver to use, what you should do is ask on the Gentoo Forums, and once you have the answer, edit the wiki. For official documentation, file a documentation bug. If there is a discrepancy in the wiki, it's probably better to add it to its Talk Page. (Although I think having some consistent way of reporting problems in the wiki like you outlined is a good idea) --Alec 20:58, 31 March 2012 (UTC)
- I think the only thing still holding us back a bit for moving most documentation to the wiki would be the need for translations. If there is anything that I can help with to find a way of supporting translations on the wiki, I'd love to hear it. --SwifT (talk) 06:39, 15 March 2013 )
- I created a comparison table of the since now proposed solutions. Astaecker 11:29, 27 July 2012 (UTC)
'Link' template for translated pages
{{Link}} solves a problem with linking to translated pages, see the Rationale section. I would like to have some feedback before moving the template in the Template namespace. Astaecker 15:19, 29 October 2011 (UTC)
Templates need to be localized
Text formatting templates, such as Template:Note or Template:Warning, need to be either automatically localized, or need standard localized versions (e.g. something like "Template:Note/ru" or "Template:Примечание") available for translators to insert manually. — tetromino 19:22, 11 November 2011 (UTC)
- I experimented with it. Some solutions:
- Separation of code and text by using subpages. The templates can be protected and translators can still update the text in the subpages.
- For automatic localization using subpages I found no way to address the subpage (relativ or absolute) inside the template to fetch the translations, because after transclusion all variables ({{BASEPAGENAME}}, etc.) apply then to the target page.
- Translate the text (and only the text) with the translate extension works, but the <translate> tags around the text of the original english template will get transcluded and displayed in the target page. No problem with translated templates. Works too for english pages, if we use the english localized template version ({{Template/en}}).
- Translate the text without the translate extension we can use for each text string a parameter. The localized template version calls main template, passes through all parameters and add the translated text parameters.
- No separation. The template gets big and the code is harder to read.
- Automatic localization means, all translations are in the template. Technically we can use a switch function and e.g. User:Astaecker/Lang subpage template to detect the wanted language.
- I prefer the "translate extension" solution, because of the quality control of the translations. --Astaecker 11:08, 12 November 2011 (UTC)
Success Stories
A new category in which users can put their machine configuration.
It is nice to divide docs by hardware/software, but seeing a complete working machine of people is something that makes things much clearer. --Alonbl 23:51, 12. Nov. 2011 (UTC)
Print to PDF and/or Export to EBook File Format?
I prefer reading long articles on my EBook Device (Kindle DXG). Seeing most documents being published in PDF, or some sites even providing EBook formats. Thankfully, my device can handle PDF but some can't. As for the Amazon Kindle's, I've seen really good results using kindlegen on converting EPUB to MOBI, but using kindlegen on HTML with TABLE TAGS produces poor MOBI files. As such, I usually use PDF files for computer technical documents. Also, kindlegen (aka mobigen) is binary only (proprietary). A couple months ago, I mirrored the entire Gentoo Documentation just to convert XML to HTML using gorg, and then kindlegen to convert to MOBI. This is very tedious for EBook users! I manage quite well as I use the console, but avoid Calibre due to it's package bloat and lack of command line only. (Calibre requires X for it's command line tool.) Probably the simple solution for now, for simple articles would be to ensure a 'Print to PDF' option. Lengthy articles such as the Gentoo Handbook and EBuild/EClass documentation, would be nice to have an EBook format. Signed: Roger 19:09, 15 November 2011 (UTC)
I second this motion as far as PDF and ePUB goes. I even submitted a wish/bug to Gentoo's Bugzilla about this. ----Hook 00:14, 24 March 2012 (UTC)
Provide direct links to Help:Formatting and Gentoo Templates on Edit Page
When editing a page, I always go stumbling along trying to find a dumb template or how to format something as the direct links to these pages are not always published on the page I'm editing. Except for the basic "Help" link, which doesn't do much good. How about placing at least two of the most popular Help pages (Help:Formatting and Gentoo Templates) right on the page that is being edited by a user so he/she doesn't have to waste time trying to hunt them down. (Although by now I have most of Help:Formatting memorized, some of Gentoo Templates are new.) The full links follow.
- Help:Formatting Pretty much memorized here, but a good one for most others!
- Special:PrefixIndex/Template: I think this is the one?
- Help:Gw.com_cheat_sheet Actually, this is more what I'm talking about compared to the 2nd one above as it's more structured (easier read) like the Help:Formatting page! Lacks many of the templates/commands though.
Signed: Roger 19:09, 15 November 2011 (UTC)
Definition of Macros
Dear wiki-admins,
You should define some macros as soon as possible for things like referencing portage packages, infoboxes for software that autocomplete from portage information, general infoboxes for software that include fields such as 'deprecated by', and create categories for each of the Gentoo projects (Hardened, etc.) so that relevant articles can be grouped together in a way that makes sense for users coming from other sources of documentation.
Voltaire 00:02, 2 August 2012 (UTC)
- We will definitely also need one for man pages. Like 'man 5 corosync.conf' should be possible to define with a quick macro that makes it obviously possible to type at the terminal but also clickable in-wiki to go to a hosted, HTML version of the man page. This should be the latest version auto-built out of portage, or preferably a diffed history of versions. This sort of cross-linking is precisely where a lot of Linux documentation falls down and where the Gentoo community could showcase its pragmatism. Voltaire 00:30, 4 August 2012 (UTC)
Template documentation rework
I reworked all templates and its documentation to get some improvements. As an example see {{Error}}.
- Testcases (/testcases subpage):
- Add testcases for every parameter (using {{Testcase}}.
- Put testcases, which are for debugging only (e.g. checking for mandatory parameters) in <noinclude>-tags, so they will not be transcluded.
- Documentation (/doc subpage):
- Add consistent headings (Parameters, Usage, See also)
- Fill out the missing pieces (intro description, parameter description, etc.)
- Transclude the /testcases subpage to showcase the usage of the template.
- Template:
- Check for mandatory parameters and print an error message (using {{Error}}).
- Put the whole template code in <includeonly>-tags, so you don't see the often ugly template visuals. As each template page transcludes the /doc and so the /testcases subpage, the showcasing testcases of the /testcases subpage are seen also on the template page.
Any comments? - Astaecker 14:58, 9 August 2012 (UTC)
- As there is no feedback, I will update all templates next week. Astaecker 04:57, 19 August 2012 (UTC)
"desc" parameter for templates Code, File, Kernel
The templates {{Code}}, {{File}} and {{Kernel}} are users of {{ContentBox}} and use 1. unnamed parameter to add a description and the 2. unnamed parameter to add the actual content. The problem is, that the 1. unnamed parameter is optional, so you always have to specify an empty parameter.
I suggest to move the description part to a new "desc" parameter and change the content part to the 1. parameter. The 2. unnamed parameter should show an {{Error}}.
I know, this means a lot of changes to existing articles, but IMHO it is the right thing to do in the long run. Astaecker 09:27, 24 August 2012 (UTC)
Template for generic inline code
I looked Help:Gw.com_cheat_sheet and it seems we don't have a proper way to add generic inline code. Gentoo-wiki.com uses a specific template called Codeline, and we also have something similar, but for another purpose: the Path template. In my opinion using ''foo'' is not correct in that this uses an italic font where a monospace font is needed instead. Also, as you can easily notice, it's the only entry in the table that doesn't use a template, but I cannot understand why such an exception was made. What do you think? Fturco 16:43, 9 October 2012 (UTC)
- +1 by me. Some remarks about an implementation:
- The template shouldn't be named "Codeline" like in g-w.com, because this template should also cover other usecases like referencing parts of commands, etc. Also the name is to long for an often used template. Maybe "var".
- The styling should be distinguishable from other inline template, like {{Path}} and {{Key}}. This can also mean, that we change "Path".
- We don't strive to be template-complete with g-w.com. We add templates, where we see need.
- -Astaecker 11:03, 10 October 2012 (UTC)
- If not adding a specific template like I proposed we can instead use <code>foo</code>, but definitely not ''foo''. The advantage of using a template is that, if the need arise, we can change the way inline code looks like by just editing the corresponding template in a single place; otherwise we have to look all over the wiki articles in search for inline code to alter. Anyway I can't find a proper, short name for this new template. Perhaps it's way too generic and we should stick with the <code> tag. Fturco 14:36, 10 October 2012 (UTC)
- Perhaps we can:
- Rename "Code" to "CodeBox", "File" to "FileBox", "Kernel" to "KernelBox"; these three templates are very similar, so I think it's better they all have the same suffix
- "Code" template name is not used now, so we can use it for generic inline code
- Rename "Path" template to "File"; directories, links, devices, etc. are all files in Linux, aren't they?
- "Kernel" template name is not used now, so we can use it for kernel options such as CONFIG_MODULES
- "Path" is not used now; it may be used if the need arises
- At the end we would have Code/CodeBox, File/FileBox and Kernel/KernelBox. Yes, I like symmetric things :)
- There would be a lot of work to fix things, but I'm ready to work on it. What do you think? Fturco 16:58, 10 October 2012 (UTC)
- I like the Code/CodeBox and File/FileBox combos and renaming Kernel to KernelBox makes sense.
- I don't like Kernel for CONFIG_* stuff. First, CONFIG_* stuff is not very user friendly (not descriptive, useless for make menuconf/*config ), and second, it has the same rationale as Code (highlight a snippet). So I would left Kernel unused.
- So, I'm in favor, but we should get the others onboard. I thing, the change is too big for a "be bold and do it" approach.
- -Astaecker 08:20, 11 October 2012 (UTC)
Cannot upload and link to ASCII/Text files
Seems only JPEG, PNG, ... image files can be uploaded and linked to within Wiki articles here. It would be nice to allow ASCII/Text files to be uploaded as well. --Roger 09:51, 17 October 2012 (UTC)
- Bug #451074 (which I filed being unaware of this page) is related to this. --ulm (talk) 12:20, 19 January 2013 (UTC)
The "enabled per default" USE flag in the USEflag template
The {{USEflag}} template has a column named "default". I find it hard to say if a USE flag is enabled per default or not, the problem is you do not know which gentoo profile a document writer is using, or the document reader. We should define which gentoo profile is meant by "default" in this template. I have been assuming the "default gentoo profile" is meant here, which is very minimal, but a desktop will user assume the "desktop profile" is meant, which has already more USE flags enabled "per default". Which gentoo profile should we assume as mandatory for this template, so we have a baseline for further editing. I would suggest we should use the minimal "default gentoo profile" as a basis for this template, but I am open for other solutions. Needle (talk) 21:26, 6 May 2013 (UTC)
- Good point. We should agree on a profile. I vote for a "default profile", based on assumed usage:
- For most articles, we should default on the "desktop" profile, because it's the most common used one (including "gnome" and "kde" subprofiles), I guess.
- For the articles in the Server & Security category, we should default on the "default" profile, again because it's the most common used one
- Astaecker (talk) 08:37, 8 May 2013 (UTC) | http://wiki.gentoo.org/wiki/Gentoo_Wiki:Suggestions | CC-MAIN-2013-20 | refinedweb | 2,775 | 61.36 |
I'd like to perform some basic stemming on a Spark Dataframe column by replacing substrings. What's the quickest way to do this?
In my current use case, I have a list of addresses that I want to normalize. For example this dataframe:
id address
1 2 foo lane
2 10 bar lane
3 24 pants ln
id address
1 2 foo ln
2 10 bar ln
3 24 pants ln
For Spark 1.5 or later, you can use the functions package:
from pyspark.sql.functions import * newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))
Quick explanation:
withColumnis called to add (or replace, if the name exists) a column in the data frame.
regexp_replacewill generate a new column by replacing all substrings that match the pattern. | https://codedump.io/share/R7OT1jOrLzvp/1/pyspark-replace-substring-in-spark-dataframe-column | CC-MAIN-2017-34 | refinedweb | 128 | 73.17 |
Your application’s user interface may be a Windows Form, a Web Form, or maybe just a command line. This article is about separating the user interface from the rest of your application’s code.
Introduction
Your application's user interface may be a Windows Form, a Web Form, or maybe just a command line. This article is about separating the user interface from the rest of your application's code.
Here are some reasons this is a good idea:
The Engine Class
The first thing to do is move your working code into a class I often name Engine, unless I can think of a better name. This class has methods to respond to all the UI events, and completely separates all the application's funtionality from the UI. Put this class in a separate library project, along with all the other classes it uses, and then reference the library from each UI project. Your UI projects should contain only UI code.
Information flows two ways between the UI and the Engine class.
Let's see some code
This demonstration project implements an imaginary process of listing the machine names on a network. To keep things simple, it doesn't actually scan the network, it just makes up names: Machine1, Machine2, etc.
This is the interface definition the Engine class will use to send information back to the UI to report progress events.
public interface IUI
{
void Started();
void Progress(string progress);
void Complete();
}
public class Engine
static IUI _iui;
static bool _cancel;
public static IUI Iui
{
set { Engine._iui = value; }
}
public static void ScanNetwork()
_iui.Started();
_cancel = false;
for (int i = 1; i < 15;i++)
{
if (_cancel) break;
_iui.Progress("Machine" + i.ToString());
}
_iui.Complete();
The Form1 class inherits from IUI and defines the interface methods.
public partial class Form1 : Form, IUI
public Form1()
InitializeComponent();
Engine.Iui = this;
private void buttonScanNetwork_Click(object sender, EventArgs e)
Engine.ScanNetwork();
private void buttonCancel_Click(object sender, EventArgs e)
Engine.Cancel();
public void Started()
listBoxMachines.Items.Clear();
labelStatus.Text = "Started";
public void Progress(string progress)
listBoxMachines.Items.Add(progress);
public void Complete()
labelStatus.Text = "Complete";
The Engine.Iui property is set to point to the class that implements the IUI interface. In this case it's the form class, but when writing a console application I create a separate class.
This code will work as it is, but there's a problem. In this example the imaginary network scan occurs instantly. In real life it takes time, and the user will have to wait for the whole scan to complete before the machine names will appear in the list. There is a line with a Sleep call in the project code that you can uncomment to see what I mean.
The machine names should be added to the list as they are found (or made up in this case) so the user can see progress. It would also be nice to have a way to cancel the potentially time consuming scan. To keep the UI "alive", the scanning process needs to run on a separate thread. There's more than one way to do this, but here's a way that's quick and easy.
Adding a background worker
From the Visual Studio toolbox, drag a BackgroundWorker component onto the form. In the Properties pane for the BackGroundWorker, select the Events view and double click the DoWork event to create an event handler. The event handler code should call Engine.Scan
private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)
Engine.ScanNetwork();
private void buttonScanNetwork_Click(object sender, EventArgs e)
listBoxMachines.Items.Clear();
backgroundWorker1.RunWorkerAsync();
Create the method that will manipulate the control and define a delegate with the same signature.
public delegate void UpdateStatusCallback(string status);
public void UpdateStatus(string status)
labelStatus.Text = status;
private object[] StringToObjectArray(string str)
object[] args = new object[1];
args[0] = str;
return args;
public void Started()
UpdateStatusCallback callback
= new UpdateStatusCallback(this.UpdateStatus);
labelStatus.Invoke(callback, StringToObjectArray("Started"));
We've explored the details of implementing a Windows Forms interface for the Engine class. Because of the necessity to keep the GUI alive, this is the most complicated UI to implement.
The included solution code has a Console application that implements a command line interface for the Engine class, and it's very simple.
Conclusion
I've shown an easy way to get the flexibility of interchangable user interfaces and, at the same time, add structure to your code. Next time someone asks "can we make a web version?" you'll be ready to go.
I’ve been developing software for twenty years with C, C++,
and now C#. My latest creation is a
software visualization program called LumiCode which is written entirely in C#.
I believe good software design is easier to achieve if we
can actually see the design, and I enjoy developing tools for that purpose. | http://www.c-sharpcorner.com/UploadFile/lumikon/SeparateUI06232008203906PM/SeparateUI.aspx | crawl-002 | refinedweb | 808 | 56.25 |
>>>>> "Martin" == Martin v Loewis <martin@mira.isdn.cs.tu-berlin.de> writes: >> What's the status of this patch? As I recall, Ulrich didn't >> like it because it put a data member in the user namespace >> (i.e., named in `c' instead of `_M_c'.) But, if I recall >> correctly, Jason said that it was required to have the name `c' >> by the standard. Martin> Jason is right, see 23.2.3.1, [lib.queue]/1. I believe Martin> this member name is normative; according to 17.3.2.3, Martin> [lib.objects.within.classes]/1, members not intended to be Martin> normative are not listed. I agree. And, current libstdc++ CVS has this change. Put this patch should in, on the mainline and the branch. -- Mark Mitchell mark@codesourcery.com CodeSourcery, LLC | https://gcc.gnu.org/pipermail/gcc-patches/1999-June/013929.html | CC-MAIN-2021-21 | refinedweb | 133 | 71.31 |
FFI Helper User Guide Matt Wette July 2019 With NYACC Version 1.03.0
Next: Introduction, Previous: (dir), Up: (dir)
This is a user guide for the NYACC FFI Helper.
The acronym FFI stands for “Foreign Function Interface”. It refers
to the Guile facility for binding functions and variables from C source
libraries into Guile programs. This distribution provides utilities
for generating a loadable Guile module from a set of C declarations
and associated libraries. The C declarations can, and conventionally
do, come from naming a set of C include files. The
nominal method for use is to write a ffi-module specification
in a file which includes a
define-ffi-module declaration, and
then use the command
guild compile-ffi to produce an associated
file of Guile Scheme code.
$ guild compile-ffi ffi/cairo.ffi wrote `ffi/cairo.scm'
The FH does not generate C code. The hooks to access functions in the
Cairo library are provided in 100% Guile Scheme via
(system foreign).
The compiler for the FFI Helper (FH) is based on the C parser and utilities
which are included in the NYACC
package. Development for the FH is currently being performed in the
c99dev branch of the associated git repository. Within the
NYACC distribution, the relevant modules can be found under the
directory examples/.
Use of the FFI-helper module depends on the scheme-bytestructure package available from. Releases are available at.
At runtime, after the FFI Helper has been used to create Scheme code,
the modules
(system ffi-help-rt) and
(bytestructures
guile) are required. No other code from the NYACC distribution
is needed. However, note that the process of creating the Scheme
output depends on reading system headers, so the generated code may
well contain operating system and machine dependencies. If you copy
code to a new machine, you should re-run
guild compile-ffi.
You are probably hoping to see an example, so let’s try one.
This is a small FH example to illustrate its use. We will start with the Cairo package because that is the first one I started with in developing the FFI Helper. Say you are an avid Guile user and want to be able to use Cairo in Guile. On most systems Cairo comes with the associated pkg-config support files; this demo depends on that support.
Warning: The FFI Helper package is under active development and there is some chance the following example will cease to work in the future.
If you want to follow along and are working in the distribution tree, you should source the file env.sh in the examples directory.
By practice, I like to put all FH generated modules under a directory called ffi/, so we will do that. We start by generating, in the ffi directory, a file named cairo.ffi with the following contents:
(define-ffi-module (ffi cairo) #:pkg-config "cairo" #:include '("cairo.h" "cairo-pdf.h" "cairo-svg.h"))
To generate a Guile module you execute
guild as follows:
$ guild compile-ffi ffi/cairo.ffi wrote `ffi/cairo.scm'
Though the file cairo/cairo.ffi is only three lines long, the file ffi/cairo.scm will be over five thousand lines long. It looks like the following:
(define-module (ffi cairo) #:use-module (system ffi-help-rt) #:use-module ((system foreign) #:prefix ffi:) #:use-module (bytestructures guile)) (define link-libs (list (dynamic-link "libcairo"))) ;; int cairo_version(void); (define ~cairo_version (delay (fh-link-proc ffi:int "cairo_version" (list) link-libs))) (define (cairo_version) (let () ((force ~cairo_version)))) (export cairo_version) … ;; typedef struct _cairo_matrix { ;; double xx; ;; double yx; ;; double xy; ;; double yy; ;; double x0; ;; double y0; ;; } cairo_matrix_t; (define-public cairo_matrix_t-desc (bs:struct (list `(xx ,double) `(yx ,double) `(xy ,double) `(yy ,double) `(x0 ,double) `(y0 ,double)))) (define-fh-compound-type cairo_matrix_t cairo_matrix_t-desc cairo_matrix_t? make-cairo_matrix_t) (export cairo_matrix_t cairo_matrix_t? make-cairo_matrix_t) … many, many more declarations … ;; access to enum symbols and #define'd constants: (define ffi-cairo-symbol-val (let ((sym-tab '((CAIRO_SVG_VERSION_1_1 . 0) (CAIRO_SVG_VERSION_1_2 . 1) (CAIRO_PDF_VERSION_1_4 . 0) (CAIRO_PDF_VERSION_1_5 . 1) (CAIRO_REGION_OVERLAP_IN . 0) (CAIRO_REGION_OVERLAP_OUT . 1) … more constants … (CAIRO_MIME_TYPE_JBIG2_GLOBAL_ID . "application/x-cairo.jbig2-global-id")))) (lambda (k) (or (assq-ref sym-tab k))))) (export ffi-cairo-symbol-val) (export cairo-lookup) … more …
Note that from the pkg-config spec the FH compiler picks up the
required libraries to bind in. Also,
#define based constants,
as well as those defined by enums, are provided in a lookup function
ffi-cairo-symbol-val. So, for example
guile> (use-modules (ffi cairo)) ;;; ffi/cairo.scm:6112:11: warning: possibly unbound variable `cairo_raster_source_acquire_func_t*' ;;; ffi/cairo.scm:6115:11: warning: possibly unbound variable `cairo_raster_source_release_func_t*' guile> (ffi-cairo-symbol-val 'CAIRO_FORMAT_ARGB32)) $1 = 0
We will discuss the warnings later. They are signals that extra code needs to be added to the ffi module. But you see how the constants (but not CPP function macros) can be accessed.
Let’s try something more useful: a real program. Create the following
code in a file, say
cairo-demo.scm, then fire up a Guile session
and
load the file.
(use-modules (ffi cairo)) (define srf (cairo_image_surface_create 'CAIRO_FORMAT_ARGB32 200 200)) (define cr (cairo_create srf)) (cairo_move_to cr 10.0 10.0) (cairo_line_to cr 190.0 10.0) (cairo_line_to cr 190.0 190.0) (cairo_line_to cr 10.0 190.0) (cairo_line_to cr 10.0 10.0) (cairo_stroke cr) (cairo_surface_write_to_png srf "cairo-demo.png") (cairo_destroy cr) (cairo_surface_destroy srf)
guile> (load "cairo-demo.scm") … ;;; compiled /.../cairo.scm.go ;;; compiled /.../cairo-demo.scm.go guile>
If we set up everything correctly we should have generared the target
file cairo-demo.png which contains the image of a square. A
few items in the above code are notable. First, the call to
cairo_image_surface_create accepted a symbolic form
'CAIRO_FORMAT_ARGB32 for the format argument. It would have
also accepted the associated constant
0. In addition,
procedures declared in
(ffi cairo) will accept Scheme strings
where the C function wants “pointer to string.”
Now try this in your Guile session:
guile> srf $4 = #<cairo_surface_t* 0x7fda53e01880> guile> cr $5 = #<cairo_t* 0x7fda54828800>
Note that the FH keeps track of the C types you use. This can be useful for debugging (at a potential cost of bloating the namespace). The constants you see are the pointer values. But it goes further. Let’s generate a matrix type:
guile> (define m (make-cairo_matrix_t)) guile> m $6 = #<cairo_matrix_t 0x10cc26c00> guile> (use-modules (system ffh-help-rt)) guile> (pointer-to m) $7 = #<cairo_matrix_t* 0x10cc26c00>
When it comes to C APIs that expect the user to allocate memory for a structure and pass the pointer address to the C function, FH provides a solution:
guile> (cairo_get_matrix cr (pointer-to m)) guile> (fh-object-ref m 'xx) $9 = 1.0
Guile has an API, called the Foreign Function Interface, which allows
one to avoid writing and compiling C wrapper code in order to access C
coded libraries. The API is based on
libffi and is covered in
the Guile Reference Manual. We review some important bits here. For
more insight you should read the relevant sections in the Guile
Reference Manual. For more info on libffi internals visit
libffi.
The relevant procedures used by the FH are
dynamic-link
links libraries into Guile session
dynamic-func
generated Scheme-level pointer to a C function
pointer->procedure
geneates a Scheme lambda given C function signature
dynamic-pointer
provides access to global C variables
Several of the above require import of the module
(system foreign).
In order to generate a Guile procedure wrapper for a function, say
int foo(char *str), in some foreign library, say
libbar.so, you can use something like the following:
(use-modules (system foreign)) (define foo (pointer->procedure int (dynamic-func "foo" (dynamic-link "libbar")) (list '*)))
The argument
int is a variable name for the return type,
the next argument is an expression for the function pointer and the
third argument is an expression for the function argument list.
To execute the function, which expects a C string, you use something like
(define result-code (foo (string->pointer "hello")))
If you want to try a real example, this should work:
guile> (use-modules (system foreign)) guile> (define strlen (pointer->procedure int (dynamic-func "strlen" (dynamic-link)) (list '*))) guile> (strlen (string->pointer "hello, world")) $1 = 12
It is important to realize that internally Guile takes care of converting Scheme arguments to and from C types. Scheme does not have the same type system as C and the Guile FFI is somewhat forgiving here. When we declare a C function interface with, say, an uint32 argument type, in Scheme you can pass an exact numeric integer. The FH attempts to be even more forgiving, allowing one to pass symbols where C enums (i.e., integers) are expected.
As mentioned, access to libraries not compiled into Guile is
accomplished via
dynamic-link. To link the
shared library libfoo.so into Guile one would write something
like the following:
(define foo-lib (dynamic-link "libfoo"))
Note that Guile takes care of dealing with the file extension (e.g., .so). Where Guile looks for libraries is system dependent, but usually it will find shared objects in the following
(assq-ref %guile-build-info 'libdir)
(assq-ref %guile-build-info 'extensiondir)
When used with no argument
dynamic-link returns a handle for
objects already linked with Guile. The procedure
dynamic-link
returns a library handle for acquiring function and variable handles,
or pointers, for objects (e.g., a pointer for a function) in the
library. Theoretically, once a library has been dynamically linked
into Guile, the expression
(dynamic-link) (with no argument)
should suffice to provide a handle to acquire object handles, but I
have found this is not always the case. The FH will try all
library handles defined by a ffi module to acquire object pointers.
In this section we hope to provide some insight into the FH works. The FH specification, via the dot-ffi file, determines the set of declarations which will be included in the target Guile module. If there is no declartion filter, then all the declarations from the specified set of include files are targeted. With the use of a declaration filter, this set can be reduced. By declaration we mean typedefs, aggregate definitions (i.e., structs and unions), function declarations, and external variables.
In the C language typedefs define type aliases, so there is no harm in
expanding typedefs which appear outside the specification. For
example, say the file foo.h includes a declaration for the
typedef
foo_t and the file bar.h includes a declaration
for the typedef
bar_t. Furthermore, suppose
foo_t is a
struct that references
bar_t. Then the FH will preserve the
typedef
foo_t but expand
bar_t. That is, if the
declarations are
typedef int bar_t; /* from bar.h */ typedef struct { bar_t x; double y; } foo_t; /* from foo.h */
then the FH will treat
foo_t as if it had been declared as
typedef struct { int x; double y; } foo_t; /* from foo.h */
When it comes to handling C types in Scheme the FH tries to leave base types (i.e., numeric types) alone and uses its own type system, based on Guiles structs and associated vtables, for structs, unions, function types and pointer types. Enum types are handled specially as described below. The FH type system associates with each type a number of procedures. One of these is the printer procedure which provided the association of type with output seen in the demo above.
One of the challenges in automating C-Scheme type conversion is that C
code uses a lot of pointers. So as the FH generates types for
aggregates, it will automatically generate types for associated
pointers. For example, in the case above with
foo_t the FH will
generate an aggregate type named
foo_t and a pointer type named
foo_t*. In addition the FH generates code to link these two
together so that, given an object
f1 of type
foo_t, the
expression
(pointer-to f1) will generate an object of type
foo_t*. This makes the task of generating an object value in
Scheme, and then passing the pointer to that value as an argument to a
FFI-generated procedure, easy. The inverse operation
value-at
is also provided. Note that sometimes the C code needs to work with
pointer pointer types. The FH does not produce double-pointers and in
that case, the user must add code to the FH module defintion to
support the required additional type (e.g.,
foo_t**).
In addition, the FH type system provide unwrap and wrap procedures
used internal to ffi-generated modules for function calls. These
convert FH types to and from objects of type expected by Guile’s FFI
interface. For example, the unwrap procedure associated with the FH
pointer type
foo_t* will convert an
foo_t* object to a
Guile
pointer. Similarly, on return the wrap procedure are
applied to convert to FH types. When the FH generates a type, for
example
foo_t it also generates an exported procedure
make-foo_t that users can use to build an object of that type.
The FH also generates a predicate
foo_t? to determine if an
object is of that type. The
(system ffi-help-rt) module
provides a procedure
fh-object-ref to convert an object of type
foo_t to the underlying bytestructures representation. For
numeric and pointer types, this will generate a number and for
aggregate types, a bytestructure. Additional arguments to
fh-object-ref for aggregates work as with the bytestructures
package and enable selection of components of the aggregate. Note
that the underlying type for a bytestructure pointer is an integer.
Enums are handled specially. In C, enums are represented by integers.
The FH does not generate types for C enums or C enum
typedefs. Instead, the FH defines unwrap and wrap procedures to
convert Scheme values to and from integers, where the Scheme values
can be integers or symbols. For example, if, in C, the enum typedef
baz_t has element
OPTION_A with value 1, a procedure
expecting an argument of type
baz_t will accept the symbol
'OPTION_A or the integer
1.
Where the FH generates types, the underlying representation is a bytestructure descriptor. That is, the FH types are essentially a layer on top of a bytestructure. The layer provides identification seen at the Guile REPL, unwrap and wrap procedures which are used in function handling (not normally visible to the user) and procedures to convert types to and from pointier-types.
For base types (e.g.,
int,
double) the FH uses the
associated Scheme values or the associated bytestructures values.
(I think this is all bytestructure values now.)
The underlying representation of bytestructure values is bytevectors. See the Guile Reference Manual for more information on this datatype.
The following routines are user-level procedures provided by the
runtime module
(system ffi-help-rt):
fh-type?
a predicate to indicate whether an object is a FH type
fh-object?
a predicate to indicate whether an object is a FH object
fh-object-val
the underlying bytestructure value
fh-object-ref
a procedure that works like
bytestructure-ref on the underlying
object
fh-object-set!
a procedure that works like
bytestructure-set! on the underlying
object
pointer-to
a procedure, given a FH object, or a bytestructure, that returns an associated pointer object (i.e., a pointer type whose object value is the address of the underlying argument); this may be a FH type or a bytestructure
value-at
a procedure to dereference an object
fh-cast
a procedure to cast arguments for varaidic C functions
make-type
make base type, as listed below; also used to make bytestructure
objects for base types (e.g.,
(make-double) for
double)
Supported base types are
These types are useful for cases where the corresponding types are passed by reference as return types. For example
(let ((name (make-char*))) (some_function (pointer-to name)) (display "name: ") (display (char*->string name)) (newline)) (let ((return-val (make-double))) (another_function (pointer-to return-val)) (simple-format #t "val is ~S\n" (fh-object-ref return-val)))
You can pass a bytestructure struct value:
guile> (make-ENTRY `((key 0) (data 0))) #<ENTRY 0x18a10b0>
TODO: should we support
(make-ENTRY 0 0) ?
(nyacc lang c99 ffi-help)
(define ffi-module module-name ...)
#:pkg-config
This option take a single string argument which provides the name used
for the pkg-config program. Try
man pkg-config.
#:include
This form, with expression argument, indicates the list of include
files to be processed at the top level. Without use of the
#:inc-filter form, only declarations in these files will be
output. To constrain the set of declarations output use the
#:decl-filter form.
#:inc-filter
This form, with predicate procedure argument taking the form
(proc file-spec path-spec), is used to indicate which includes
beyond the top-level should have processed declarations emitted in the
output. The
file-spec argument is a string as parsed from
#include statements in the C code, including brackets or double
quotes (e.g.,
"<stdio.h>",
"\"foo.h\""). The
path-spec is the full path to the file.
#:use-ffi-module
This form, with literal module-type argument (e.g.,
(ffi
glib)), indicates dependency on declarations from another processed
ffi module. For example, the ffi-module for
(ffi gobject)
includes the form
#:use-ffi-module (ffi glib).
#:decl-filter
This form, with a predicate procedure argument, is used to restrict
which declarations should be processed for output. The single
argument is either a string or a pair. The string form is used for
simple identifiers and the pair is used for struct, union and enum
forms from the C code (e.g.,
(struct . "foo")).
#:library
This form, with a list of strings, indicates which (shared object)
libraries need to be loaded. The formmat of each string in the list
should be as provided to the
dynamic-link form in Guile.
#:renamer
todo
#:cpp-defs
This form, with a list of strings, provides extra C preprodessor
definitions to be used in processing the header files. The defines
take the form
"SYM=val
".
#:inc-dirs
todo
#:inc-help
todo
#:api-code
todo
#:library '("libcairo" "libmisc") #:inc-dirs '("/opt/local/include/cairo" "/opt/local/include") #:renamer (string-renamer (lambda (n) (if (string=? "cairo" (substring n 0 5)) n (string-append "cairo-" n)))) #:pkg-config "cairo" #:include '("cairo.h" "cairo-svg.h") #:inc-help (cond ((string-contains %host-type "darwin") '(("__builtin" "__builtin_va_list=void*") ("sys/cdefs.h" "__DARWIN_ALIAS(X)="))) (else '())) #:decl-filter (string-member-proc "cairo_t" "cairo_status_t" "cairo_surface_t" "cairo_create" "cairo_svg_surface_create" "cairo_destroy" "cairo_surface_destroy") #:export (make-cairo-unit-matrix)
Another decl-filter, useful for debugging.
#:decl-filter (lambda (k) (cond ((member k '( "cairo_t" "cairo_status_t" "cairo_glyph_t" "cairo_path_data_t" )) #t) ((equal? k '(union . "union-_cairo_glyph_t")) #t) (else #f)))
Since this is not all straightforward you will get errors.
Method
MAX_HEAP_SECTS
The message is
Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS
The message comes from the garbage collector. It means you’ve run out of memory. I found that this actually came from a bug in the ff-compiler which generated this code:
(bs:struct (list ... `(compose_buffer ,(bs:vector #f unsigned-int))
The original C declaration was
struct _GtkIMContextSimple { ... guint compose_buffer[7 + 1]; ... };
This bug, failure to evaluate
7+1 to an integer, was fixed.
After using the FFI Helper to provide code for some packages you may
notice that the quantity of code produced is large. For example, to
generate a guile interface for gtk2+, along with glib, gobject, pango
and gdk you will end up with over 100k lines of scm code. This may
seem bulky. Instead it may be preferable to generate a small number
of calls for gtk and work from there. In order to achieve this you
could use the
#:api-code or
#:decl-filter options.
For example, in the expansion of the GLU/GL FFI module, called
glugl.ffi, I found that a very large number of declarations
starting with
PF were being generated. I removed these using
the
#:decl-filter option:
(define-ffi-module (ffi glugl) #:include '("GL/gl.h" "GL/glu.h") #:library '("libGLU" "libGL") #:inc-filter (lambda (spec path) (string-contains path "GL/" 0)) #:decl-filter (lambda (n) (not (and (string? n) (string-prefix? "PF" n)))))
Using the option reduced glugl.scm from 59,274 lines down to 15,354 lines.
As another example, if we wanted to just generate code for the gtk hello world demo we could write
(define-ffi-module (hack1) #:pkg-config "gtk+-2.0" #:api-code " #include <gtk2.h> void gtk_init(int *argc, char ***argv); void gtk_container_set_border_width(GtkContainer *container, guint border_width); void gtk_container_add(GtkContainer *container, GtkWidget *widget); void gtk_widget_show(GtkWidget *widget); void gtk_main(void); ")
Since the above example does not ask the FH to pull in typedef’s then the pointer types will be expanded to native. You could invent your own types or echo the typedefs from the package headers
;;; ffi/gtk2+.scm:3564:5: warning: possibly unbound variable `GtkEnumValue*' ;;; ffi/gtk2+.scm:3581:5: warning: possibly unbound variable `GtkFlagValue*' ;;; ffi/gtk2+.scm:10717:11: warning: possibly unbound variable `GtkAllocation*' ;;; ffi/gtk2+.scm:15107:15: warning: possibly unbound variable `GdkNativeWindow' ;;; ffi/gtk2+.scm:15122:15: warning: possibly unbound variable `GdkNativeWindow' ;;; ffi/gtk2+.scm:26522:11: warning: possibly unbound variable `GSignalCMarshaller' ;;; ffi/gtk2+.scm:62440:11: warning: possibly unbound variable `GdkNativeWindow' ;;; ffi/gtk2+.scm:62453:5: warning: possibly unbound variable `GdkNativeWindow'
When I see this I check the scm file and see one of many things
(fht-unwrap GtkAllocation*)
This usually means that
GtkAllocation was somehow defined
but not the pointer type.
User is responsible for calling string->pointer and pointer->string.
By definition: wrap is c->scm; unwrap is scm->c.
define-ffi-module options:
#:decl-filter proc
proc is a prodicate taking a key of the form
"name",
(struct . "name"),
(union . "name") or
(enum . "name").
#:inc-filter proc
#:include expr
expr is string or list or procecure that evaluates to string or list
#:library expr
expr is string or list or procecure that evaluates to string or list
#:pkg-config string
#:renamer proc
procdure
Here are the type of hacks I need to parse inside /usr/include with NYACC’s C99 parser. There is no such thing as a working C standard.
(define cpp-defs (cond ((string-contains %host-type "darwin") '("__GNUC__=6") (remove (lambda (s) (string-contains s "_ENVIRONMENT_MAC_OS_X_VERSION")) (get-gcc-cpp-defs))) (else '()))) (define fh-inc-dirs (append `(,(assq-ref %guile-build-info 'includedir) "/usr/include") (get-gcc-inc-dirs))) (define fh-inc-help (cond ((string-contains %host-type "darwin") '(("__builtin" "__builtin_va_list=void*" "__attribute__(X)=" "__inline=" "__inline__=" "__asm(X)=" "__asm__(X)=" "__has_include(X)=__has_include__(X)" "__extension__=" "__signed=signed" ))) (else '(("__builtin" "__builtin_va_list=void*" "__attribute__(X)=" "__inline=" "__inline__=" "__asm(X)=" "__asm__(X)=" "__has_include(X)=__has_include__(X)" "__extension__=" )))))
(system ffi-help-rt)
Here we provide details of the run-time support module.
if need foo_t pointer then I gen wrapper for foo_t* but add foo_t to *wrappers* so if I later run into need for foo_t may be prob
allow user to specify #:renamer (lambda (n) "make_goo" => "make-goo")
Now the hard part if we want to reference other ffi-modules for types or other c-routines. Say ffi-module foo defines foo_t now in ffi-module bar we want to reference, but redefine, foo_t
(define-ffi-module (cairo cairo) ...) (define-ffi-module (cairo cairo-svg) #:use-ffi-module (cairo cairo)
Should setters for
bs:struct enum fields check for symbolic
arg?
Use guardians for
cairo_destroy and
cairo_surface_destroy?
What about vectors? If
foo(foo_t x[],
enum-wrap 0 => 'CAIRO_STATUS_SUCCESS enum-unwrap 'CAIRO_STATUS_SUCCESS => 0
./configure --prefix=xxx make install
Please report bugs by navigating with your browser to
‘’ and select
the “Submit New” item under the “Bugs” menu. Alternatively,
ask on the Guile user’s mailing list guile-user@gnu.org.
typedef struct foo foo_t; typedef foo_t bar_t; struct foo { int a; }; int baz(foo_t *x);
Right now, on the first declaration I assign
foo_t the type
fh-void. The second declaration is handled as a type-alias.
When I get to the third declaration I define the
struct foo compound type, then re-define the
foo_t as
a compound type, and it’s pointer type (missed this first. | http://www.nongnu.org/nyacc/nyacc-fh-ug.html | CC-MAIN-2020-50 | refinedweb | 4,015 | 55.03 |
Introduction
The cloud is an abstract notion of a loosely connected group of computers working together to perform some task or service that appears as if it is being fulfilled by a single entity. The architecture behind the scenes is also abstract: each cloud provider is free to design its offering as it sees fit. Software as a Service (SaaS) is a related concept, in that the cloud offers some service to users. The cloud model potentially lowers users' costs because they don't need to buy software and the hardware to run it — the provider of the service has done that already.
Take, for example, Amazon's S3 offering. As its name implies, it is a publicly available service that lets Web developers store digital assets (such as images, video, music, and documents) for use in their applications. When you use S3, it looks like a machine sitting on the Internet that has a hard drive containing your digital assets. In reality, a number of machines (spread across a geographical area) contain the digital assets (or pieces of them, perhaps). Amazon also handles all the complexity of fulfilling a service request to store your data and to retrieve it. You pay a small fee (around 15 cents per gigabyte per month) to store assets on Amazon's servers and one to transfer data to and from Amazon's servers.
Rather than reinvent the wheel, Amazon's S3 service exposes a RESTful API, which enables you to access S3 in any language that supports communicating over HTTP. The JetS3t project is an open source Java library that abstracts away the details of working with S3's RESTful API, exposing the API as normal Java methods and classes. It's always best to write less code, right? And it makes a lot of sense to borrow someone else's hard work too. As you'll see in this article, JetS3t makes working with S3 and the Java language a lot easier and ultimately a lot more efficient.
S3 at a high level
Logically, S3 is a global storage area network (SAN), which appears as a super-big hard drive where you can store and retrieve digital assets. Technically though, Amazon's architecture is a bit different. Assets you choose to store and retrieve via S3 are called objects. Objects are stored in buckets. You can map this in your mind using the hard-drive analogy: objects are to files as buckets are to folders (or directories). And just like a hard drive, objects and buckets can be located via a Uniform Resource Identifier (URI).
For example, on my hard drive, I have a file named whitepaper.pdf, which is in the folder named documents in my home directory. Accordingly, the URI of the .pdf file is /home/aglover/documents/whitepaper.pdf. In S3's case, the URI is slightly different. First, buckets are top-level only — you can't nest them as you would folders (or directories) on a hard drive. Second, buckets must follow Internet naming rules; they can't include dashes next to periods, names shouldn't contain underscores, and so on. Lastly, because bucket names become part of a public URI within Amazon's domain (s3.amazonaws.com), bucket names must be unique across all of S3. (The good news is that you can only have 100 buckets per account, so it's doubtful there are squatters taking hundreds of good names.)
Buckets serve as the root of a URI in S3. That is, a bucket's name becomes part of the URI leading to an object within S3. for example, if I have a bucket named agdocs and an object named whitepaper.pdf, the URI would be.
S3 also offers the ability to specify owners and permissions for buckets and objects, as you can do for files and folders on a hard drive. When you define an object or a bucket in S3, you can specify an access-control policy that states who can access your S3 assets and how (for example, read and write permissions). Accordingly, you can then provide access to your objects in a number of ways; using a RESTful API is just one of them.
Getting started with S3 and JetS3t
To begin using S3, you need an account. S3 isn't free, so when you create your account you must provide Amazon with a means of payment (such as a credit card number). Don't worry — there are no setup fees; you only pay for usage. The nominal fees for the examples in this article will cost less than $1.
As part of the account-creation process, you also need to create some credentials: an access key and a secret key (think username and password). (You can also obtain x.509 certificates; however, they are only needed if you use Amazon's SOAP API.) As with any access information, it is imperative that you keep your secret key ... secret. Should anyone else get hold of your credentials and use them to access S3, you'll be billed. Consequently, the default behavior any time you create a bucket or an object is to make everything private; you must explicitly grant access to the outside world.
With an access key and a secret key in hand, you can download JetS3t and use it with abandon to interact with S3 via its RESTful API via.
Programmatically signing into S3 via JetS3t is a two-step process. First, you must
create a
AWSCredentials object and then pass it into a
S3Service object. The
AWSCredentials object is fairly straightforward. It takes your access and secret keys as
Strings. The
S3Service object is actually an interface type. Because S3 offers both a RESTful API and a SOAP API, the JetS3t library offers two implementation types:
RestS3Service and
SoapS3Service. For the purposes of this article (and indeed, most, if not all of your S3 pursuits), the RESTful API's simplicity makes it a good choice.
Creating a connected
RestS3Service instance is simple, as shown in Listing 1:
Listing 1. Creating an instance of JetS3t's
RestS3Service
def awsAccessKey = "blahblah" def awsSecretKey = "blah-blah" def awsCredentials = new AWSCredentials(awsAccessKey, awsSecretKey) def s3Service = new RestS3Service(awsCredentials)
Now you are set to do something interesting: create a bucket, say, add a movie to it, and then obtain a special limited-time-available URL. In fact, that sounds like a business process, right? It's a business process associated with releasing a limited asset, such as a movie.
Creating a bucket
For my imaginary movie business, I'm going to create a bucket dubbed bc50i. With
JetS3t, the process is simple. Via the
S3Service type, you have a few options. I prefer to use the
getOrCreateBucket call, shown in Listing 2. As the name implies, calling this method either returns an instance of the bucket (represented by an instance of the
S3Bucket type) or creates the bucket in S3.
Listing 2. Creating a bucket on a S3 server
def bucket = s3Service.getOrCreateBucket("bc50i")
Don't let my simple code examples fool you. The JetS3t library is fairly extensive. For
instance, you can quickly ascertain how many buckets you have by simply asking an instance of an
S3Service via the
listAllBuckets call. This method returns an array of
S3Bucket instances. With any instance of a bucket, you can ask for its name and creation date. More important, you can control permissions associated with it via JetS3t's
AccessControlList type. For instance, I can grab an instance of my bc50i bucket and make it publicly available for anyone to read and write to, as shown in Listing 3:
Listing 3. Altering the access-control list for a bucket
def bucket.acl = AccessControlList.REST_CANNED_PUBLIC_READ_WRITE
Of course, via the API, you are free to remove buckets too. Amazon even allows you to specify in which geographical areas you'd like your bucket created. Amazon handles the complexity of where the actual data is stored, but you can nudge Amazon to put your bucket (and then all objects within it) in either the United States or Europe (the currently available options).
Adding objects to a bucket
Creating S3 objects with JetS3t's API is just as easy as bucket manipulation. The library is also smart enough to take care of some of the intricacies of dealing with content types associated with files within an S3 bucket. For instance, imagine that the movie I'd like to upload to S3 for customers to view for a limited time is nerfwars2.mp4. Creating an S3 object is as easy as creating a normal
java.io.File type and associating the
S3Object type with a bucket, as I've done in Listing 4:
Listing 4. Creating an S3 object
def s3obj = new S3Object(bucket, new File("/path/to/nerfwars2.mp4"))
Once you've got a
S3Object initialized with a file and a bucket, all you need to do is upload it via the
putObject method, as shown in Listing 5:
Listing 5. Uploading the movie is a piece of cake
s3Service.putObject(bucket, s3obj)
With the code in Listing 5, you're done. The movie is now on Amazon's servers, and the key for the movie is its name. You could, of course, override that name should you feel the need to call the object something else. In truth, the JetS3t API (and by relation the Amazon S3 RESTful API) exposes a bit more information for you when you create objects. As you know, you can also provide access-control lists. Any object within S3 is capable of holding additional metadata, which the API allows you to create. You can later query any object via the S3 API (and by derivation, JetS3t) for that metadata.
Creating URLs to objects
At this point, my S3 instance has a bucket with a movie sitting in it. In fact, my movie can be found at this URI:. Yet, no one other than me can get to it. (And in this case, I can only access it programmatically, because the default access controls associated with everything are set to deny any noncredentialed access to it.) My goal is to provide select customers a way to view the new movie (for a limited time) until I'm ready to start charging for access (which S3 can facilitate as well).
Figure 1 shows the default access control in action. The XML document returned (and accordingly displayed in my browser) is informing me that access is denied to the asset I was trying to reach ().
Figure 1. Amazon's security in action
Creating a public URL is a handy feature exposed by S3; in fact, with S3, you can create a public URL that is only valid for a period of time (for instance, 24 hours). For the movie I've just stored on the S3 servers, I'm going to create a URL that is valid for 48 hours. Then I'll then provide this URL to select customers so they can download the movie and watch it at will (provided they download it within two days).
To create a time-sensitive URL for an S3 object, you can use JetS3t's
createSignedGetUrl method, which is a static method of the
S3Service type. It takes a bucket name, a object's key (the movie's
name in this case, remember?), some credentials (in the form of JetS3t's
AWSCredentials object), and an expiration date. If you know the desired bucket name and the object's key, you can quickly obtain a URL as shown in the Groovy code in Listing 6:
Listing 6. Creating a time-sensitive URL
def now = new Date() def url = S3Service.createSignedGetUrl( bucket.getName(), s3obj.key, awsCredentials, now + 2)
With Groovy, I can specify a date 48 hours in the future quite easily via the
+ 2 syntax. The resulting URL looks something like this (on a single line): 1asd06A5MR2&Expires=1234738280&Signature=rZvk8Gkms%3D
Now, with this resultant URL, browser requests will honored, as shown in Figure 2:
Figure 2. The URL facilitates downloading
Wasn't this process a piece of cake? With a few lines of code, I've created a secure asset in the cloud that can only be downloaded with a special URL.
Leveraging S3 for time-sensitive downloads
S3 makes a lot of sense if your bandwidth and storage needs aren't constant. For example, imagine the business model I'm demonstrating — one in which movies are released at specific times throughout the year. In the traditional storage model, you'd need to buy a bunch of space on a rack somewhere (or provide your own hardware and pipe leading to it) and most likely see spikes of downloads followed by lulls of relatively low activity. You'd be paying, however, regardless of demand. With S3, the model is satisfied based on demand — the business pays for storage and bandwidth only when it's required. What's more, S3's security features let you further specify when people can download videos and even specify who can download them.
Achieving these requirements with S3 turns out to be quite easy. At a high level, creating a limited publicly available download for a movie requires four steps:
- Create a bucket.
- Add a desired video (or object) to that bucket.
- Create a time-sensitive URL for the video.
That's it!
A smart move
S3's pay-as-you-go model has some obvious advantages over the traditional storage model. For instance, to store my music collection on my own hard drive, I must buy one — say a 500GB unit for $130 — up front. I don't have nearly 500GB of data to store, so in essence I'm paying roughly 25 cents per gigabyte for unneeded (albeit fairly inexpensive) capacity. I also must maintain my device and pay to power it. If I go the Amazon route, I don't need to fork out $130 up front for a deprecating asset. I'll pay about 10 cents less per gigabyte and needn't pay to manage and maintain the storage hardware. Now imagine the same benefits on an enterprise scale. Twitter, for example, stores the images for its more than 1 million user accounts on S3. By paying on a per-usage basis, Twitter is spared the high expense of acquiring a hardware infrastructure to store and serve up those images, as well as ongoing labor and parts costs to configure and maintain it.
The cloud's benefits don't end there. You also gain low latency and high availability. The presumption is that the assets stored on Amazon's cloud are physically located around the globe, so content is served up faster to varying locations. What's more, because your assets are distributed to various machines, your data remains highly available should some machine (or portion of the network) go down.
In summary, the benefits of Amazon's S3 are simple: low cost, high availability, and security. Unless you're a SAN guru and enjoy maintaining hardware assets for storing digital items, Amazon probably does a better job than you. So why spend the up-front money on hardware (which loses value over time, don't forget) when you can borrow someone else's?
Resources
Learn
- Amazon S3: Visit home base for the Amazon Simple Storage Service.
- JetS3t: Learn more about the JetS3t toolkit and application suite.
- Cloud Computing: Visit IBM Cloud Computing Central for a wealth of cloud resources.
- Browse the technology bookstore for books on these and other technical topics.
- developerWorks Java technology zone: Find hundreds of articles about every aspect of Java programming.
Get products and technologies
- JetS3t: Download JetS3t.
- developerWorks Cloud Computing Resource Center: Access IBM software products in the Amazon Elastic Compute Cloud (EC2) virtual environment.. | http://www.ibm.com/developerworks/java/library/j-s3/ | CC-MAIN-2015-48 | refinedweb | 2,632 | 62.27 |
Details
Description
I'm using Velocity 1.3-rc1 (updated from CVS (tag TVEL_1_3_BRANCH) as at 28th of
May, 2002) on a Redhat 7.2 system, combined with velocity-tools/struts and
velocity-tools/view from latest cvs.
When a velocimacro library is loaded at initialisation time, it is normally
added to the libModMap hash in VelocimacroFactory. The libModMap hash is checked
when reloading velocimacro templates. However, if the parsing of the velocimacro
library fails midway through, the macros are added to the namespace but the
Template is not returned to VelocimacroFactory, and thus not added to libModMap.
This means that if a VM library is broken at initialization time, it will never
be reloaded until Velocity is restarted.
I have not tried this under the HEAD tagged CVS sources, as my macros refuse to
parse at all using this branch.
Activity
- All
- Work Log
- History
- Activity
- Transitions
The problem here is twofold and IMHO fixing it for 1.5 is hard.
First, this is an error. If a macro library that is supposed to be loaded cannot be loaded for whatever reason, it is debatable whether this is actually a fatal error and it shouldn't just report in the log file but stop the initialization of the engine altogether. Will proposed the creation of a VelocityInitException which would be thrown in that case.
Second, fixing it so that the cache notices "there is a macro library available though this resource loader, but it is currently buggy, let's go back after the check interval and see if this has changed" at init time is hard. If an existing library that parsed fine the first time gets broken, then the cache simply keeps the last good version (it is argueable whether this is the right behaviour, too). But if there is no good version in the first place, the current internal mechanism of loading resources have to be rewritten (differentiate between "unloaded" -> "loaded, but not yet parsed" -> "parsed"). I'm afraid that is out of the question for 1.5 and probably most of the 1.x series.
Thanks for reporting this. Will look into it. | https://issues.apache.org/jira/browse/VELOCITY-82 | CC-MAIN-2017-09 | refinedweb | 357 | 62.48 |
Earlier in the year I wrote about using Bridge.net to write browser-based applications using React. Well, now, I'd like to present an update to that. I've changed how the base Component class ties into the React library (this is a class that may be derived from in order to create custom React components) - it now supports "SetState" - and I've added an alternative base class; the StatelessComponent, which will allow the writing of component classes that will operate as stateless components, as introduced by React 0.14. I've also improved how the components appear when viewed in the React Dev Tools browser extension and I've tied it into the latest, just-released version of Bridge (1.10) that has fixed a lot of bugs.
If you're the sort of person who likes to jump straight to the end of a book to see how it ends, then you can find the code on in my GitHub "Bridge.React" repo or you can add it to a Bridge project through NuGet (Bridge.React). But if you want to find out more of the details then keep reading! I'm not going to presume any prior knowledge from my previous post - so if you've read that, then I'm afraid I'm going to re-tread some of the same ground - however, I imagine that I don't have that many dedicated followers, so figure it makes more sense to make this entry nicely self-contained :)
In the past, I've also written about writing bindings for TypeScript (which is a language I liked.. but not as much as C#) and bindings for DuoCode (which is a project that seemed to have promise until they spent so longer thinking about their pricing model that I gave up on them) as well as a couple of posts about Bridge - and, often, I've got quite technical about how the bindings work under the hood. Today, though, I'm just going to deal with how to use the bindings. I'm happy that they're finally fully-populated and I've tried to make an effort to make them easy to consume, so let's just stick to getting Bridge apps talking to React and not worry about the magic behind the scenes!
I'm going to assume that you're familiar with React - though I won't be going into too much depth on it, so if you're not an expert then it shouldn't be any problem. I'm not going to assume that you have tried out Bridge yet, because it's so easy to presume that you haven't that it won't take us long to start from scratch!
So, let's really start from the basics. You need to create a new solution in Visual Studio - choose a C# Class Library. Now go to References / Manage NuGet Packages, search for "Bridge.React" online and install the package. This will automatically pull in the Bridge package as a dependency, and this sets up a "demo.html" file under the "Bridge/www" folder to make getting started as frictionless as possible. That file has the following content:
<!DOCTYPE html> <html lang="en" xmlns=""> <head> <meta charset="utf-8" /> <title>Bridge BridgeReactBlogPost</title> <script src="../output/bridge.js"></script> <script src="../output/BridgeReactBlogPost.js"></script> </head> <body> <!-- Right-Click on this file and select "View in Browser" --> </body> </html>
Note that the title and the JavaScript filename are taken from the project name. So the file above mentions "BridgeReactBlogPost" because that's the name of the project that I'm creating myself alongside writing this post (just to ensure that I don't miss any steps or present any dodgy demonstration code!).
We need to add a few more items now - the React library JavaScript, the Bridge.React JavaScript and an element for React to render inside. So change demo.html to something like the following:
<!DOCTYPE html> <html lang="en" xmlns=""> <head> <meta charset="utf-8" /> <title>Bridge BridgeReactBlogPost</title> <script src=""></script> <script src=""></script> <script src="../output/bridge.js"></script> <script src="../output/bridge.react.js"></script> <script src="../output/BridgeReactBlogPost.js"></script> </head> <body> <div id="main" /> </body> </html>
(Aside: If you want to, then you can add the line
"combineScripts": true
to your bridge.json file, which will cause ALL of the project JavaScript files to be built into a single file - including "bridge.js" and "bridge.react.js" - so, if you used this option, you would only need to include a single JavaScript file. In this example, it would be just "../output/BridgeReactBlogPost.js").
Now change the "Class1.cs" file (that was created automatically when you requested the new "Class Library" project) thusly:
using Bridge.Html5; using Bridge.React; namespace BridgeReactBlogPost { public class Class1 { [Ready] public static void Main() { React.Render( DOM.Div( new Attributes { ClassName = "wrapper" }, "Hiya!" ), Document.GetElementById("main") ); } } }
.. and then right-click on demo.html, click "View in Browser" and you should be greeted by some React-rendered content. Good start!
Update (2nd December 2015): I originally showed a non-static method above with a [Ready] attribute on it - this worked in earlier versions of Bridge but does not work any longer. In the examples in this post, using an instance method with the [Ready] attribute will result in the method NOT being called at DOM ready (it will appear to fail silently by doing no work but showing no warnings). Don't make my mistake, make [Ready] methods static!
Now, let's be slightly more ambitious -
[Ready] public static void Main() { React.Render( DOM.Div(new Attributes { ClassName = "wrapper" }, DOM.Input(new InputAttributes { OnChange = e => Window.Alert(e.CurrentTarget.Value), MaxLength = 3 }) ), Document.GetElementById("main") ); }
Re-build then use "View in Browser" again. Now each change to the input box is thrown back in your face in an alert. The type of "e.CurrentTarget" is "InputElement" and so there is a string "Value" property available. And the "InputAttributes" class allows the setting of all of the properties that are specific to an InputElement, such as "MaxLength". This is one of the great things about using a type system to document your API - you use types (such as requiring an InputAttributes instance when DOM.Input is called) to inform the user of the API; what can and can't be done. And, while I've got a lot of respect for the people maintaining the DefinitelyTyped TypeScript type definitions, you don't get as much detail in their React bindings as are available here!
In fairness, I should really give credit where it's due here - the "InputElement" type comes from the Bridge.Html5 namespace, so I haven't had to write all of those definitions myself. And the "InputAttributes" class was based upon the InputElement's source code; I only had to remove read-only properties (for example, the html "input" element has a "valueAsNumber" property - only applicable to input elements with type "number" - that is read-only and so it would not make sense for this to be settable as a React attribute). I also had to remove some unsupported functionality (for example, checkbox input elements support an "indeterminate" flag in browsers but this is not supported by React).
All of the element factory methods in React ("div", "span", "input", etc..) have corresponding methods in the bindings, with types that express any additional properties that should be available - eg. we have
ReactElement TD( TableCellAttributes properties, params Any<ReactElement, string>[] children );
where the "TableCellAttributes" introduces additional properties such as "int ColSpan" and "int RowSpan" (note that the bindings all use pascal-cased function and type names since this is what is more commonly seen in C# code - where the functions are translated into JavaScript they will automatically use the camel-cased JavaScript names, so "Div" becomes "div", for example).
But this is the boring stuff - as soon as you start using React, you want to create your own components!
React 0.14 introduced a concept, the "Stateless Component". In native JavaScript, this is just a function that takes a props reference and returns a React element. But to make it feel more natural in C#, the bindings have a base class which can effectively become a Stateless Component - eg.
public class MyLabel : StatelessComponent<MyLabel.Props> { public MyLabel(Props props) : base(props) { } public override ReactElement Render() { return DOM.Label( new LabelAttributes { ClassName = props.ClassName }, props.Value ); } public class Props { public string Value; public string ClassName; } }
The "StatelessComponent" base class takes a generic type parameter that describe the "props" reference type. Then, when "Render" is called, the "props" reference will be populated and ready to use within Render. If any other functions are declared within the class, they may be called from Render as you might expect (see further down). So we are able to write very simple custom components that React will treat as these special Stateless Components - about which, Facebook say:
In the future, we’ll also be able to make performance optimizations specific to these components
Creating one of these components is as easy as:
React.Render( new MyLabel(new MyLabel.Props { ClassName = "wrapper", Value = "Hi!" }), Document.GetElementById("main") );
It is important to note, however, that - due to the way that React creates components - the constructor of these classes must always be a no-op (it won't actually be called when React prepares the component) and the only data that the class can have passed in must be described in the props data. If you tried to do something like the following then it won't work -
public class MyLabel : StatelessComponent<MyLabel.Props> { private readonly int _index; public MyLabel(Props props, int index) : base(props) { // THIS WON'T WORK - the constructor is not processed _index = index; } public override ReactElement Render() { return DOM.Label( new LabelAttributes { ClassName = props.ClassName }, props.Value + " (index: " + _index + ")" ); } public class Props { public string Value; public string ClassName; } }
You can use instance members if you want to, you just can't rely on them being set in the constructor because the constructor is never called. Side note: I'm thinking about trying to write a C# Analyser to accompany these bindings so that any rules like this can be pointed out by the compiler, rather than you just having to remember them.
public class MyLabel : StatelessComponent<MyLabel.Props> { private int _index; public MyLabel(Props props) : base(props) { } public override ReactElement Render() { // Accessing instance fields and methods is fine, so long as it // isn't done in the constructor SetIndex(); return DOM.Label( new LabelAttributes { ClassName = props.ClassName }, props.Value + " (index: " + _index + ")" ); } private void SetIndex() { _index = MagicStaticIndexGenerator.GetNext(); } public class Props { public string Value; public string ClassName; } }
You can also create custom components that have child elements. Just like "DOM.Div" takes an attributes reference (its "Props", essentially) and then an array of child elements, the StatelessComponent class takes a params array after that first "props" argument.
This array has elements of type "Any<ReactElement, string>", which means that it can be the result of a React factory method (such as "Div") or it can be a string, so that text elements can be easily rendered. Or it can be any class that derives from StatelessComponent as StatelessComponent has an implicit cast operator to ReactElement.
(Note: There used to be a ReactElementOrText class mentioned here but it didn't offer any benefit over Bridge's generic Any<,> class, so I've changed the NuGet package - as of 1.3.0 / 27th September 2015 - and have updated this post accordingly).
So, we could create a simple "wrapper" component that renders a Div with a class and some children -
public class MyWrapper : StatelessComponent<MyWrapper.Props> { public MyWrapper(Props props, params Any<ReactElement, string>[] children) : base(props, children) { } public override ReactElement Render() { return DOM.Div( new Attributes { ClassName = props.ClassName }, Children ); } public class Props { public string ClassName; } }
And render it like this:
React.Render( new MyWrapper(new MyWrapper.Props { ClassName = "wrapper" }, DOM.Span(null, "Child1"), DOM.Span(null, "Child2"), DOM.Span(null, "Child3") ), Document.GetElementById("main") );
or even just like:
React.Render( new MyWrapper(new MyWrapper.Props { ClassName = "wrapper" }, "Child1", "Child2", "Child3" ), Document.GetElementById("main") );
The "Children" property accessed within MyWrapper is exposed through StatelessComponent and will echo back the child elements passed into the constructor when the component instance was declared. If there were no children specified then it will be an empty array.
This brings us on to the next topic - Keys for dynamic children. To aid React's reconciliation process in cases where dynamic children elements are specified, you should specify Key values for each item. Each Key should be consistent and unique within the parent component (for more details, read the "Keys / Reconciliation" section from the Facebook docs).
If you were declaring React components in vanilla JavaScript, then this would be as easy as including a "key" value in the props object. Using these Bridge bindings, it's almost as simple - if your component needs to support an optional "Key" property then its Props class should include a "Key" property. And that's all that's required! You don't need to set anything to that Key inside your component, you merely need to allow it to be set on the props. React will accept numeric or string keys, so I would recommend that you declare the "Key" property as either an int or a string or as an Any<int, string>, which is built-in Bridge class that allows either of the value types to be used. To illustrate:
public class MyListItem : StatelessComponent<MyListItem.Props> { public MyListItem(Props props) : base(props) { } public override ReactElement Render() { return DOM.Li(null, props.Value); } public class Props { public Any<int, string> Key; public string Value; } }
Note: In the earlier examples, the "Child{x}" elements were fixed at compile time and so didn't need Key properties to be set, but if you were displaying a list of search results that were based on data from an api call, for example, then these elements would NOT be fixed at compile time and so you should specify unique Key values for them.
So far, I've only talked about stateless components, which are like a slimmed-down version of full React components. But sometimes you need a stateful component, or one that supports the full React lifecycle.
For these times, there is another base class - simply called Component. This has two generic type parameters, one for the "props" data and for "state". However, the constructor signature is the same as the StatelessComponent; it takes a props reference and then any children element that the component instance has. The state reference is controlled by the two React component lifecycle functions "GetInitialState" and "SetState". "GetInitialState" is called when the component is first created and "SetState" can be used to not only update the internal "state" reference but also request that the component re-render.
The most basic example would be something like this:
// Note: I've not even declared a class fortthe State, I've just used // "string" since the state in this class is just a string value. But // that's because I'm lazy, the state was more complicated then it // could be a separate class, just like Props. public class StatefulControlledTextInput : Component<StatefulControlledTextInput.Props, string> { public StatefulControlledTextInput(Props props) : base(props) { } protected override string GetInitialState() { return ""; } public override ReactElement Render() { return DOM.Input(new InputAttributes { ClassName = props.ClassName, Type = InputType.Text, Value = state, OnChange = ev => SetState(ev.CurrentTarget.Value) }); } public class Props { public string ClassName; } }
Each time the input's value is changed, the component calls its own SetState function so that it can re-render with the new value (there's a good Facebook summary article if you've forgotten the difference between "controlled" and "uncontrolled" components; the gist is the controlled components only raise events when the user requests that their values change, they won't be redrawn unless React cause them to redraw).
This isn't all that the Component class allows, though, it has support for the other React component lifecycle methods - for example, sometimes the "OnChange" event of a text input is raised when the content hasn't really changed (if you put focus in a text input and [Ctrl]-[C] / copy whatever value is in it and then [Ctrl]-[V] / paste that value straight back in, the OnChange event will be raised even though the new value is exactly the same as the old value). You might consider this redraw to be unacceptable. In which case, you could take advantage of the "ShouldComponentUpdate" function like this:
public class StatefulControlledTextInput : Component<StatefulControlledTextInput.Props, string> { public StatefulControlledTextInput(Props props) : base(props) { } protected override string GetInitialState() { return ""; } protected override bool ShouldComponentUpdate( StatefulControlledTextInput.Props nextProps, string nextState) { return (props != nextProps) || (state != nextState); } public override ReactElement Render() { return DOM.Input(new InputAttributes { ClassName = props.ClassName, Type = InputType.Text, Value = state, OnChange = ev => SetState(ev.CurrentTarget.Value) }); } public class Props { public string ClassName; } }
Now, in the cases where the input's value doesn't really change, the component's "update" will be bypassed.
Clearly, this is a trival example, but it demonstrates how you could do something more complicated along these lines. All of the other functions "ComponentDidMount", "ComponentDidUpdate", "ComponentWillMount", "ComponentWillReceiveProps", "ComponentWillUnmount" and "ComponentWillUpdate" are also supported.
And, of course, the Component base class has the same "Children" integration that StatelessComponent has and the same support for specifying a "Key" props value.
There is one little oddity to be aware of, though: In React, "setState" has (in my opinion) a slightly odd behaviour in that it will accept a "partial state value" that it will then merge with the current state reference. So if you had a MyComponentState class with properties "Value1" and "Value2" then you could, in vanilla JavaScript React, call setState({ Value1: whatever }) and it would take that "Value1" and overwrite the current "Value1" in the current state reference, leaving any existing "Value2" untouched. In these bindings, you must specify an entire State reference and this merging does not occur - the old State reference is replaced entirely by the new. This is largely because the "SetState" function in the bindings takes a full "State" class reference (C# doesn't really have a concept of a part-of-this-class representation) but it's also because I think that it's clearer this way; I think that you should be explicit about what you're setting State to and having it be a-bit-of-what-was-there-before and a-bit-of-something-new is not as clear (if you ask me) as a complete here-is-the-new-state reference.
In React, it is strongly recommended that props and state be considered to be immutable references. In the examples here I've used immutability-by-convention; the "props" classes have not actually been immutable types. I'm intending to write a follow-up article or two because there is more that I want to explore, such as how to use these bindings to write React apps in a "Flux"-like manner and how to take more advantage of genuinely immutable types. But, hopefully, this has been a nice enough introduction into the bindings and got you thinking about trying to use C# to write some React apps! Because, if you're aiming to write a web application in a "Single Page Application" style, if your application is of any serious complexity then you're going to end up with quite a lot of code - and, while I have a real soft spot for JavaScript, if it comes to maintaining a large app that's written in JavaScript or that's written in C# then I know which way I would lean! Thank goodness Bridge.net has come along and let us combine JavaScript frameworks with C# :)
Posted at 23:29
Just
Dan is a big geek who likes making stuff with computers! He can be quite outspoken so clearly needs a blog :)
In the last few minutes he seems to have taken to referring to himself in the third person. He's quite enjoying it. | http://www.productiverage.com/Archive/11/2015 | CC-MAIN-2017-13 | refinedweb | 3,358 | 52.49 |
Example: Program to Sort Strings in Dictionary Order
public class Sort { public static void main(String[] args) { String[] words = { "Ruby", "C", "Python", "Java" }; for(int i = 0; i < 3; ++i) { for (int j = i + 1; j < 4; ++j) { if (words[i].compareTo(words[j]) > 0) { // swap words[i] with words[j[ String temp = words[i]; words[i] = words[j]; words[j] = temp; } } } System.out.println("In lexicographical order:"); for(int i = 0; i < 4; i++) { System.out.println(words[i]); } } }
Output
In lexicographical order: C Java Python Ruby
In the above program, the list of 5 words to sorted is stored in a variable, words.
Then, we loop through each word (words[i]) and compare it with all words (words[j]) after it in the array. This is done by using the string's compareTo() method.
If the return value of compareTo() is greater than 0, it has to be swapped in position, i.e. words[i] comes after words[j]. So, in each iteration, words[i] contains the earliest word. | https://www.programiz.com/java-programming/examples/lexicographical-order-words | CC-MAIN-2021-04 | refinedweb | 171 | 63.7 |
Python is an open-source scripting language and includes various modules and libraries for information extraction and retrieval. In this article, we will be discussing Data Retrieval Using Python and how to get information from APIs that are used to share data between organizations and various companies. The hypertext transfer protocol (HTTP) is defined as an application protocol which is used distributed information systems for communication for the World Wide Web.
Python handles all the HTTP requests and integration with web services seamlessly. When a user uses Python language, there is no need to manually add query strings to your URLs or to form encode POST data. The installation of the requests library is managed with the following command:
Output
Web APIs include various sections which are mentioned as follows:
1. Method
2. Base URI
3. Element
4. Media types
The sections of web APIs for specific URL is described as below:
The method is a part of the HTTP protocol which includes methods such as GET, POST, PUT, and DELETE. Usually, these verbs do what their meaning implies i.e. getting data, changing data, or deleting it. In requests, the return value of HTTP is a response object.
Code Implementation to get a text of the response
>>> import requests >>> response = requests.get("") >>> type(response) <class 'requests.models.Response'> >>> print(response) <Response [200]> >>> print(response.text)
The output of the Data Retrieval Using Python, the response received is as follows:
JSON Parsing:
JavaScript Object Notation(JSON) is a notation used to define objects in JavaScript. The python library “requests” has built a JSON parser into its Response object. It can also convert Python dictionaries into JSON strings. Consider the following example which explains JSON parsing.
{ "first_name": "xyz", "last_name": "abc" }
It can be parsed with the Python code as mentioned below:
import json >>> parsed_json= json.loads(json_string) >>> print(parsed_json) {'last_name': 'abc', 'first_name': 'xyz'} >>> print(parsed_json['first_name']) xyz
You can also dump the key-value pair into JSON format.
Web Scraping:
Web scraping is a basic practice of using a computer program or various web scraping tools to sift through a web page and gather the data in a systematic format. In other words, web scraping also called “Web harvesting”, “web data extraction” is the construction of an agent to parse or organize data from the web in an automated manner.
The method of web scraping can be used for the following scenarios:
- Retrieving information from a table on the wiki page.
- A user may want to get the listing of reviews for a particular movie to perform text mining. Users can even a build predictive model to spot fake reviews.
- Displaying analysis in visualization manner.
- Enrich the data set based on the information available on the specified website.
- It sounds very interesting to track trending news stories on a particular topic of interest.
But do bear in mind that if you use web scrapers without any proxies, any search engine that you use for web scraping will block or ban your IP address.
And in order for marketers and technical guys to overcome this hurdle, the use of rotating residential proxies, captcha solvers, and authentication tools have been readily available on the web. You can actually read about the Zenscrape residential proxies on the internet.
Example:
In this example, we will be focusing on hacking a web page and storing the information in a dictionary format. Hacker News is a popular aggregator of news articles that is found interesting by all hackers. For hacking a specific it is important to have three plugins installed in your system which are mentioned below:
1. Requests
2. Re
3. BeautifulSoup
The command for the installation of plugin is:
# Importing plugins import requests import re from bs4 import BeautifulSoup articles = [] url = '' #website which is used for hacking r = requests.get(url) #fetching all the requests html_soup = BeautifulSoup(r.text, 'html.parser') for item in html_soup.find_all('tr', class_='athing'): item_a = item.find('a', class_='storylink') item_link = item_a.get('href')if item_a else None item_text = item_a.get_text(strip=True) if item_a else None next_row = item.find_next_sibling('tr') item_score = next_row.find('span', class_='score') item_score = item_score.get_text(strip=True) if item_score else '0 points' # We use regex here to find the correct element item_comments = next_row.find('a', string=re.compile('\d+( |\s)comment(s?)')) item_comments = item_comments.get_text(strip=True).replace('\xa0', ' ') \ if item_comments else '0 comments' #Storing articles in JSON or dictionary format articles.append({ 'link': item_link, 'title': item_text, 'score': item_score, 'comments': item_comments}) for article in articles: print(article)
Explanation:
1. The requests are fetched with respect to values fetched in the URL.
2. With the list of items used for iteration using for loop, it helps us to maintain a systematic approach of creating JSON (key-value) pairs.
3. The dictionary (JSON) value created includes a parameter of link, score, title, and comments.
Output:
The above illustration explains the web scraping concept without reference to any API. Web Scraping is considered beneficial over the use of API due to the following constraints:
1. The website where a user is focusing on the information extraction does not provide ant API (Application Programming Interface).
2. The API provided is not free of cost.
3. API provided is limited, which means a user can access them only for a specific period of time.
4. API does not expose the data which is needed, but the website does.
Conclusion:
Data science research analysts using Python can easily scrap or fetch the information from the given website for the research outputs. Information Retrieval with Python goes through a simple procedure by showing how to handle the cookies and session values. We also focussed on various methods used for information retrieval which can be used in research.
Also Read- Python vs JavaScript: The Competition Of The Giants! | https://blog.eduonix.com/software-development/data-retrieval-using-python/ | CC-MAIN-2022-33 | refinedweb | 965 | 55.84 |
28 May 2010 16:07 [Source: ICIS news]
SHANGHAI (ICIS news)--Bayer MaterialScience (BMS) is confident that its 2010 full-year earnings before interest, taxation, depreciation and amortisation (EBITDA) will be double those of the previous year, the company’s CEO said on Friday.
BMS’s Patrick Thomas said he expected the second quarter to be slightly better than the first, while the 2010 full-year results would double that of 2009.
He was interviewed at the opening of BMS’s AutoCreative centre in ?xml:namespace>
The driver of the company’s growth in 2010 would be polycarbonates (PC), owing to the boom in electronics, office equipment and flat-screened TV panels, Patrick Thomas said.
“
“Meanwhile, optic disc storage is also performing surprisingly well,” he said.
Each year BMS purchases $3bn-4bn (€2.4bn-3.2bn) worth of benzene, toluene and phenol for feedstock, which leaves the company open to risks from volatile aromatics prices, he said.
“The downside risk is only on high material cost,” said Thomas.
The company is a major producer of polyurethanes (PU), toluene diisocyanate (TDI) and methylene di-p-phenylene (MDI).
PU demand had seen speculative growth in
“This year the growth won’t be that much and will be closer to GDP. If demand remains the same as [the first quarter], the annual growth of PU demand from the automotive sector in
The company’s CEO said: “As the world’s largest consumer and manufacturer of automobiles,
($1 = €0.81)
For more on Bayer MaterialScience visit ICIS company intelligence
For more on polycarbon | http://www.icis.com/Articles/2010/05/28/9363431/bayer-materialscience-to-double-2010-ebitda-ceo-patrick.html | CC-MAIN-2014-52 | refinedweb | 259 | 59.74 |
ISP configuration structure. More...
#include <dc/flashrom.h>.
The area code the user is in.
Broadcast address.
Call waiting prefix.
DNS servers (2)
Various flags that can be set in options.
Gateway address.
DHCP/Host name.
Host IP address.
The long-distance dial prefix.
DHCP, Static, dialup(?), PPPoE.
The modem init string to use.
Netmask.
Outside dial prefix.
Phone number 1's area code.
Phone number 2's area code.
Phone number 1.
Phone number 2.
POP3 server.
POP3 login.
POP3 passwd.
PPP login.
PPP password.
Proxy server hostname.
Proxy server port.
The "Real Name" field of PlanetWeb.
SMTP server.
Which fields are valid? | http://cadcdev.sourceforge.net/docs/kos-2.0.0/structflashrom__ispcfg.html | CC-MAIN-2017-13 | refinedweb | 104 | 82.51 |
If you’ve ever read any beginner’s articles about Ruby on Rails, you’ll know that quite a bit of thought has been put into the code base that makes up the Rails framework. Over time, many of the internals have been rewritten, which has improved their speed and efficiency and allowed the implementation of additional features, but the original architecture remains largely unchanged.
In this article, I’ll help beginners take that next step by examining the inner workings of Rails. If you’re yet to experiment with Rails, I’d recommend you download a free preview of my new book, Simply Rails 2, from which this information is excerpted. The chapter presented here gives a surface-level tour of the Ruby on Rails framework, and prepares the reader for building a digg-clone, which we’ve named (somewhat cheekily) Shovell. If you need installation and other setup instructions, download the sample PDF, which contains chapters 1 to 4.
Three Environments
Rails encourages the use of a different environment for each of the stages in an application’s life cycle — development, testing, and production. If you’ve been developing web applications for a while, this is probably how you operate anyway; Rails just formalizes these environments.
development
In the development environment, changes to an application’s source code are immediately visible; all we need to do is reload the corresponding page in a web browser. Speed is not a critical factor in this environment. Instead, the focus is on providing the developer with as much insight as possible into the components responsible for displaying each page. When an error occurs in the development environment, we are able to tell at a glance which line of code is responsible for the error, and how that particular line was invoked. This capability is provided by the stack trace (a comprehensive list of all the method calls leading up to the error), which is displayed when an unexpected error occurs.
test
In testing, we usually refresh the database with a baseline of dummy data each time a test is repeated: this step ensures that the results of the tests are consistent, and that behavior is reproducible. Unit and functional testing procedures are fully automated in Rails.
When we test a Rails application, we don’t view it using a traditional web browser. Instead, tests are invoked from the command line, and can be run as background processes. The testing environment provides a dedicated space in which these processes can operate.
production
By the time your application finally goes live, it should be sufficiently tested that all — or at least most — of the bugs have been eliminated. As a result, updates to the code base should be infrequent, which means that the production environments can be optimized to focus on performance. Tasks such as writing extensive logs for debugging purposes should be unnecessary at this stage. Besides, if an error does occur, you don’t want to scare your visitors away with a cryptic stack trace; that’s best kept for the development environment.
As the requirements of each of the three environments are quite different, Rails stores the data for each environment in entirely separate databases. So at any given time, you might have:
- live data with which real users are interacting in the production environment
- a partial copy of this live data that you’re using to debug an error or develop new features in the development environment
- a set of testing data that’s constantly being reloaded into the testing environment
Let’s look at how we can configure our database for each of these environments.
Database Configuration
Configuring the database for a Rails application is incredibly easy. All of the critical information is contained in just one file. We’ll take a close look at this database configuration file, then create some databases for our application to use.
The Database Configuration File
The separation of environments is reflected in the Rails database configuration file
database.yml. We saw a sample of this file back in Chapter 1, and in fact we created our very own configuration file in Chapter 2, when we used the
rails command. Go take a look — it lives in the
config subdirectory of our Shovell application.
With the comments removed, the file should look like this:
Example 4.1.
01-database.yml
development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000
test:
adapter: sqlite3
database: db/test.sqlite3
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
timeout: 5000
This file lists the minimum amount of information we need in order to connect to the database server for each of our environments (development, test, and production). With the default setup of SQLite that we installed in Chapter 2, every environment is allocated its own physically separate database file, which calls the
db subdirectory home.
The parameter database sets the name of the database that is to be used in each environment. As the configuration file suggests, Rails can support multiple databases (and even different types of database engines, such as MySQL for production and SQLite for development) in parallel. Note that we're actually talking about different databases here, not just different tables -- each database can host an arbitrary number of different tables in parallel.
Figure 1 shows a graphical representation of this architecture.
However, there's one startling aspect missing from our current configuration: looking at the
db subdirectory, the databases referenced in our configuration file don't exist yet! Fear not, Rails will auto-create them as soon as they're needed. There's nothing we need to do as far as they are concerned.
The Model-View-Controller Architecture
The model-view-controller (MVC) architecture that we first encountered in Chapter 1 is not unique to Rails. In fact, it predates both Rails and the Ruby language by many years. However, Rails really takes the idea of separating an application's data, user interface, and control logic to a whole new level.
Let's take a look at the concepts behind building an application using the MVC architecture. Once we have the theory in place, we'll see how it translates to our Rails code.
MVC in Theory
MVC is a pattern for the architecture of a software application. It separates an application into the following hands the retrieved data to the view.
- The view is rendered and sent back to the client for the browser to display.
This process is illustrated in Figure 2.
Separating a software application into these three distinct components is a good idea for a number of reasons, including the following:
It improves scalability (the ability for an application to grow).
For example, if your application begins experiencing performance issues because database access is slow, you can upgrade the hardware running the database without other components being affected.
It makes maintenance easier.
As the components have a low dependency on each other, making changes to one (to fix bugs or change functionality) does not affect another.
It promotes reuse.
A model may be reused by multiple views, and vice versa.
If you haven't quite got your head around the concept of MVC yet, don't worry. For now, the important thing is to remember that your Rails application is separated into three distinct components. Jump back to Figure 2 if you need to refer to it later on.
MVC the Rails Way
Rails promotes the concept that models, views, and controllers should be kept quite separate by storing the code for each of these elements as separate files in separate directories.
This is where the Rails directory structure that we created back in Chapter 2 comes into play. The time has come for us to poke around a bit within that structure. If you take a look inside the app directory, which is depicted in Figure.)
This separation continues within the code that comprises the framework itself. The classes that form the core functionality of Rails reside within the following modules:
ActiveRecord
ActiveRecordis the module for handling business logic and database communication. It plays the role of model in our MVC architecture. (While it might seem odd that
ActiveRecorddoesn't have the word "model" in its name, there is a reason for this: Active Record is also the name of a famous design pattern -- one that this component implements in order to perform its role in the MVC world. Besides, if it had been called
ActionModelthen it would have sounded more like an overpaid Hollywood star than a software component ...)
ActionControlleris the component that handles browser requests and facilitates communication between the model and the view. Your controllers will inherit from this class. It forms part of the
ActionPacklibrary, a collection of Rails components that we'll explore in depth in Chapter 5.is designed to handle all of an application's tasks that relate to the database, including:
- establishing a connection to the database server
- retrieving data from a table
- storing new data in the database
ActiveRecordalso has a few other neat tricks up its sleeve. Let's look at some of them now. Database Abstraction
ActiveRecordships with database adapters to connect to SQLite, MySQL, and PostgreSQL. A large number of adapters are also available for other popular database server packages, such as Oracle, DB2, and Microsoft SQL Server, via the RubyGems system. The
ActiveRecordmodule is based on the concept of database abstraction. As we mentioned in Chapter 1, database abstraction is a way of coding an application so that it isn't dependent upon any one database. should be required. Examples of code that differs greatly between vendors, and which
ActiveRecordabstracts, include:
- the process of logging into the database server
- date calculations
- handling of boolean (
true/
false) data
- evolution of your database structure
ActiveRecordin action, though, we need to do a little housekeeping. Database Tables Tables are the containers within a. An example of a table is shown in Figure 4.
storieswhich consists of five rows, this table will store the data for five
Storyobjects. The nicest thing about the mapping between classes and tables is that you don't need to write code to achieve it -- the mapping just happens, because
ActiveRecordinfobject in Ruby, we're dealing with a single story. But the SQL table holds a multitude of stories, so its name should be plural. While you can override these conventions -- as is sometimes necessary when dealing with legacy databases -- it's much easier to adhere to them. The close relationship between tables and objects extends even further: if our
storiestable were to have a
linkcolumn, as our example in Figure 4 does, the data in this column would automatically be mapped to the
linkattribute in a
Storyobject. SQLite console. You could type out the following SQL commands, although typing out SQL isn't much fun. Instead, I encourage you to download the following script from the code archive, and copy and paste it straight into your SQLite console that you invoked via the following command in the application directory:
$ sqlite3 db/development.sqlite3
Once your SQLite console is up, paste in the following:
Example 4.2.
02-create-stories-table.sql
CREATE TABLE stories (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"name" varchar(255) DEFAULT NULL,
"link" varchar(255) DEFAULT NULL,
"created_at" datetime DEFAULT NULL,
"updated_at" datetime DEFAULT NULL
);
You needn't worry about remembering these SQL commands to use in your own projects; instead, take heart in knowing that in Chapter 5 we'll look at migrations. Migrations are special Ruby classes that we can write to create database tables for our application without using any SQL at all.
Using the Rails Console
Now that we have our stories table in place, let's exit the SQLite console (simply type
.quit) and open up a Rails console. A Rails console is just like the interactive Ruby console (
irb) that we used in Chapter 3, but with one key difference. In a Rails console, you have access to all the environment variables and classes that are available to your application while it's running. These are not available from within a standard
irb console.
To enter a Rails console, change to your
shovell folder, and enter the command
ruby script/console, as shown below. The
>> prompt is ready to accept your commands:
$ cd shovell
$ ruby script/console
>>
Saving an Object
To start using
ActiveRecord, simply define a class that inherits from the
ActiveRecord::Base class. (We touched on the
:: operator very briefly in Chapter 3, where we mentioned that it was a way to invoke class methods on an object. It can also be used to refer to classes that exist within a module, which is what we're doing here.) Flip back to the section on object oriented programming (OOP) in Chapter 3 id: nil, name: nil, url: nil, created_at: nil,
updated_at: nil>
>> story.class
=> Story(id: integer, name: string, link: string,
created_at: datetime, updated_at: datetime)
As you can see, the syntax for creating a new
ActiveRecord object is identical to the syntax we used to create other Ruby objects in Chapter 3. At this point, we've created a new
Story object. However, this object exists in memory only -- we haven't stored it in our database yet.
We can confirm the fact that our Story object hasn't been saved yet by checking the return value of the
new_record? method:
>> story.new_record?
=> true
Since it can be. the sake Rails
ActiveRecord module in more detail in Chapter 5.
The
ActionPack Module
ActionPackis the name of the library that contains the view and controller parts of the MVC architecture. Unlike the
ActiveRecordmodule, these modules are a little more intuitively named:
ActionControllerand
ActionView. Exploring application logic and presentation logic on the command line doesn't make a whole lot of sense; views and controllers are designed to interact with a web browser, after all! Instead, I'll just give you a brief overview of the
ActionPackcomponents, and we'll cover the hands-on stuff in Chapter 5.
ActionController(the Controller)%MINIFYHTML74ec242a8a79671e75d2857f5d05436224%The controller handles the application logic of your program, acting
- one controller for displaying story links, which we'll name StoriesController
- another controller for handling user authentication, called SessionsController
- a controller to display user pages, named UsersController
- and finally a fourth controller to handle story voting, called VotesController
ActionController::Base class, but they'll have different functionality, implemented as instance methods. (There will actually be an intermediate class between this class and the
ActionController::Baseclass; we'll cover the creation of the StoriesController class in more detail in Chapter 5. However, this doesn't change the fact that
ActionController::Baseis the base class from which every controller inherits.) Here's a sample class definition for the
StoriesControllerclass:
class StoriesController < ActionController::Base
def index
end
def show
end
end
This simple class definition sets up our
StoriesController with two empty methods: the
index method, and the show
method. We'll expand upon both of these methods in later chapters.
Each controller resides in its own Ruby file (with a
.rb extension), which lives within the
app/controllers directory. The
StoriesController class that we just defined, for example, would inhabit the file
app/controllers/stories_controller.rb.
Naming Classes and Files
You'll have noticed by now that the names of classes and files follow different conventions:
- Class names are written in CamelCase (each word beginning with a capital letter, with no spaces between words). There are actually two variations of CamelCase: one with an uppercase first letter (also known as PascalCase), and one with a lowercase first letter. The Ruby convention for class names requires an uppercase first letter.
- Filenames are written in lowercase, with underscores separating each word.
This is an important detail! If this convention is not followed, Rails will have a hard time locating your files. Luckily, you won't need to name your files manually very often, if ever, as you'll see when we look at generated code in Chapter 5.
ActionView (the View)
As we discussed earlier, the case may write code like this:
<strong><?php echo 'Hello World from PHP!' ?></strong>
The equivalent code in ERb would be the following:
<strong><%= 'Hello World from Ruby!' %></strong>
There are two forms of the ERb tag pair: one that includes the equal sign, and one that doesn't:
<%= ... %>
This tag pair is for regular output. The output of a Ruby expression between these tags will be displayed in the browser.
<% ... %>
This tag pair is for code that is not intended to be displayed, such as calculations, loops, or variable assignments.
An example of each ERb tag file a Rails developer needs to modify is the template, which is the file that contains the presentation code for the view. As you might have guessed, these templates are stored in the
app/views folder.
As with everything else is twofold and varies depending on the template's type and the actual language in which a template is written. By default there are three types of extensions in Rails:
html.erb
This is the extension for standard HTML templates that are sprinkled with ERb tags.
xml.builder
This extension is used for templates that output XML (for example, to generate RSS feeds for your application).
js
StoriesController class defined earlier. Invoking the show method for this controller would, by default, attempt to display the
ActionView template that lived in the
app/views/stories directory. Assuming the page was a standard HTML page (containing some ERb code), the name of this template would be
show.html.erb..
Communication between controllers and views occurs via instance variables that are populated from within the controller's action. Let's expand upon our sample StoriesController class to illustrate this point (there's no need to type any of this out just yet):
class Stories -- and allow the view to display just the end result of the computation.
Rails also provides access to special containers, such as the
params and
session hashes. These contain such information as the current page request and the user's session. We'll make use of these hashes in the chapters that follow.
The REST
When I introduced Rails in Chapter 1, I mentioned quite a few common development principles and best practices that the Rails team advises you to adopt in your own projects. One that I kept under my hat until now was RESTful-style development, or resource-centric development. REST will make much more sense with your fresh knowledge about models and controllers as the principal building blocks of a Rails application.
In Theory
REST stands for Representational State Transfer and originates from the doctoral dissertation of Roy Fielding, one of the co-founders of The Apache Software Foundation and one of the authors of the HTTP specification.
REST, according to the theory, is not restricted to the World Wide Web. The basis of the resource-centric approach is derived from the fact that most of the time spent using network-based applications can be characterized as a client or user interacting with distinct resources. For example, in an ecommerce application, a book and a shopping cart are separate resources with which the customer interacts.
Every resource in an application needs to be addressed by a unique and uniform identifier. In the world of web applications, the unique identifier would be the URL by which a resource can be accessed. In our Shovell application, each submitted story will be able to be viewed at a unique URL.
The potential interactions within an application are defined as a set of operations (or verbs) that can be performed with a given resource. The most common verbs are create, read, update, and delete, which are often collectively referred to as "CRUD operations." If you relate this to our Shovell application you'll see that it covers most of the interactions possible with the Shovell stories: a user will create a story, another user will read the story, the story can also be updated or deleted.
The client and server have to communicate via the same language (or protocol) in order to implement the REST architecture style successfully. This protocol is also required to be stateless, cacheable, and layered.
Here, stateless means that each request for information from the client to the server needs to be completely independent of prior or future requests. Each request needs to contain everything necessary for the server to understand the request and provide an appropriate answer.
Cacheable and layered are architectural attributes that improve the communication between client and server without affecting the communication protocol.
REST and the Web
As mentioned in the previous section, REST as a design pattern can be used in any application domain. But the Web is probably the domain that implements REST most often. Since this is a book that deals with building web applications, we'd better take a look at the implementation details of RESTful style development in web applications in particular.
HTTP (Hypertext Transfer Protocol: the communication protocol used on the Web), as the astute reader will know, also makes heavy use of verbs in its day-to-day operations. When your browser requests a web page from any given web server, it will issue a so-called
GET-request. If you submit a web page form, your browser will do so using a
POST-request (not always, to be honest, but 99% of the time).
In addition to
GET and
POST, HTTP defines two additional verbs that are less commonly used by web browsers. (In fact, none of the browsers in widespread use actually implement them.) These verbs are
PUT and
DELETE. If you compare the list of HTTP verbs with the verbs of CRUD from the previous section, they line up fairly nicely, as you can see in Table 1.
Table 1. HTTP Verbs Versus CRUD Verbs
The language in which client (the browser) and server (the web server) talk to each other is obviously HTTP. HTTP is, by definition, stateless. This means that as soon as a browser has downloaded all of the information the server offered as a reply to the browser's request, the connection is closed and the two might never ever talk again. Or the browser could send another request just milliseconds later, asking for additional information. Each request contains all the necessary information for the server to respond appropriately, including potential cookies, the format, and the language in which the browser expects the server to reply.
HTTP is also layered and cacheable, both of which are attributes the REST definition expects of the spoken protocol. Routers, proxy servers, and firewalls are only three (very common) examples of architectural components that implement layering and caching on top of HTTP.
REST in Rails
REST and Rails not only both start with the letter R, they have a fairly deep relationship. Rails comes with a generator for resources (see the section called "Code Generation" for a primer on this topic) and provides all sorts of assistance for easy construction of the uniform addresses by which resources can be accessed.
Rails's focus on the MVC architecture (which we'll be getting our hands on in Chapter 5) is also a perfect companion for RESTful style development. Models resemble the resources themselves, while controllers provide access to the resource and allow interaction based on the interaction verbs listed above.
I mentioned in the previous section that two verbs aren't implemented in the majority of browsers on the market. To support the verbs
PUT and
DELETE, Rails uses
POST requests with a little tacked-on magic to simulate the
PUT and
DELETE verbs transparently for both the user and the Rails application developer. Nifty, isn't it?
We will gradually start implementing and interacting with resources for our Shovell application over the course of the next hands-on chapters, so let's now move on and talk about yet another batch of components that make up the Rails framework.
Code Generation
Rather than having us create all of our application code from scratch, Rails gives us the facility to generate an application's basic structure with considerable ease. In the same way that we created our application's entire directory structure, we can create new models, controllers, and views using a single command.
To generate code in Rails, we use the
generate script, which lives in the
script folder. Give it a try now: type
ruby script/generate without any command parameters. Rails displays an overview of the available parameters for the command, and lists the generators from which we can choose, as Figure 5 illustrates.
Rails can generate code of varying complexity. At its simplest, creating a new controller causes a template file to be placed in the appropriate subdirectory of your application. The template itself consists of a mainly empty class definition, similar to the
Story and
Author classes that we looked at earlier in this chapter.
However, code generation can also be a very powerful tool for automating complex, repetitive tasks; for instance, you might generate a foundation for handling user authentication. We'll launch straight into generating code in Chapter 5, when we begin to generate our models and controllers.
Another example is the generation of a basic web-based interface to a model, referred to as scaffolding. We'll also look at scaffolding in Chapter 5, as we make a start on building our views.
ActionMailer
While not strictly part of the Web, email is a big part of our online experience, and Rails's integrated support for email is worth a mention. Web applications frequently make use of email for tasks like sending sign-up confirmations to new users and resetting a user's password.
ActionMaileris the Rails component that makes it easy to incorporate the sending and receiving of email into your application.
ActionMaileris structured in a similar way to
ActionPackin that it consists of controllers and actions with templates.
While the creation of emails, and the processing of incoming email, are complex tasks,
ActionMailerhides these complexities and handles the tasks for you. This means that creating an outgoing email is simply a matter of supplying the subject, body, and recipients of the email using templates and a little Ruby code. Likewise,
ActionMailerprocesses incoming email for you, providing you with a Ruby object that encapsulates the entire message in a way that's easy to access.
Adding email functionality to a web application is beyond the scope of this book, but you can read more about
ActionMaileron the Ruby on Rails wiki.
Testing and Debugging
As mentioned in Chapter 1, an automated testing framework is already built into Ruby on Rails. It also, rather helpfully, supplies a full stack trace for errors to assist with debugging.
Testing
A number of different types of testing are supported by Rails, including automated and integration testing.
Automated Testing
The concept of automated testing isn't new to the world of traditional software development, but it's fairly uncommon in web application development. While most Java-based web applications make use of comprehensive testing facilities, a large number of PHP and Perl web applications go live after only some manual tests have been performed (and sometimes without any testing at all!). Although performing automated tests is optional, developers may decide against this option for reasons ranging from the complexity of the task to time constraints.
We touched on this briefly in Chapter 1, but it's worth stressing again: the fact that comprehensive automated testing is built into Rails, and is dead easy to implement, means there's no longer a question about whether or not you should test your apps. Just do it!
The
generatecommand that we introduced a moment ago can automatically create testing templates that you can use with your controllers, views, and models. (Note that Rails just assists you in doing your job, it's not replacing you -- yet!)
The extent to which you want to implement automated testing is up to you. It may suit your needs to wait until something breaks, then write a test that proves the problem exists. Once you've fixed the problem so that the test no longer fails, you'll never again get a bug report for that particular problem.
If, on the other hand, you'd like to embrace automated testing completely, you can even write tests to ensure that a specific HTML tag exists at a precise position within a page's hierarchy Document Object Model (DOM). Yes, automated tests can be that exact.
Integration Testing
Rails's testing capabilities also include integration testing.
Integration testing refers to the testing of several web site components in succession -- typically, the order of the components resembles the path that a user would follow when using the application. You could, for example, construct an integration test that reconstructs the actions of a user clicking on a link, registering for a user account, confirming the registration email you send, and visiting a page that's restricted to registered users.
We'll look at both automated testing and integration testing in more detail as we progress through the development of our application.
Debugging
When you're fixing problems, the first step is to identify the source of the problem. Like many languages, Rails assists this process by providing the developer (that's you!) with a full stack trace of the code. We mentioned earlier in the section called "Three Environments" that a stack trace is a list of all of the methods that were called up to the point at which an exception was raised. The list includes not only the name of each method, but also the classes those methods belong to, and the names of the files they reside within.
Using the information contained in the stack trace, you can go back to your code to determine the problem. There are several ways to tackle this, depending on the nature of the problem itself:
- If you have a rough idea of what the problem may be, and are able to isolate it to your application's model (either a particular class or aspect of your data), your best bet is to use the Rails console that we looked at earlier in this chapter. Type
consolefrom the
scriptdirectory to launch the console. Once inside, you can load the particular model that you're interested in, and poke at it to reproduce and fix the problem.
- If the problem leans more towards something related to the user's browser or session, you can add a
debuggerstatement around the spot at which the problem occurs. With this in place, you can reload the browser and step through your application's code using the ruby-debug tool to explore variable content or to execute Ruby statements manually.
We'll be covering all the gory details of debugging in Chapter 11.
Summary
In this chapter, we peeled back some of the layers that comprise the Ruby on Rails framework. By now you should have a good understanding of which parts of Rails perform particular roles in the context of an MVC architecture. We also discussed how a request that's made by a web browser is processed by a Rails application.
We looked at the different environments that Rails provides to address the different stages in the life cycle of an application, and we configured databases to support these environments. We also provided Rails with the necessary details to connect to our database.
We also had our first contact with real code, as we looked at the
ActiveRecord models,
ActionController controllers, and
ActionView templates for our Shovell application. We explored the topics of the REST style of application architecture, code generation, testing, as well as debugging.
In the next chapter, we'll build on all this knowledge as we use the code generation tools to create actual models, controllers, and views for our Shovell application. It's going to be a big one!
That's it for this excerpt of Simply Rails 2 -- but don't forget that the downloadable PDF contains three more chapters than are included here. See the complete Table of Contents for the full details of what's covered in this book. | http://www.sitepoint.com/rails-for-beginners/ | crawl-003 | refinedweb | 5,373 | 50.67 |
This post comes out of a conversation that I was having with my colleague Pete around the use of the HttpListener class inside of a UWP application.
I’m using HttpListener as an example because it’s the type that we were talking about but there’s many, many other types that I could use instead.
Over the past few years, I’ve been gradually building up a table of APIs in my head partitioned something like;
- .NET APIs that I know are in the .NET Framework
- .NET APIs that I know are available to the UWP developer
and so it’s become easier and easier over time to know that (e.g.) a class like HttpListener isn’t available to the UWP developer because that class wasn’t in the API set offered by .NET Core on which UWP apps are based.
Of course, in recent times .NET Standard 2.0 support has come to UWP apps running on Windows Fall Creators Update as detailed;
Announcing UWP Support for .NET Standard 2.0
and so this means that a UWP application that’s definitely running on Windows build 16299 upwards has access to .NET Standard 2.0 making our example API HttpListener suddenly usable inside of a UWP application.
Knowing whether an API is/isn’t in one of these variants of .NET can be tricky to keep in your head but the “.NET API Browser” web page provides a quick look up;
So, what does this mean? If I’m sitting in a UWP project that has been set to target 16299 upwards of the UWP platform;
and then I can spin up a little piece of a MainPage.xaml type UI;
<Page x: <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Viewbox Margin="40"> <TextBlock> <Run Text="Number of HTTP requests served "/> <Run Text="{x:Bind NumberOfRequests, Mode=OneWay}"/> </TextBlock> </Viewbox> </Grid> </Page>
and marry that up with a little code behind;
using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Runtime.CompilerServices; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace App1 { public sealed partial class MainPage : Page, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public MainPage() { this.InitializeComponent(); this.Loaded += OnLoaded; } public int NumberOfRequests { get => this.numberOfRequests; set { if (this.numberOfRequests != value) { this.numberOfRequests = value; this.FirePropertyChanged(); } } } void FirePropertyChanged([CallerMemberName] string property = null) { this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property)); } ); } async void OnLoaded(object sender, RoutedEventArgs e) { // an endless async method isn't perhaps the nicest thing in the world // but it's very easy to read. this.listener = new HttpListener(); this.listener.Prefixes.Add(""); this.listener.Start(); while (true) { var context = await this.listener.GetContextAsync(); if (context.Request.AcceptTypes.Contains(HTML)) { // Ah, for an HtmlTextWriter being part of .NET Standard 2.0 😉 context.Response.ContentType = "text/html"; context.Response.StatusCode = 200; using (var writer = new StreamWriter(context.Response.OutputStream)) { writer.Write( $"<html><body>{DateTime.Now.ToShortTimeString()}</body></html>"); } this.NumberOfRequests++; } else { context.Response.StatusCode = 501; } context.Response.Close(); } } static readonly string HTML = "text/html"; HttpListener listener; int numberOfRequests; } }
and then make some changes to my application manifest;
and I’ve then got a little web server that I can hit from a second machine asking for //myMachine:8080/whatever and I can see responses being returned and the usage counter going up;
and that all seems to work quite nicely
Again, the use of HttpListener here is just an example – I’m not sure whether/where you’d actually want to build a UWP app that offered up an HTTP server so it’s just an example of an API as it happened to be the one that we were discussing.
Pingback: A Follow-On Prague Experiment with Skeletons – Mike Taulty | https://mtaulty.com/2017/11/30/uwp-and-net-standard-2-0-remembering-the-forgotten-apis/ | CC-MAIN-2021-25 | refinedweb | 627 | 50.23 |
This is a
playground to test code. It runs a full
Node.js environment and already has all of
npm’s 400,000 packages pre-installed, including
detergent with all
npm packages installed. Try it out:
require()any package directly from npm
awaitany promise instead of using callbacks (example)
This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.
a tool to prepare text for pasting into HTML
Online web app:
applicableOpts
opts.cb
npm i detergent
Consume via a
require():
const { det, opts, version } = require("detergent");
or as an ES Module:
import { det, opts, version } from "detergent";
or for web pages, as a production-ready minified script file (so-called "UMD build"), straight from CDN:
<script src=""></script>
// in which case you get a global variable "detergent" which you consume like this: const { det, opts, version } = detergent;
This package has three builds in
dist/ folder:
Detergent is a tool which cleans and prepares text so you can paste it safely into HTML template:
For starters, Detergent will:
Then Detergent will optionally:
£into
£)
Adobe Photoshop and Illustrator both place ETX characters when you insert linebreaks using SHIFT+ENTER to break the line but keep the text within the same paragraph (that's opposed to normal line breaks using ENTER alone which breaks paragraphs). When a text with an ETX character is pasted into HTML template, it is invisible in the code editor but might surface up later as "�" when CMS or ESP or other platform attempts to read the code.
Detergent has optional features to improve the English style:
between last two words
Extra features are:
<BR>'s to appear: with a closing slash (XHTML) or without (HTML), so your HTML code should be passing the W3C validator.
instead of
) so you can read and recognise them. Not all named HTML entities work in all email clients, so we did the testing, found out which-ones don't render correctly and set those to be numeric.
The main function is exported in a plain object under key
detergent, so please import it like that:
const { det } = require("detergent"); // or request everything: const { det, opts, version } = require("detergent"); // this gives extra plain object `exportedOpts` with default options. Handy when // developing front-ends that consume the Detergent.
det is the main function. See its API below.
opts is default options' object. You pass it (or its tweaked version) to
det.
version returns same-named package.json key's value - the version of the particular copy of Detergent you've got.
det()Input
The
det above is a function. You pass two input arguments to it:
det()options object
Here it is in one place:
det("text to clean", { fixBrokenEntities: true, removeWidows: true, convertEntities: true, convertDashes: true, convertApostrophes: true, replaceLineBreaks: true, removeLineBreaks: false, useXHTML: true, dontEncodeNonLatin: true, addMissingSpaces: true, convertDotsToEllipsis: true, stripHtml: true, stripHtmlButIgnoreTags: ["b", "strong", "i", "em", "br", "sup"], stripHtmlAddNewLine: ["li", "/ul"], cb: null });
The default set is a wise choice for the most common scenario - preparing text to be pasted into HTML.
You can also set the options to numeric
0 or
1, that's shorter than Boolean
true or
false.
det()output object
Function
det returns a plain object, for example:
{ } }
applicableOpts
Next generation web applications are designed to show only the options that are applicable to the given input. This saves user's time and also conserves mental resources — you don't even need to read all the labels of the options if they are not applicable.
Detergent currently has 14 option keys, 12 of them boolean. That's not a lot but if you use the tool every day, every optimisation counts.
I got inspiration for this feature while visiting competitor application — it has 110 checkboxes grouped into 12 groups and options are hidden twice — first sidebar is hidden when you visit the page, second, option groups are collapsed.
Another example of overwhelming options set — Kangax minifier — — it's got 26 options with heavy descriptions.
Detergent tackles this problem by changing its algorithm: it processes the given input and then makes a note, is particular option applicable or not, independently, is it enabled or not. Then, if it's enabled, it changes the result value.
For example, detergent's output might look like this — all options not applicable because there's nothing to do on "abc":
{ } }
The options keys which have values of a type array (
stripHtmlButIgnoreTags and
stripHtmlAddNewLine) are omitted from
applicableOpts report.
The simplest possible operation - encoding using default settings:
const { det } = require("detergent"); let { res } = det("clean this text £"); console.log(res); // > 'clean this text £'
Now, using custom settings object with one custom setting
convertEntities (others are left default):
const { det } = require("detergent"); let { res } = det("clean this text £", { convertEntities: 0 // <--- zero is like "false", turns off the feature }); console.log(res); // > 'clean this text £'
opts.cb
One of the unique (and complex) features of this program is HTML tag recognition. We process only the text and don't touch the tags, for example, widow word removal won't add non-breaking spaces within your tags if you choose not to strip the HTML.
opts.cb lets you perform additional operations on all the string characters outside any HTML tags. We aim to tap detergent.io uppercase-lowercase functionality here but maybe you'll find additional uses.
Here's an example, where we have widow word removal, HTML tags and additionally, with help of
opts.cb, turn all the letters uppercase (but not on HTML tags):
const { det } = require("detergent"); const { res } = det(`aAa\n\nbBb\n\ncCc`, { cb: str => str.toUpperCase() }); console.log(res); // => "AAA<br/>\n<br/>\nBBB<br/>\n<br/>\nCCC"
In monorepo, npm libraries are located in
packages/ folder. Inside, the source code is located either in
src/ folder (normal npm library) or in the root,
cli.js (if it's a command-line application).
The npm script "
dev", the
"dev": "rollup -c --dev" builds the development version retaining all
console.logs with row numbers. It's handy to have js-row-num-cli installed globally so you can automatically update the row numbers on all
console.logs.
MIT License
Passes unit tests from, licenced under CC0-1.0 | https://npm.runkit.com/detergent?t=1580311386869 | CC-MAIN-2020-10 | refinedweb | 1,035 | 50.87 |
<module>
import requests
ImportError: No module named requests
[Finished in 0.1s with exit code 1]
I understand what the error is saying however I do not understand how to import the module into sublime text so that I can use things like "requests" and "json" etc.
I have two questions:
1. Is there a way that I can load all current python modules into sublime text? [if so where do I get that from?]
2. How do I go about adding these modules once I find them? [I would need step by step instructions]
I know this is a very basic set of question, please keep in mind I am new to this. | http://www.sublimetext.com/forum/viewtopic.php?f=2&t=10964&start=0 | CC-MAIN-2015-48 | refinedweb | 114 | 80.51 |
My Vim configuration
I have used Vim almost exclusively for writing code for the past 12 years. When I write prose, I ocasionally use iA Writer, but I tend to introduce :w inavertedly here and there.
I don’t spend much time configuring my Vim, only an evening or two a year, or when I try a new language and I need to install some syntax file. But for the most part of my work, it is quite stable. Recently I did a raid searching for new plugins or stuff I could use and was very productive.
I won’t try to convince you to use Vim. I do not know if Vim is better or not for you. I have two very big barriers that prevent me for even trying other environments. First, I am too used to this way of working, that allows me to quickly open a Vim in whatever terminal in any machine — remote or not — and use most of my configuration. Second: I am too happy with this and I would be complaining for every extra second of time spent in start-up, updating plugins, or whatever wants the IDE to do.
Since I work mainly with PHP (Symfony2) and Javascript, my environment is more optimized for these languages.
Rather than copying my configuration or anyone else’s, I suggest you to copy only the lines you understand and really want. It is way better than cluttering your configuration with options that you will never need or use. Also, try installing plugins and new features one or two at a time. Most of them require you to mechanize some keystrokes, and, like learning new words, it is better to learn and practice small bits before adding more. At least it is for me.
With that said, you may want to check out spf13’s distribution. It has a nice selection of plugins. I think that is better to hand-pick the ones you want to use, one each week, but it is your call and he did a great work.
My Vim configuration is on Github.
Potwiki
Potwiki by Edwin Steiner manages a very simple wiki in text files in some directory. To opening the main page, I type ,ww and my wiki opens. You can create new articles just by writing the title CamelCase and following the link. As simple as that.
Excellent for taking notes that you can manage in a VCS.
There are other wiki engines out there that come with TODO-list management and other goodies, but as I am happy with the simplicity of Potwiki, and also I have no intention of throwing my wiki away or converting it to a different syntax, I don’t care much about them. They are probably great, though, so you may want to check out other options first.
Solarized
Solarized by Ethan Schoonover is a color schema created with a lot of principles in mind. I do not care much about the exact principles behind it, but it is so clear that someone has put so much thought on a color schema that it feels like an insult to him to continue using the color schema “elflord” just because I like the nerdy name.
Also, it comes in two versions: light and dark. I normally use the dark one, but during conferences I can switch quickly to the lighter one, which is more beamer-friendly pressing ,b. For doing this you can add these lines to .vimrc:
" solarized toggle background function! ToggleBackground() if (w:solarized_style=="dark") let w:solarized_style="light" colorscheme solarized else let w:solarized_style="dark" colorscheme solarized endif endfunction command! Togbg call ToggleBackground() nnoremap <leader>b :call ToggleBackground()<CR> inoremap <leader>b <ESC>:call ToggleBackground()<CR> vnoremap <leader>b <ESC>:call ToggleBackground()<CR>
Snipmate & Neosnippet
With sniptmate by garbas you can write snippets in a snippets folder, organized by filetype (.php, .js, .erl…), and they will be available for autocompletion. Very nice for some repetitive tasks, like writing constructor functions, new classes, annotations, or whatever you may need. It comes also with a lot of preinstalled snippets.
Neosnippet by Shoguo does basically the same, but makes these snippets available for Neocomplete (discussed below). Since I was using snipmate, and they are compatible, now I use both.
Neocomplete
Autocompletion, autocompletion, autocompletion. Using several sources: snippets, filenames, previously used words, exuberant ctags for code… This is very very nice. Check it out here.
Of course this works better with exuberant ctags. For a Symfony2 project, what works best for me is this
.ctags configuration, placed at the root of the project:
-R --languages=php --php-kinds=cif --exclude=.git/* --exclude=app/* --exclude=bin/* --exclude=web/* --exclude=tests/* --exclude=*/Test/* --exclude=*/Tests/* --exclude=*test* --exclude=*Form/Type* --exclude=vendor/*/vendor
This will generate a
tags file that will be used for autocompletion, jumping to definitions and things like that.
ctrlp
ctrlp by kien is a finder. You can open it by, of course, pressing CTRL+P and this will open a small window at the bottom with several options to find files.
There are several keystrokes worth to remember, but two will unleash 80% of the goodies: CTRL+F to navigate forward in the list of modes and CTRL+B to navigate backwards. The modes are:
- MRU: Most recently used files.
- Buffers
- Files
Also, if you use ctlrp-funky by tacahiroy you will have a new mode containing the tags of the current file (even if you don’t use crags). For example, the function definitions. If you want to access this useful mode directly you can do it with ,fu.
Tagbar
tagbar by majutsushi allows you to open a side window with the tags of the current file, as some IDEs do. I open it with ,tb This is useful in some cases, if you want to have a map of the file in mind. Still, I normally prefer ctrlp-funky for jumping into tags.
NERD Tree
NERD Tree by scrooloose is a filesystem explorer. I was using ranger in the past, but since I am too lazy to install it in every machine I have access to, now I just use NERD Tree and then I have one less thing to install.
As usual in the Vim world, NERD Tree has a very complete documentation, but with just one command you have a lot: ,n (my binding for
:NERDTreeToggle).
If you feel adventurous you can check out the documentation to find more about file navigation, bookmarking files, and so on.
PHP & Symfony2 specifics
PIV
PIV by spf13 is a full PHP integration environment for Vim, with better completion, indenting, support for PHP 5.3 namespaces and such, and PHPDoc goodies.
The PHPDoc part is tricky. With ,pd you can insert PHPDoc snippets according to the context. This needs configuration and, as far as I know, it can only be done by manually editing the plugin file in
.vim/bundle/PIV/ftplugin/php/doc.vim. If you know a better way, please let me know.
PHP namespace
vim-php-namespace by arnaud-lib allows you to insert
use statements for the class under the cursor by pressing ,u, which saves time.
Vim Twig
vim-twig by beyondwords provides twig syntax highlighting and useful snippets. No more tweaking Vim to use Jinja syntax for your Twig templates.
PHP CS fixer
vim-php-cs-fixer by stephpy allows you to run
php-cs-fixer to your files.
php-cs-fixer is a tool created by Fabien Potencier that fixes trivial violations of the PSR-1 and PSR-2 documents.
With ,pcf it will fix the current file, and with ,pcd it will fix the current directory. Sweet.
Vdebug
Vdebug by joonty is a multi-language debugger client for several languages, PHP included.
This (beware, it will be open a big face staring at you) is a good post about how to configure Xdebug and Vdebug to work together and do some debug.
And that is it. I know that there are endless plugins, and many will be very good, but these ones are the ones I use, and, since each plugin takes some time to get used to it, I prefer to try one at a time and make its keystrokes a natural extension of the toolbelt. | http://nacho-martin.com/my-vim-configuration.html | CC-MAIN-2017-26 | refinedweb | 1,382 | 71.04 |
Lastly, with any Python challenge, I ALWAYS get people asking "can I use a different language", this time, I want to challenge you to use Python. You can use an Online Interpreter to test your code, so you won't even need to download anything new. On top of that, there are so many python resources out there, it should be easy for you to create something, ANYTHING!
Your submission can be multiple lines if you need extra code to set things up, so for example, here's my one liner. It's based on Dogstopper's Character Flipper snippet.
def inverter(original = None): if original == None: original = input(">>> ") return ''.join([char.upper() if char.islower() else char.lower() for char in str(original)])
Notice how my submission is 4 lines, but only 1 line (number 4) will be judged.
Good luck everyone, and I hope to see a lot of participation! | http://www.dreamincode.net/forums/topic/278267-one-liner-challenge/page__pid__1616748__st__0 | CC-MAIN-2013-20 | refinedweb | 152 | 73.98 |
25 January 2010 08:30 [Source: ICIS news]
SHANGHAI (ICIS news)--China-based Maoming Petrochemical expects to restart its 640,000 tonne/year No 2 cracker at Maoming in early February, a company source said on Monday.
The cracker had been shut for nearly 40 days for a scheduled turnaround, the source at the Sinopec subsidiary said.
Ethylene supply in the local south China market had slightly tightened due to the shut down.
“We made a small change on the shutdown time and period earlier. The cracker was taken offline on 27 December, three days later than the original date,” the source said in Mandarin.
The company’s No 1 cracker with a capacity of 380,000 tonnes/year would be shut down for a 30-day turnaround in October, the source added. .
Maoming Petrochemical is located at Maoming city in the southern ?xml:namespace> | http://www.icis.com/Articles/2010/01/25/9328348/chinas-maoming-pc-to-restart-no-2-cracker-in-early.html | CC-MAIN-2015-22 | refinedweb | 145 | 60.35 |
This is split out from D44748, and is intended to be landed before D44748.
The only functional change intended here is contained inside of LocationSize::print: we'll now print LocationSize(N) instead of N to represent location sizes. If the location size is unknown, we'll print LocationSize(unknown) instead of UINT64_MAX (and similar for map tombstone/empty keys). I added the LocationSize prefix because I plan to add precise/unknown markers in D44748.
Accidentally left in LocationSize::precise. Oops. :)
Ok, I think you missed my point in the other review. The entire idea was to have something which was so obviously correct it didn't need further review. Specifically, to avoid waiting for me or anyone else to review it. Unfortunately, we're now in the worst of both worlds: this change does not appear to be fully NFC and we had a long review delay.
Let me now try to be a bit more specific.
Please declare a *typedef* of uint64_t (not a class) called LocationSize in the MemoryLocation.h header within the llvm namespace. Update all the parameters and fields which are currently uint64_t, but will eventually be a LocationSize. Do not change the meaning of the bit-patterns in any way. Make sure it builds and passes make check, then submit without further review.
Once done, discard this change and rebase your original change over the typedef. This should greatly reduce the LOC changed.
To preserve the old behavior, doesn't this need to be 0?
I recommend leaving this out in the first patch. This part starts changing semantics. Please do the large change *without* changing semantics, then a small patch with the semantic change.
Thanks for the clarification, and sorry about the misunderstanding. I submitted the bit-for-bit NFC patch as r333314, and will rebase the original review soon. :)
If the goal is to preserve bit-for-bit behavior, yes. I failed to mention that I ran tests/built meaningful things with LLVM with assert(isSizeSet()) before all Size accesses, and saw 0 issues. So, I assumed the intent was for size to always be set before anything attempted to access it. Hence, barring a few pathological cases with size nearing UINT64_MAX, the initial value doesn't appear to matter.
I considered this to be more noise than a meaningful functionality change, but I also didn't realize your intent was to have me submit something without review. With that in mind, yes, this change doesn't make much sense in this patch. :) | https://reviews.llvm.org/D45581 | CC-MAIN-2022-27 | refinedweb | 421 | 65.93 |
I need functional language algorithm help
#1 Crossbones+ - Reputation: 4688
Posted 27 April 2013 - 11:28 PM
Second, this is not homework. I'm self-learning.
Now, I've made two attempts at this problem. First and Second. My issue is that I know I'm doing something wrong. But I don't know what it is. My process of going through the problem is jacked somehow. In the first attempt, the code looks like right. I'm using recursion, following the steps the book has laid out (to the best of my understanding). But the result produced is the answer plus junk. In the second attempt, there is some recursion and helper functions. And the answers are correct. However, the code feels .... wrong. As if I didn't do it the Scheme way. It's like writing C with classes and not idiomatic C++. It's right, but it's wrong.
So any tips, hints, pointing in the right direction, would be greatly appreciated. Crossbones+ - Reputation: 1412
Posted 28 April 2013 - 08:13 AM
The approach is fine, you just haven't written it neatly.
- Your argument names are cryptic and sometimes in an illogical order.
- You write extra functions that obscure rather than clarify. For instance, I have no idea what "move-letters" is supposed to do and what arguments it's supposed to take unless I read the code. And when I read the code, I find it's just (append x (list y)). Stuff like this is better inlined.
- You should always nest definitions that are only intended to be used inside another function. It makes the structure of the code far easier to comprehend, plus it often further simplifies code by allowing you to drop any function arguments that are already defined in the outer scope.
I wrote an exact Scala equivalent to your insert-everywhere/in-one-word function but fixed all of the above. I think it looks fine with these changes. Note how the recursive helper has one less argument than yours, and one function even turned into a local definition with no arguments.
def insertEverywhere(c: Char, string: List[Char]) = { def recInsert(stringBefore: List[Char], stringAfter: List[Char]): List[List[Char]] = { val newWord = stringBefore ::: (c :: stringAfter) if (stringAfter.isEmpty) List(newWord) else newWord :: recInsert(stringBefore ::: List(stringAfter.head), stringAfter.tail) } recInsert(Nil, string) }Direct Racket translation: :: is cons, ::: is append, head is first, tail is rest, Nil is empty, val is define.
Edited by Yrjö P., 28 April 2013 - 08:17 AM.
#3 Crossbones+ - Reputation: 4688
Posted 28 April 2013 - 05:28 PM
Yrjo, thanks!
Out of curiosity, can anyone tell me where I went wrong on the First attempt?<<
#4 Crossbones+ - Reputation: 4688
Posted 30 April 2013 - 02:48 AM
And the scheme/racket version of your code:
(define (insert-everywhere c string) (local [(define (recursive-insert string-before string-after) (local [(define new-word (append string-before (cons c string-after)))] (cond [(empty? string-after) (list new-word)] [else (cons new-word (recursive-insert (append string-before (list (first string-after))) (rest string-after)))])))] (recursive-insert empty string))) (insert-everywhere "w" (list "e" "a" "r"))
Edited by Alpha_ProgDes, 30 April 2013 - 03:16 AM.
Super Mario Bros clone tutorial written in XNA 4.0 [MonoGame, ANX, and MonoXNA] by Scott Haley
If you have found any of the posts helpful, please show your appreciation by clicking the up arrow on those posts
#5 Members - Reputation: 1594
Posted 30 April 2013 - 01:02 PM
While your code is certainly correct and written in functional style, I would suggest you try to go one step further. Now, it seems that you are 'inlining' different steps into one big step. Functional programming has the advantage of giving the programmer the possibility to clearly distinguish between different 'levels' of operation, each following a certain pattern.
For example, let's say I have a list of numbers and want to take the sum of the squares of all uneven numbers. The following Haskell-code (I picked Haskell because even if you are not familiar with it, I believe it is more readable than Scheme, as long as I stay away from some of the more arcane notations) does this in a straightforward manner:
bizarreSum :: [Integer] -> Integer ---------------------------------- bizarreSum [] = 0 -- empty list case bizarreSum (x:xs) -- cons case (head = x, tail = xs) | odd x = x * x + bizarreSum xs -- head is odd | otherwise = bizarreSum xs
But one can distinguish three different steps in this algorithm: first, we filter out the even numbers, then we square every number, and finally, we summate. This can be written as
bizarreSum' :: [Integer] -> Integer ----------------------------------- bizarreSum' = foldl (+) 0 . map sqr . filter odd
The dot chains the operations together: filtering, mapping, folding. Filter, map and foldl are three well-known patterns, they are in a way higher-level functional loops. In my opinion, it is preferable to try to find these patterns and try to implement your algorithms using them, as you work on a higher level of abstraction.
Permutation can then be implemented as a series of mapping operations. My Haskell implementation looks like this:
split :: [a] -> [([a], a, [a])] ------------------------------- split xs = [ (take n xs, xs !! n, drop (n+1) xs) | n <- [ 0 .. length xs - 1 ] ] permutations :: [a] -> [[a]] ---------------------------- permutations [] = [[]] permutations xs = do (prefix, x, postfix) <- split xs p <- permutations (prefix ++ postfix) return (x : p)
The permutations function first splits a list [a(1), a(2), ..., a(n)] up in three parts: a prefix list [a(1)..a(i-1)], an element x=a(i), and a postfix list [a(i+1)..a(n)], for every possible i (this is a map). Then for all permutations p of prefix++postfix (again a map) it prepends x=a(i) to the front of p. So, this is akin to a nested loop, or in our case, a map within a map. In above Haskell code, you can interpret "x <- xs" as "for each x in xs" (it uses monads, which are a very powerful concept, and I love to explain people about them, but now it is a bit out of scope of this post).
In your first attempt, insert-everywhere/in-all-words seems to be wrong:
(insert-everywhere/in-all-words 1 '((2 3))) '((1 2 3) (1 3 2) (2 1 3) (3 2 1) (3 1 2) (2 3 1))
I don't think it is supposed to generate all permutations of (2 3) in this example. I didn't take the time to inspect your code thoroughly, but I did notice a lot of conds and recursion, which means that you are constantly reimplementing functional building blocks, map in your case.
Final note: it is true that bizarreSum' is less memory-efficient than bizarreSum, as each time a new list must be created in memory (however, this does not apply to Haskell as it is a nonstrict language, but in most other languages, this could be an actual issue). However, would performing your own inlining not be a case of premature optimisation? If it is your intention to practice functional programming, I believe it is more important to focus on learning to think on a higher level than to be efficient.
Edited by SamLowry, 30 April 2013 - 03:12 PM. | http://www.gamedev.net/topic/642402-i-need-functional-language-algorithm-help/ | CC-MAIN-2014-35 | refinedweb | 1,211 | 70.02 |
Courts of original and appellate jurisdiction Courts of record and not of record
Courts of original jurisdiction – Those courts in Courts of record – Those whose proceedings arewhich, under the law, actions or proceedings enrolled and which are bound to keep a writtenmay be originally commenced. record of all trials and proceedings handled by them. [Regalado] One attribute of a court ofCourts of appellate jurisdiction – Courts which record is the strong presumption as to thehave the power to review on appeal the veracity of its records that cannot be collaterallydecisions or orders of a lower court. [Regalado] attacked except for fraud. All Philippine courts, including inferior courts, are now courts ofCourts of general and special jurisdiction record. [Riano]
Courts of general jurisdiction – Those competent Courts not of record – Courts which are notto decide their own jurisdiction and to take required to keep a written record or transcript ofcognizance of all kinds of cases, unless proceedings held therein.otherwise provided by the law or Rules. Principle of Judicial HierarchyCourts of special or limited jurisdiction – Thosewhich have no power to decide their own The judicial system follows a ladderized schemejurisdiction and can only try cases permitted by which in essence requires that lower courtsstatute. [Regalado] initially decide on a case before it is considered by a higher court. Specifically, under the judicialConstitutional and statutory courts policy recognizing hierarchy of courts, a higher court will not entertain direct resort to it unlessConstitutional courts – Those which owe their the redress cannot be obtained in thecreation and existence to the Constitution and, appropriate courts. [Riano citing Santiago v.therefore cannot be legislated out of existence or Vasquez (1993)]deprived by law of the jurisdiction and powersunqualifiedly vested in them by the Constitution. The principle is an established policy necessarye.g. Supreme Court; Sandiganbayan is a to avoid inordinate demands upon the Court’sconstitutionally-mandated court but created by time and attention which are better devoted tostatute. those matters within its exclusive jurisdiction, and to preclude the further clogging of theStatutory courts – Those created, organized and Court’s docket [Lim v. Vianzon (2006)].with jurisdiction exclusively determined by law.[Regalado] When the doctrine/principle may be disregarded: A direct recourse of the Supreme Court’s originalCourts of law and equity jurisdiction to issue writs (referring to the writs of certiorari, prohibition, or mandamus) should beCourts of Law- Those courts which administer allowed only when there are special andthe law of the land. They settle cases according important reasons therefor, clearly andto law. specifically set out in the petition. [Mangahas v. Paredes (2007)]. The Supreme Court mayCourts of Equity- Those courts which rules disregard the principle of hierarchy of courts ifaccording to the precepts of equity or justice. warranted by the nature and importance of theThey settle cases according to the principles of issues raised in the interest of speedy justiceequity referring to principles of justice, fainess and avoid future litigations [Riano].and fair play. Doctrine of Non-Interference or Doctrine ofPhilippine courts are both courts of law and Judicial Stabilityequity. Hence, both legal and equitablejurisdiction is dispensed with in the same The principle holds that courts of equal andtribunal [U.S. v. Tamparong (1998)] coordinate jurisdiction cannot interfere with each other’s orders [Lapu-lapu Development andSuperior and Inferior Courts Housing Corp. v. Group Management Corp. (2002)] The principle also bars a court fromSuperior courts – Courts which have the power of reviewing or interfering with the judgment of areview or supervision over another and lower co-equal court over which it has no appellatecourt. jurisdiction or power of review [Villamor v. Salas (1991)].The doctrine of non-interference applies with General Rule: No court has the authority toequal force to administrative bodies. When the interfere by injunction with the judgment oflaw provides for an appeal from the decision of another court of coordinate jurisdiction or toan administrative body to the SC or CA, it means pass upon or scrutinize and much less declare asthat such body is co-equal with the RTC in terms unjust a judgment of another courtof rank and stature, and logically beyond thecontrol of the latter [Phil Sinter Corp. v. Cagayan Exception: The doctrine of judicial stability doesElectric Power (2002)]. not apply where a third party claimant is involved
JURISDICTION How jurisdiction over the DEFENDANT is acquired - Acquired by the 1. Voluntary appearance or submission by the defendant or respondent to the courtJURISDICTION IN GENERAL or 2. By coercive process issued by the courtJurisdiction is defined as the authority to try, to him, generally by the service ofhear and decide a case [Tolentino v. Leviste summons [de Joya v. Marquez (2006),(2004)]. citing Regalado]
Judicial power includes the duty of the courts of NOTE: In an action in personam, jurisdiction overjustice: [Art 8, Sec. 1, Constitution] the person is necessary for the court to validly 1. To settle actual controversies involving try and decide the case, while in a proceeding in rights which are legally demandable and rem or quasi in rem, jurisdiction over the person enforceable; of the defendant is not a prerequisite to confer 2. To determine WON there has been a jurisdiction on the court provided the latter has grave abuse of discretion amounting to jurisdiction over the res [Alba v. CA (2005)]. lack or excess of jurisdiction on the part of any government branch/ JURISDICTION OVER THE SUBJECT MATTER instrumentality. Jurisdiction over the subject matter is the powerAll courts exercise judicial power. Only the to deal with the general subject involved in theSupreme Court is the court created by the action, and means not simply jurisdiction of theConstitution [Art 8, Sec. 1, Constitution]. The particular case then occupying the attention ofSandiganbayan is a Constitutionally mandated the court but jurisdiction of the class of cases tocourt, but it is created by statute. [PD 1486] which the particular case belongs (Riano citing CJS).
REQUISITES FOR A VALID EXERCISE OF It is the power to hear and determine cases ofJURISDICTION the general class to which the proceedings in 1. Court must have jurisdiction over the question belong [Reyes v. Diaz (1941)] persons of the parties 2. It must have jurisdiction over the subject matter of the controversy Jurisdiction versus the exercise of jurisdiction 3. It must have jurisdiction over the res 4. It must have jurisdiction over the issues Jurisdiction: the authority to hear and determine a cause — the right to act in a case. [Arranza v. BF Homes (2000)].JURISDICTION OVER THE PARTIES ‘Exercise of Jurisdiction.’: the exercise of thisThe manner by which the court acquires power or authorityjurisdiction over the parties depends on whetherthe party is the plaintiff or the defendant. Jurisdiction is distinct from the exercise thereof. Jurisdiction is the authority to decide a case andThe mode of acquisition of jurisdiction over the not the decision rendered therein. When there isplaintiff and the defendant applies both to jurisdiction over the subject matter, the decisionordinary and special civil actions. on all other questions arising in the case is but an exercise of jurisdiction. [Herrera v. Baretto etHow jurisdiction over the PLAINTIFF is acquired - al (1913)]Jurisdiction over the plaintiff is acquired by filingof the complaint or petition. By doing so, hesubmits himself to the jurisdiction of the court Error of Jurisdiction as distinguished from Error of[Davao Light & Power Co., Inc. v CA (1991)]. Judgment
Error of judgment Error of jurisdiction the prescribed docket fee vest a trial court with jurisdiction over the subject It is one which the matter or the nature of the action [CB v. court may commit in CA (1992)](2008 Bar Exam). the exercise of its a. Exception: Non-payment of docket feeIt is one where the act jurisdiction [Cabrera does not automatically cause the complained of was v. Lapid (2006)]. dismissal of the case on the ground of issued by the court It includes errors of lack of jurisdiction as long as the feewithout or in excess of procedure or is paid within the applicablejurisdiction [Cabrera v. mistakes in the prescriptive or reglementary period, Lapid (2006)]. court’s mistakes in more so when the party involved the court’s findings demonstrates a willingness to abide [Banco Filipino by the rules prescribing such Savings v. CA (2000)] payment. [Go v. Tong (2003)]Correctible only by the Correctible by appeal extraordinary writ of [Cabrera v Lapid Doctrine of Primary Jurisdiction certiorari [Cabrera v (2006)] Lapid (2006)] Ground for reversal Courts cannot and will not resolve a controversy only if it is shown that involving a question which is within the Renders a judgment jurisdiction of an administrative tribunal, prejudice has beenvoid or voidable [Rule especially where the question demands the caused [Banco 16 Sec. 1, Rule 65] exercise of sound administrative discretion Español-Filipino v Palanca (1918)] requiring the special knowledge, experience and services of the administrative tribunal to determine technical and intricate matters of factHow conferred and determined: [Paloma v. Mora (2005)]. 1. Jurisdiction being a matter of substantive law, the statute in force at the time of the Objective is to guide a court in determining commencement of the action determines whether it should refrain from exercising its the jurisdiction of the court. jurisdiction until after an administrative agency has determined some question or some aspect 2. It is conferred only by the Constitution or of some question arising in the proceeding the law. before the court [Riano citing Omictin v. CA (2007)] 3. Jurisdiction CANNOT be: a. Fixed by agreement of the parties; b. Cannot be acquired through, or Doctrine of Adherence of Jurisdiction waived, enlarged or diminished by, any act or omission of the parties; Also known as doctrine of continuity of c. Neither can it be conferred by the jurisdiction acquiescence of the court [Regalado citing De Jesus v Garcia (1967)]. The court, once jurisdiction has been acquired, d. Cannot be subject to compromise retains that jurisdiction until it finally disposes of [Civil Code, Art 2035] the case [Bantua v. Mercader (2001)].
6. Once attached to a court, it cannot be Objections to Jurisdiction over the Subject Matter ousted by subsequent statute. a. Exception: The statute itself When it appears from the pleadings or evidence conferring new jurisdiction expressly on record that the court has no jurisdiction over provides for retroactive effect. the subject matter, the court shall dismiss the [Southern Food v. Salas (1992)] same. (Sec. 1, Rule 9)
7. The filing of the complaint or appropriate The court may on its OWN INITIATIVE object to initiatory pleading and the payment of an erroneous jurisdiction and may ex mero motutake cognizance of lack of jurisdiction at any enter into agreement simplifying thepoint in the case and has a clearly recognized issues of the case.right to determine its own jurisdiction [Fabian v. 3. Waiver or failure to object to theDesierto (1998)]. presentation of evidence on a matter not raised in the pleadings. Here the partiesEarliest opportunity of a party to raise the issue try with their express or implied consentof jurisdiction is in a motion to dismiss filed or issues not raised by the pleadings. Thebefore the filing or service of an answer. Lack of issues tried shall be treated in all respectsjurisdiction over subject matter is a ground for a as if they had been raised in themotion to dismiss. If no motion is filed, the pleadings.defense of lack of jurisdiction may be raised asan affirmative defense in the answer. [Rianociting Sec. 1(b) and 6 of Rule 16]. JURISDICTION OVER THE RES OR PROPERTY IN LITIGATIONJurisdiction over the subject matter may beraised at any stage of the proceedings, even for Jurisdiction over the res refers to the court’sthe first time on appeal. When the court jurisdiction over the thing or the property whichdismisses the complaint for lack of jurisdiction is the subject of the action.over the subject matter, it is common reasonthat the court cannot remand the case to Jurisdiction over the res may be acquired by theanother court with the proper jurisdiction. Its courtonly power is to dismiss and not to make any 1. By placing the property or thing under itsother order. custody (custodia legis) a. The seizure of the thing under legal process whereby it is brought intoEffect of Estoppel on Objections to Jurisdiction actual custody of law b. Example: attachment of property.General Rule: Estoppel does not apply to confer 2. Through statutory authority conferringjurisdiction to a tribunal that has none over a upon it the power to deal with thecause of action. Jurisdiction is conferred by law. property or thing within the court’sWhere there is none, no agreement of the territorial jurisdictionparties can provide one. Settled is the rule that a. Institution of a legal proceedingthe decision of a tribunal not vested with wherein the power of the court overappropriate jurisdiction is null and void. the thing is recognized and made[SEAFDEC-AQD v. NLRC (1992)] effective b. Example: suits involving the status ofException: Participation in all stages of the case the parties or suits involving thebefore the trial court, that included invoking its property in the Philippines of non-authority in asking for affirmative relief, resident defendants.effectively barred petitioner by estoppel fromchallenging the court’s jurisdiction. [Soliven v.Fastforms (2004)]
CASES COVERED BY THE RULES ON NOTE: It is a condition precedent under Rule 16; BARANGAY CONCILIATION can be dismissed but without prejudice
Exclusive Jurisdiction 1. All cases involving custody, guardianship, JURISDICTION OF THE legitimacy, paternity and filiation arising SANDIGANBAYAN under the Code of Muslim Personal Laws; 2. All cases involving disposition, Original Jurisdiction in all cases involving: distribution and settlement of estate of 1. Violations of RA 3019 (Anti-Graft and deceased Muslims, probate of wills, Corrupt Practices Act) issuance of letters of administration of 2. Violations of RA 1379 (Anti-Ill-Gotten appointment administrators or executors Wealth Act) regardless of the nature or aggregate 3. Sequestration cases (E.O. Nos. 1,2,14,14- value of the property; A) 3. Petitions for the declaration of absence 4. Bribery (Chapter II, Sec. 2, Title VII, Book and death for the cancellation and II, RPC) where one or more of the correction of entries in the Muslim principal accused are occupying the Registries; following positions in the government, 4. All actions arising from the customary whether in permanent, acting or interim contracts in which the parties are capacity at the time of the commission of Muslims, if they have not specified which the offense: law shall govern their relations; and a. Officials of the executive branch 5. All petitions for mandamus, prohibition, occupying the positions of regional injunction, certiorari, habeas corpus and director and higher, otherwise all other auxiliary writs and processes in classified as Grade 27 and higher, of aid of its appellate jurisdiction the Compensation and Position Classification Act of 1989 (RA 6758)Concurrent Jurisdiction b. Members of Congress and officials 1. Petitions of Muslim for the constitution of thereof classified as G-27 and up the family home, change of name and under RA 6758 commitment of an insane person to an c. Members of the Judiciary without asylum prejudice to the provisions of the 2. All other personal and legal actions not Constitution mentioned in par 1 (d) wherein the d. Chairmen and Members of the parties involved are Muslims except those Constitutional Commissions without for forcible entry and unlawful detainer, prejudice to the provisions of the which shall fall under the exclusive Constitution jurisdiction of the MTC. e. All other national and local officials 3. All special civil actions for interpleader or classified as Grade 27 and higher declaratory relief wherein the parties are under RA 6758 Muslims or the property involved belongs f. Other offenses or felonies committed exclusively to Muslims by the public officials and employees mentioned in Sec. 4(a) of RA 7975 asCases Cognizable amended by RA 8249 in relation to laws or special laws administered by their office BOC; g. Civil and criminal cases filed pursuant 5. Decisions of the Central Board of to and in connection with EO Nos. 1, Assessment Appeals in the exercise of its 2, 14-A (Sec. 4, RA 8249) appellate jurisdiction over cases involving the assessment and taxation of real NOTE: Without the office, the crime property originally decided by the cannot be committed. provincial or city board of assessment appeals;Appellate Jurisdiction Over final judgments, 6. Decision of the secretary of Finance onresolutions or orders of the RTC whether in the customs cases elevated to himexercise of their original or appellate jurisdiction automatically for review from decisions ofover crimes and civil cases falling within the the Commissioner of Customs which areoriginal exclusive jurisdiction of the adverse to the government under Sec.Sandiganbayan but which were committed by 2315 of the Tariff and Customs Code;public officers below Salary Grade 27. 7. Decisions of Secretary of Trade and Industry in the case of non-agriculturalConcurrent Original Jurisdiction with SC, product, commodity or article, and theCA, and RTC for petitions for writs of habeas Secretary of Agriculture in the case ofdata and amparo agricultural product, commodity or article, involving dumping duties andNOTE: The requisites that the offender the counterveiling duties under Secs. 301 andoffender occupies salary Grade 27 and the 302, respectively, of the Tariff andoffense must be intimately connected with the Customs Code, and safeguard measuresofficial function must concur for the SB to have under RA 8800, where either party mayjurisdiction appeal the decision to impose or not to impose said duties.
TOTALITY RULE
COMMENCEMENT subject to the specific rules prescribed for a special civil action a. Special
RIGHT OF ACTION vs. CAUSE OF ACTION There is a failure to state a cause of action if the(Regalado) pleading asserting the claim states no cause of action. This is a ground for a motion to dismiss. [Rule 16, Sec.1(g)] Right of action Cause of action It is submitted that the failure to state a cause of action does not mean that the plaintiff has “no cause of action.” It only means that the plaintiff’s allegations are insufficient for the courtto know that the rights of the plaintiff were order that the complaint may beviolated by the defendant. [Riano] dismissed.
There is a failure to state a cause of action if Ratio: A party may not institute more than oneallegations in the complaint taken together, do suit for a single cause of action. [Rule 2, Sec. 3]not completely spell out the elements of a 1. To prevent repeated litigation betweenparticular cause of action. [Riano] the same parties in regard to the same subject or controversy; 2. To protect the defendant fromA failure to state a cause of action is not the unnecessary vexation. Nemo debetsame as an absence or a lack of cause of action. vexare pro una et eadem causa (No manThe former refers to an insufficiency in the shall be twice vexed for one and theallegations of the complaint while the latter same cause);refers to the failure to prove or to establish by 3. To avoid the costs and expenses incidentevidence one’s stated cause of action. [Riano] to numerous suits. [City of Bacolod v. SM Brewery (1969)]
Whether or not admitting the facts alleged, the JOINDER OF CAUSES OF ACTIONcourt could render a valid verdict in accordancewith the prayer of the complaint [Santos v. de It is the assertion of as many causes of action asLeo (2005)] a party may have against another in one pleading alone. It is also the process of uniting 2 or more demands or rights of action in oneSPLITTING A SINGLE CAUSE OF ACTION; action. [Riano citing Rule 2, Sec. 5 and CJS]EFFECTS By a joinder of actions, or more properly, aDefinition: The act of instituting two or more joinder of causes of action is meant the unitingsuits on the basis of the same cause of action. of two or more demands or rights of action in[Rule 2, Sec.4] one action, the statement of more than one cause of action in a declaration [Ada v. BaylonThe act of dividing a single or indivisible cause of (2012)]action into several parts or claims and bringingseveral actions thereon. (Regalado) SPLITTING OF CAUSES JOINDER OF CAUSES There is a single Contemplates severalThe test of singleness of cause of action lies in cause of action causes of actionthe singleness of the delict or wrong violating Prohibited Encouragedthe rights of one person. It causes multiplicity It minimizes of suits and double multiplicity of suitsFor a single cause of action or violation of a vexation on part of and inconvenience onright, the plaintiff may be entitled to several defendant the partiesreliefs. It is the filing of separate complaints forthese several reliefs that constitutes splitting up Ratio: To avoid a multiplicity of suits and toof the cause of action which is proscribed by expedite disposition of litigation at minimumRule 2, Sec. 3 and 4. [City of Bacolod v. SM cost [Ada v. Baylon (2012)]Brewery (1969)] The rule however is purely permissive as theEffects: plaintiff can always file separate actions for each 1. The filing of one or a judgment upon the cause of action. [Baldovi v. Sarte, (1917)] merits in any one is available as a ground for the dismissal of the others. [Rule 2, Joinder shall not include special civil actions Sec.4] governed by special rules. [Ada v. Baylon (2012)] 2. Filing of the 1st complaint may be pleaded in abatement of the 2nd Requisites [Rule 2, Sec. 5]: complaint, on the ground of litis 1. The party joining the causes of action pendentia; or must comply with the rules on joinder of 3. A judgment upon the merits in any of the parties; complaints is available as ground for 2. The joinder shall not include special civil dismissal of the others based on res actions or actions governed by special judicata. rules; 4. A Motion to Dismiss under Rule 16 (litis 3. Where causes of action are between the pendentia or res judicata) may be filed in same parties but pertain to different venues/jurisdictions, the joinder may be allowed in the RTC provided one of the only when the court trying the case has causes of action are within the RTC’s jurisdiction over all of the causes of action jurisdiction and the venue lies therein; therein notwithstanding the misjoinder of the 4. TOTALITY RULE - Where the claims in all same. This is because if the court has no the causes of action are principally for jurisdiction to try the misjoined action, then the recovery of money, the aggregate same must be severed and if not so severed, any amount claimed shall be the test of adjudication rendered by the court with respect jurisdiction. to the same would be a nullity. [Ada v. Baylon (2012)]
Adverse party may contest: Authority may be Distinguished from Joinder of Causes of Actioncontested by the adverse party at any time - In joinder of causes of action, it is enoughbefore judgment is rendered if the cause of action arises out of the - If the court determines after hearing that same contract the party declared indigent has sufficient - Unlike permissive joinder of parties, in income or property, the proper docket joinder of causes of action, there is no and other lawful fees shall be assessed need for a common question of fact or and collected by the clerk of court law
Where the plaintiff is uncertain against whom of A party is misjoined when he is made a party toseveral persons he is entitled to relief, he may the action although he should not be impleaded.join any or all of them in the alternative,although a right to relief against one may be A party is not joined when he is supposed to beinconsistent with a right to relief against the joined but is not impleaded in the action. (Riano)other. (Rule 3, Sec. 13) Effect: 1. Neither misjoinder nor non-joinder ofCOMPULSORY AND PERMISSIVE JOINDER OF parties is a ground for dismissal of anPARTIES action. [Rule 3, Sec. 11] a. Non-joinder of an indispensable party general interest in reputation of a specific is not a ground for outright dismissal. individual. Each of the sugar planters has a Reasonable opportunity must be given separate and distinct reputation in the for his inclusion by amendment of the community not shared by the others. [Riano complaint [Cortez v Avila (1957)]. citing Newsweek, Inc. v. Intermediate Appellate b. In case of non-joinder of a necessary court (1986)] party, if the court should find the reason for such omission A class suit does not require a commonality of unmeritorious, it may order the interest in the questions involved in the suit. inclusion of such omitted necessary What is required by the Rules is a common or party general interest in the subject matter of the 2. Parties may be dropped or added by litigation. [Riano citing Mathay v. Consolidated order of the court on motion of any party Bank &Trust Company (1974)] or on its own initiative at any stage of the action and on such terms as are just. Class Suit Permissive Joinder of [Rule 3, Sec.11] Parties There is a single There are multiple Objections to defects in parties: Objections to cause of action causes of actiondefects in parties should be made at the earliest pertaining to separately belongingopportunity. numerous persons. to several persons. - The moment such defect becomes apparent, a motion to strike the names of the parties must be made. Class Suit Derivative Suit - Objections to misjoinder cannot be raised for the first time on appeal [Lapanday An action brought by Agricultural & Development Corporation minority shareholders v. Estita (2005)] in the name of the corporation to redress wrongs committedCLASS SUIT against it, for which When the subject the directors refuse toRequisites: (Rule 3, Sec. 12) matter of the sue. 1. Subject matter of the controversy is one controversy is one of of common/general interest to many common or general It is a remedy persons; interest to many designed by equity 2. The persons are so numerous that it is persons, and the and has been the impracticable to join them all as parties parties are so principal defense of (i.e. impracticable to bring them all numerous that it is the minority before the court); impracticable to bring shareholders against 3. Parties bringing the class suit are them all before the abuses by the sufficiently numerous and representative court, one or more majority. of the class and can fully protect the may sue or defend for interests of all concerned; the benefit of all. In a derivative action, 4. The representative sues/defends for the [Rule 3, Sec. 12] the real party in benefit of all. interest is the corporation itself, notAny party in interest shall have the right to the shareholders whointervene to protect his individual interest. [Rule actually instituted it3, Sec. 12] [Lim v. Lim Yu (2001))
The service of summons may be effected upon The substitute defendant need not beall the defendants by serving upon any of them, summoned. The order of substitution shall beor upon the person in charge of the office or served upon the parties substituted for the courtplace of business maintained under such name. to acquire jurisdiction over the substitute party[Rule 14, Sec. 8] [Ferreria v Vda de Gonzales (1986)].
If no legal representative is named or if the one General rule: The rule does not consider theso name shall fail to appear within the specified transferee an indispensable party. Hence, theperiod, the court may order the opposing party action may proceed without the need to implead him. are several plaintiffs, in which case theException: When the substitution by or joinder of remaining plaintiffs can proceed with their ownthe transferee is ordered by court. cause of action.
After the lapse of time to file an answer, the plaintiff may move to declare the If defendant motion denied: in default Defendant allowed to file an answer
If motion granted:Court issues order of default and renders judgment or require plaintiff to submit evidence ex parte
FILING AND SERVICE OF PLEADINGS It is not simply the filing of the complaint or appropriate initiatory pleading but the payment PAYMENT OF DOCKET FEES of the prescribed docket fee, that vests a trial Court sets aside order of default and defendant is allowed to filewith court an answer jurisdiction over the subject matter or As a rule, the court acquires jurisdiction over the nature of the action [Proton Pilipinas v. Banque case only upon payment of prescribed fees National de Paris (2005)] Presentation of plaintiff’s evidence ex-parte General rule: Without payment, case is Effect of Failure to Pay Docket Fees at Filing considered not filed. PaymentCase of docket fees is set for pre-trial mandatory and jurisdictional. 1. The Manchester Rule: Manchester v. CA (1987) a. Automatic Dismissal If plaintiff proves his allegations:If plaintiff fails proves his allegations: Judgment by default Case is dismissed b. Any defect in the original pleading 10. Similar papers. resulting in underpayment of the docket fees cannot be cured by amendment, such as by the reduction PERIODS OF FILING OF PLEADINGS of the claim as, for all legal purposes, there is no original complaint over PERIOD which the court has acquired PLEADING PERIOD COUNTED jurisdiction FROM Service of 2. Relaxation of the Manchester Rule by Sun summons, Insurance v. Asuncion (1989) unless a a. NOT automatic dismissal different b. Court may allow payment of fees Within 15 days period is fixed within reasonable period of time. Note by the court that payment should always be within (Rule 11, Sec. the prescriptive period of the action 1 filed. Within 30 days if the defendant is a 3. Further modification by Heirs of Hinog v. Answer to foreign private Receipt of Melicor (2005) the juridical entity summons a. Fees as lien Complaint and service of (Rule 11, Sec. b. Where the trial court acquires summons is made 2) jurisdiction over a claim by the filing on government of the pleading and the payment of official the prescribed filing fee, BUT At least 60 days SUBSEQUENTLY, the judgment awards In case of non- Service of a claim not specified in the pleading, resident extrajudicial or cannot then be estimated, or a defendant on summons claim left for determination by the whom (Sec. 15, Rule court, then the additional filing fee extrajudicial 14) shall constitute a lien on the judgment service is made Answer to Within 15 days Service of a 4. Exception to the Sun Insurance doctrine: AMENDED (if amendment copy of the Gochan v. Gochan Complaint was a matter of amended a. The Sun Insurance rule allowing (amended right) complaint payment of deficiency does not apply counterclai where plaintiff never demonstrated m, cross- any willingness to abide by the rules claim, 3rd Notice of the to pay the docket fee but stubbornly Within 10 days party order insisted that the case filed was one (if amendment complaint, admitting the for specific performance and was not a matter complaint same (Rule 11, damages. of right) in Sec. 3) interventio n)FILING VERSUS SERVICE OF PLEADINGS Answer to From service CounterclaiFiling - The act of presenting the pleading or Within 10 days (Rule 11, Sec. m or Cross-other paper to the clerk of court. [Rule 13, Sec. 4) Claim2] Same rule as Answer to answer to theService - The act of providing a party or his third (4th, Within 15 days complaintcounsel with a copy of the pleading or paper etc)- party (Rule 11, Sec.concerned. [Rule 13, Sec. 2] complaint 5) From servicePapers required to be filed and served: (Rule 13, of theSec. 4) pleading 1. Pleading subsequent to the complaint; Reply Within 10 days responded to 2. Appearance; (Rule 11, Sec. 3. Written Motion; 6) 4. Notice; Answer to Within 10 days From notice of 5. Order; supplemen the order 6. Judgment; tal admitting the 7. Demand; complaint same, unless a 8. Offer of Judgment; different 9. Resolution; period is fixed by the court 2. Registered Mail - The date of mailing is the date of filingNOTE: Upon motion and on such terms as may a. Date of filing is determinable from 2be just, the court may extend the time to plead sources:provided in these Rules. The court may also, (1) From the post office stamp on theupon like terms, allow an answer or other envelopepleading to be filed after the time fixed by these (2) From the registry receiptRules. [Rule 11, Sec. 11] b. It is done by depositing in the post office:MANNER OF FILING (1) In a sealed envelope (2) Plainly addressed to the party orAs per Rule 13, Sec. 3: his counsel 1. Personally (a) At his office if known a. By By personally presenting the (b) Otherwise, at his residence if original to the clerk of court. known b. The pleading is deemed filed upon the (3) Postage fully pre-paid receipt of the same by the clerk of (4) With instructions to the court who shall endorse on it the date postmaster to return the mail to and hour of filing. the sender after 10 days if c. If a party avails of a private carrier, undelivered the date of the court’s actual receipt of the pleading (not the date of Substituted Service (Rule 13, Sec. 8) delivery to the private carrier) is 1. Done by delivery of the copy to the clerk deemed to be the date of the filing of of court with proof of failure of both that pleading. [Benguet Electric personal and service by mail Cooperative v. NLRC (1992)] 2. Proper only when: a. Service cannot be made personally or 2. By Registered Mail by mail a. Filing by mail should be through the b. Office and place of residence of the registry service (i.e. by depositing the party of his counsel being unknown pleading in the post office). 3. Service is complete at the time of such b. The pleading is deemed filed on the delivery date it was deposited with the post office. SERVICE OF JUDGMENTS, FINAL ORDERS, ORFiling a pleading by facsimile is not sanctioned. RESOLUTIONS (Rule 13, Sec. 9)But fax was allowed in an extradition case(Justice Cuevas v. Juan Antonio Munoz) Service is done either: 1. Personally 2. By registered mailMODES OF SERVICE 3. By publication ONLY IF: a. Party is summoned by publicationPersonal Service (Rule 13, Sec. 6) AND 1. Delivering personally a copy to the party, b. He failed to appear in the action who is not represented by a counsel, or to his counsel; or NOTE: There is NO substituted service of 2. Leaving a copy in counsel’s office with his judgments and final orders clerk or with a person having charge thereof; or 3. Leaving the copy between 8am and 6pm PRIORITIES IN MODES OF SERVICE AND FILING at the party’s or counsel’s residence, if known, with a person of sufficient age General rule: Personal filing and service is and discretion then residing thereon – if preferred. (Rule 13, Sec. 11) not person is found in his office, or if his office is unknown, or if he has no office Resort to other modes of filing and service must be accompanied by an explanation why theService by Mail (Rule 13, Sec. 7) service/filing was not done personally. If there is 1. Ordinary Mail - it does not constitute filing no written explanation, the paper is considered until the papers are actually delivered not filed. into the custody of clerk or judge a. Service may be done by ordinary mail Exception: Papers emanating from the court. if no registry service is available in the locality of either sender or addressee WHEN SERVICE IS DEEMED COMPLETE clients, because he was so busy. [Bayog v. Completeness of Natino] Proof of service service (Rule 13 (Rule 13 Sec. 13) Sec. 10) Personal service PROOF OF FILING Written admission of the party served, OR 1. Filing is proved by its existence in the Official return of the record of the case (Rule 13, Sec. 12) server ORUpon actual delivery Affidavit of the party 2. If it is not in the record: serving, with a full statement of the When pleading is Proof of filing date/place/manner of deemed filed service. Personally Service by ordinary mail Upon receipt of the Written/stamped 10 days after Affidavit of the person pleading by the clerk acknowledgment by mailing, unless mailing of facts of court the clerk of court otherwise provided showing compliance By registered mail by the court with Sec. 7 of Rule 13. Registry receipt, and Service by registered mail affidavit of the person Affidavit of the person who did the mailingWhichever is earlier: with: mailing of facts showing compliance (a) Full statementActual receipt by the of the with Sec. 7 of Rule 13addressee date/place of OR depositing the AND5 days after the mail in theaddressee received post office in a Registry receipt issued On the date the1st postmaster's sealed by the post office pleading wasnotice (Constructive) envelope deposited with the addressed to Substituted Service post office the courtAt the time of delivery of the copy to the clerk (b) Postage fully of court together with proof of failure of both paid personal service and service by mail (c) Instructions to thePurpose of the rule on completeness of service postmaster tofor service by registered mail: return the mail to the senderTo make sure that the party being served with after 10 daysthe pleading, order or judgment is duly informed if undeliveredof the same so that such party can take steps toprotect the interests, i.e., enable to file anappeal or apply for other appropriate reliefsbefore the decision becomes final. [MINTERBRO PROOF OF SERVICE (Rule 13, Sec. 13)v,CA (2012)] MODE PROOF OF SERVICEService to the lawyer binds the party. But service A written admission ofto the party does not bind the lawyer, unless the party served, ORordered by the court in the following The official return ofcircumstances: the server; OR 1. When it is doubtful who the attorney for Personal Service Affidavit of the party such party is; or serving containing a 2. When the lawyer cannot be located; or full statement of the 3. When the party is directed to do date, place, and something personally, as when he is manner of service ordered to show cause. [Retoni, Jr. v. CA] Affidavit of the person mailing stating theNotice to the lawyer who appears to have been Service by ordinary facts showingunconscionably irresponsible cannot be mail compliance with Ruleconsidered as notice to his client, as it would 13, Sec. 7then be easy for the lawyer to prejudice the Service by registered Affidavit of personinterests of his client by just alleging that he just mail mailing containingforgot every process of the court affecting his facts showing compliance with Rule 13, Sec. 7, AND 2. Instances: Registry receipt issued a. Substantial amendment – before by mailing office; OR responsive pleading is filed The registry return (1) Amendment of complaint before card which shall be an answer is filed. filed immediately upon (2) Amendment of answer before a its receipt by the reply is filed or before the period sender, or in lieu for filing a reply expires thereof of the (3) Amendment of reply any time unclaimed letter within 10 days after it is served together with the b. Formal amendment certified or sworn copy of the notice given by the postmaster to the AMENDMENTS BY LEAVE OF COURT (Rule 10, addressee. Sec. 3)
Effect of Invalid Summons Return When Service has been Completed (Rule 14, Sec. 4) 1. The server shall serve a copy of the Defendant return to the plaintiff’s counsel Rule 13, Sec. 6 Rule 14, Sec. 6 a. Within 5 days therefrom Personal service Service is only made b. Personally or by registered mail includes: on defendant himself 2. The server shall return the summons 1. Service on the a. To the clerk who issue it party or his b. Accompanied by proof of service counsel; or 2. By leaving aIt is required to be given to the plaintiff’s counsel copy with thein order to enable him: clerk or person 1. To move for a default order should the having charge defendant fail to answer on time, or of his office; or 2. In case of non-service, so that alias 3. Leaving it with summons may be sought a person of sufficient age In either of the 2 cases, server must and discretion serve a copy of the return on plaintiff’s at the party’s or counsel within 5 days from completion or counsel’s failure of service residence
ALIAS SUMMONS (Rule 14, Sec. 5) SUBSTITUTED SERVICE OF SUMMONS (Rule 14, Sec. 7)Upon plaintiff’s demand, the clerk may issue analias summons if either: It is only when the defendant cannot be served 1. Summons is returned without being personally within a reasonable time and for served on any/all of the defendants. justifiable reasons that a substituted service may 2. Summons was lost. be made.
The server shall also serve a copy of the return How Done:on the plaintiff's counsel within 5 days 1. By leaving copies of the summons at thetherefrom, stating the reasons for the failure of defendant’s residence with some personservice of suitable age and discretion residing therein; or 2. By leaving the copies at defendant’sMODES OF SERVICE OF SUMMONS office or regular place of business with some competent person in charge thereofModes: 1. Personal Service (Rule 14, Sec. 6) Necessary Requisite: For substituted service of 2. Substituted Service (Rule 14, Sec. 7) summons to be valid, it is necessary to establish 3. Service by Publication (Rule 14, Sec. 14, the following: 15, 16) 1. The impossibility of the personal service of summons within a reasonable timeNOTE: Summons cannot be served by mail 2. The efforts exerted to locate the person - Where service is made by publication, a to be served; and copy of the summons and order of the 3. Service upon: court shall be sent by registered mail to a. A person of sufficient age and last known address of defendant (Sec. 15) discretion residing in the same place Resort to registered mail is only as defendant or complementary to the service of b. Some competent person in charge of summons by publication his office or regular place of business But it does not mean that service by (Spouses Ventura v. CA, 1987) registered mail alone would suffice Meaning of RESIDENCE 1. For a substituted service to be valid,PERSONAL SERVICE OF SUMMONS (Rule 14, Sec. summons served at the defendant’s6) residence must be served at his residence AT THE TIME OF SERVICE; not his formerHow Done: place of residence 1. By handing a copy of summons to him; or 2. “dwelling house” or “residence” refers to 2. If he refuses to receive it, by tendering it the dwelling house at the time of service to him 3. They refer to the place where the person named in the summons is living at the Personal Service of Personal Service of time of when the service is made, even Pleadings Summons on though he may be temporarily out of the The Rule on Non-Resident Defendants (Extra- country at that time (Venturanza v. CA) territorial Service); Rule 14, Sec. 15
PROOF OF SERVICESERVICE UPON PRISONERS AND MINORS The proof of service of summons (Rule 14, Sec.Service of Summons on Different Entities: 18): 1. Shall be made in writing DEFENDANT SERVICE OF SUMMONS 2. It shall: Entity a. Set forth the manner, place, date of Upon any or all the defendants without service being sued under common juridical b. Specify any papers which may have name; or person in charge of personality been served with the process and the the office (Sec. 8) name of the person who received the In case of minors: by serving same upon: c. Shall be sworn to when made by a 1. The minor, regardless of person, other than the sheriff or his age, AND deputy 2. Upon his legal guardian, or also upon either of his If service has been made by publication, service parents may be proved by: (Rule 14, Sec. 19) In case of incompetents: by 1. The affidavit of the printer, his foreman, Minors and serving on: or principal clerk; or of the editor, incompetent 1. Him personally AND business or advertising manager s (Sec. 10) 2. Upon his legal guardian, Copy of the publication shall be but not upon his parents, attached unless they are his legal guardians 2. AND an affidavit showing: In any event: if the minor or a. The deposit of a copy of the incompetent has no legal summons; and guardian, the plaintiff must b. Order of publication in the post office, obtain the appointment of a postage prepaid, directed to guardian ad litem for him defendant by registered mail to his Serve to either: (Exclusive last known address enumeration) Domestic 1. The president, Effect of Defect of Proof of Service: private 2. Managing partner, 1. Where sheriff’s return is defective, juridical 3. General manager, presumption of regularity in the entity (Sec. 4. Corporate secretary, performance of official functions will not 11) 5. Treasurer, or lie 6. In- house counsel 2. Defective return is insufficient and Service may be done on: incompetent to prove that summons was 1. The resident agent; indeed served Foreign 2. If no resident agent; 3. Party alleging valid summons will now private a. The government prove that summons was indeed served juridical official designated by 4. If there is no valid summons, court did entity (Sec. law; or not acquire jurisdiction which renders null 12) b. Any officer or agent and void all subsequent proceedings and of the corporation issuances within the Philippines
Requisites of motions (not made in open court or Proof of Service (Rule 15, Sec. 6)in the course of hearing/trial) General Rule: A written motion set for hearing 1. It must be in writing; [Rule 15, Sec. 2] will not be acted upon by the court if there is no proof of service thereof. Exception: Oral motions What may be proof: 2. Hearing on the motion set by the 1. If by registered mail: Affidavit or registry applicant receipt or postmark on envelope or return card, with an explanation. Motion Day (Rule 15, Sec. 7) - Except for 2. If by personal service: Affidavit or urgent motions, motions are scheduled acknowledgment of receipt by the other for hearing: party. a. On Friday afternoons; b. Afternoon of the next working day, if Exceptions: Friday is a non-working day. 1. If the motion is one which the court can MOTIONS FOR BILL OF PARTICULARS hear ex parte. 2. If the court is satisfied that the rights of DEFINTION the adverse parties are not affected by the motion. It is a detailed explanation respecting any matter 3. If the party is in default because such a which is not averred with sufficient party is not entitled to notice. definiteness/particularity in the complaint as to enable a party to properly prepare his responsive pleading or to prepare for trial. [Rule 12, Sec. 1]OMNIBUS MOTION RULE PURPOSE AND WHEN APPLIED FORDefinition: A motion attacking a pleading/ order/judgment/ proceeding must include all objections It is filed by the plaintiff pursuant to a courtthen available. All objections not included in the order issued upon granting a motion for Bill ofmotion are deemed waived. Particulars filed by the defendant before the latter files an answer.Purpose: To require the movant to raise all - In said motion, the defendant prays for aavailable exceptions for relief during a single more definite statement of matters whichopportunity so that multiple and piece-meal are not averred with sufficientobjections may be avoided definiteness in the complaint. - An action cannot be dismissed on theException: When the court’s jurisdiction is in ground that the complaint isissue: vague/indefinite. The remedy of the 1. Lack of jurisdiction over subject-matter; defendant is to move for a Bill of 2. Litis pendentia; Particulars or avail of the proper mode of 3. Res judicata; discovery. [Galeon v. Galeon (1973)] 4. Prescription. Purpose: to define/ clarify/ particularize/ limit/ circumscribe the issues in the case to expediteLITIGATED AND EX PARTE MOTIONS the trial and assist the court. - The only question to be resolved in aKinds of Motion motion for a Bill of Particulars is WON the 1. Motion Ex Parte - Made without allegations in the complaint are averred notification to the other party because with sufficient definiteness/ particularity the question generally presented is not to enable the movant to properly prepare debatable. his responsive pleading and to prepare 2. Litigated Motion - Made with notice to the for trial. [Tantuico, Jr. v. Republic (1991)] adverse party so that an opposition - A Bill of Particulars becomes part of the thereto may be made. pleading for which it was intended. [Rule 3. Motion Of Course - Motion for a kind of 12, Sec. 6] relief/remedy to which the movant is entitled to as a matter of right, When Applied For: [Rule 12, Sec. 1] Allegations contained in such motion do 1. Before responding to a pleading not have to be investigated/verified. 2. If the pleading is a reply, within 10 days 4. Special Motion - Discretion of the court is from service thereof involved. An investigation of the facts alleged is required. What a Motion for a Bill of Particulars should point out: (Rule 12, Sec. 1) 1. The defects complained of;PRO FORMA MOTIONS 2. The paragraph wherein they are contained;Definition - A motion failing to indicate time and 3. The details desired.date of the hearing What cannot be done in a Bill of Particulars: - To supply material allegations necessary to the validity of a pleading - To change a cause of action or defense stated in the pleading - To state a cause of action or defense other than that one stated - To set forth the pleader’s theory of his cause of action or a rule of evidence on which he intends to reply - To furnish evidentiary informationACTIONS OF THE COURT Bill of Particulars Intervention
Upon the filing of the motion, the clerk must Purpose is to enable aimmediately bring it to the attention of the court. party bound to Purpose is to enable a respond to a pleadingThe court may: (Rule 12, Sec. 2) person not yet a party to get more details 1. Deny to an action, yet about matters which 2. Grant the motion outright having a certain right are alleged generally 3. Allow the parties the opportunity to be or interest in such or which are indefinite heard action, the and vague, opportunity to appear and be joined so as to properlyCOMPLIANCE WITH THE ORDER AND EFFECT OF guide such party inNONCOMPLIANCE so he could assert or answering the protect such right or pleading and to avoidCompliance with Order (Rule 12, Sec. 3) – If interest surprise in the trial ofmotion is granted wholly/partially: the case 1. Within 10 days from notice of order, Bill of Available to any Particulars or a more definite statement person not yet a party should be submitted (unless court fixes a to the action at any different period). Available to the time after the 2. Bill of Particulars or definite statement defendant before he commencement of an filed either as a separate pleading or as files his responsive action, even during an amended pleading, a copy of which pleading the proceeding, but must be served on the adverse party. not after the trial has been concludedEffect of Non-Compliance (Rule 12, Sec. 4) – 1. In case of non-compliance or insufficient Effect of Motion: compliance with the order for Bill of 1. If the motion is granted, in whole or in Particulars, the court: part, a. May order the striking out of the a. The movant can wait until the bill of pleading (or portion thereof) to which particulars is served on him by the order is directed; OR opposing party b. Make such order as it may deem just. b. Then he will have the balance of the reglementary period within which to 2. If a party fails to obey: file his responsive pleading a. If the plaintiff fails to obey, his 2. If the motion is denied complaint may be dismissed with a. He will still have such balance of the prejudice unless otherwise ordered by reglementary period to file his the court. [Rule 12, Sec. 4; Rule 17, responsive pleading, counted from Sec. 3] service of the order denying his b. If defendant fails to obey, his answer motion will be stricken off and his counterclaim dismissed, and he will IN ANY CASE: The party will have at least be declared in default upon motion of 5 days to file his responsive pleading the plaintiff. [Rule 9, Sec. 3; Rule 12, Sec. 4; Rule 17, Sec. 4]
It is not a responsive pleading. It is not a Lack of Jurisdiction (LOJ) over the Defendant’spleading at all. It is subject to the omnibus Personmotion rule since it is a motion that attacks apleading. Hence, it must raise all objections The objection of LOJ over the person on accountavailable at the time of the filing thereof. of lack of service or defective service of summons, must be raised:Types of Dismissal of Action: 1. At the very first opportunity; 1. MTD before answer under Rule 16; 2. Before any voluntary appearance is 2. MTD under Rule 17: made. a. Upon notice by plaintiff; b. Upon motion by plaintiff; In La Naval Drug Corp. v. CA, et al. the Court c. Due to fault of plaintiff. held that while lack of jurisdiction over the 3. Demurrer to evidence after plaintiff has person of defendant may be duly and completed the presentation of his seasonably raised, his voluntary appearance in evidence under Rule 33; court without qualification is a waiver of such 4. Dismissal of an appeal. defense.
Period to File: Within the time for, but before Appearance of counsel is equivalent tofiling of, the answer to the complaint or pleading summons, unless such is made to protest theasserting a claim jurisdiction of the court over the person of the defendant. If grounds other than invalid service Exceptions: of summons are raised, it cannot be considered a. For special reasons which may be as a special appearance. [De los Santos v. allowed even after trial has begun, a Montesa (1993)] motion to dismiss may be filed b. The court has allowed the filing of a NOTE: Sec. 20, Rule 14 makes a categorical motion to dismiss where the evidence statement that the inclusion in a motion to that would constitute a ground for dismiss of other grounds aside from lack of dismissal was discovered during trial jurisdiction over the person of the defendant shall not be deemed voluntary appearance onGeneral Rule: A court may NOT motu propio his part.dismiss a case, unless a motion to that effect isfiled by a party.
Where a motion to dismiss for improper venue is It does not require that the later case beerroneously denied, the remedy is prohibition dismissed in favor of the earlier case. To(Enriquez v. Macadaeg) determine which case should be abated, apply: 1. The More Appropriate Action Test;Where the plaintiffs filed the action in a court of 2. The Interest of Justice Test, taking intoimproper venue and thereafter submitted to its account:jurisdiction, the issue of venue was thereby a. Nature of the controversy;waived and they are in estoppel to repudiate or b. Comparative accessibility of the courtquestion the proceedings in said court (Vda. De to the parties;Suan, et al. v. Cusi, et al.) c. Other similar factors.
Objection to venue is also impliedly waived In both tests, the parties’ good faith shall bewhere the party enters into trial, cross-examines taken into consideration.the witnesses of the adverse party and adducesevidence (Paper Industries Corp of the The 1st case shall be abated if it is merely anPhilippines v. Samson et al.) anticipatory action or defense against an expected suit. The 2nd case will not be abated if it is not brought to harass. [Vitrionics ComputersPlaintiff’s Lack of Legal Capacity to Sue: v. RTC (1993)]
Rationale: The sum and substance of the whole Estoppel and prescription cannot be invokeddoctrine is that a matter once judicially decided against the State (Republic v. CA)is finally decided because of: 1. Public policy and necessity makes it the A motion to dismiss on the ground of prescription interest of the State that there should be will be given due course only if the complaint an end to litigation; shows on its face that the action has already 2. The hardship on the individual that he prescribed (Sison v. McQuaid) should be vexed twice for the same cause. [Nabus v. CA (1991)] If it is not apparent on its face, take note that Sec. 3 prohibits deferment of the resolution ofTwo concepts of res judicata [Abalos v. CA 1993) the motion. Thus: 1. Bar by prior judgment – Judgment on the 1. Evidence may be received in support of merits in the 1st case constitutes an the motion under Sec. 2, Rule 16; or absolute bar to the subsequent action not 2. The motion to dismiss should be denied only as to every matter which was offered without prejudice to the complaint’s and received to sustain or defeat the dismissal if evidence disclose that the claim/demand, but also to any other action had already prescribed (Sec. 1, admissible matter which might have been Rule 9) offered for that purpose and to all matters that could have been adjudged in that case. (Asked in the 2002 Bar Exam) Complaint States No Cause of Action
2. Conclusiveness of judgment – Where the Failure to state a cause of action (not lack of 2nd action between the parties is upon a cause of action) is the ground for a MTD. The different claim/demand, the judgment in former means there is insufficiency in the the 1st case operates as an estoppel only allegations in the pleading. The latter means with regard to those issues directly that there is insufficiency in the factual basis of controverted, upon the determination of the action. which the judgment was rendered. The failure to state a cause of action must be evident on the face of the complaint itself.Statute of Limitations Test: Assuming the allegations and statementsPrescription applies only when the complaint on to be true, does the plaintiff have a valid causeits face shows that indeed the action has already of action?prescribed. A MTD based upon the ground of failure to stateIf the fact of prescription is not indicated on the a cause of action imports a hypotheticalface of the complaint and the same may be admission by the defendant of the facts allegedbrought out later, the court must defer decision in the complaint.on the motion until such time as proof may bepresented on such fact of prescription. If the court finds the allegations of the complaint to be sufficient but doubts their veracity, it must deny the MTD and require the defendant to Prescription Laches answer and then proceed to try the case on its merits. Concerned with the Concerned with the fact of delay effect of delay A complaint containing a premature cause of A matter of time A matter of equity action may be dismissed for failure to state a Statutory Not statutory cause of action. Applies in law Applies in equity Based on fixed time Not based on fixed If the suit is not brought against the real party- time in-interest, a motion to dismiss may be filed onthe ground that the complaint states no cause of 6. A representation as to the credit of a thirdaction. [Tanpinco v. IAC (1992)] person.
The court’s resolution on the MTD must clearly General rule: The action/claim may be re-filed.and distinctly state the reasons therefor. Exception: The action cannot be re-filed (although subject to appeal) if it was dismissedREMEDIES OF PLAINTIFF WHEN THE COMPLAINT on any of the following grounds:IS DISMISSED 1. Res judicata; 2. Prescription;If the motion is granted, the complaint is 3. Extinguishment of the claim/demand;dismissed. Since the dismissal is final and not 4. Unenforceability under the Statute ofinterlocutory in character, the plaintiff has Frauds. [Rule 16, Sec. 1 (f),(h),(i)]several options:
1. Depending upon the ground for the WHEN GROUNDS PLEADED AS AFFIRMATIVE dismissal of the action, the plaintiff may DEFENSES REFILE the complaint, a. These are orders of dismissal which is If no motion to dismiss had been filed, any of the not tantamount to an adjudication on grounds for dismissal may be pleaded as the merits affirmative defenses and a preliminary hearing b. e.g when ground for dismissal is may be had at court’s discretion. (Rule 16, Sec. anchored on improper venue. 6)
2. He may APPEAL from the order of NOTE: The dismissal of the complaint under this dismissal where the ground relied upon is section shall be without prejudice to the one which bars refilling of complaint prosecution in the same or separate action of a a. The grounds which bar re-filing are: counterclaim pleaded in the answer. (1) Res judicata (2) Prescription If the defendant would not want to file a (3) Extinguishment of the obligation counterclaim, he should not file a motion to (4) Violation of Statutes of Fraud dismiss Instead, he should allege the grounds 3. The plaintiff may also avail of a petition of a motion to dismiss as affirmative for certiorari, alleging grave abuse of defenses in his answer with a discretion. [Riano] counterclaim A preliminary hearing may be had thereon, and in the event theREMEDIES OF THE DEFENDANT WHEN MOTION IS complaint is dismissed, defendant canDENIED prosecute his counterclaim (Herrera)
DISMISSAL OF ACTIONS DISMISSAL UPON MOTION BY PLAINTIFF;DISMISSAL UPON NOTICE BY PLAINTIFF; EFFECT ON EXISTING COUNTERCLAIM (RuleTWO-DISMISSAL RULE (Rule 17, Sec. 1) 17, Sec. 2)
Dismissal by plaintiff as a matter of right Under this section, dismissal of the complaint is subject to the discretion of the court and uponDismissal is effected not by motion but by mere such terms and conditions as may be just.notice of dismissal which is a matter of rightbefore the service of: Generally, Dismissal is Without Prejudice 1. The answer; or General Rule: Dismissal is without prejudice 2. A motion for summary judgment Exceptions: 1. When otherwise stated in the motion toThe dismissal as a matter of right ceases when dismiss; oran answer or a motion for summary judgment is 2. When stated to be with prejudice in theserved on the plaintiff and not when the answer order of the courtor the motion is filed with the court. Effect on Counterclaim:Dismissal NOT Automatic - It requires an orderby the court confirming the dismissal. Until If counterclaim has been pleaded by defendantconfirmed, the withdrawal does not take effect prior to service upon him of plaintiff’s motion for dismissal, dismissal shall be limited to theGenerally, Dismissal is Without Prejudice complaintGeneral Rule: Dismissal is without prejudice - Remember that if the civil case isExceptions: dismissed, so also is the counterclaim 1. Where the notice of dismissal so provides; filed therein or It was held that if the court does not 2. Where the plaintiff has previously have jurisdiction to entertain the main dismissed the same case in a court of action of the case and dismiss the competent jurisdiction (Two Dismissal case, then the compulsory Rule) counterclaim, being ancillary to the 3. Even where the notice of dismissal does principal controversy must likewise be not provide that it is with prejudice but it dismissed (Metals Engineering is premised on the fact of payment by the Resources v. CA) defendant of the claim involved (Serrano - However, under this section, if a v. Cabrera) counterclaim has been pleaded by a defendant PRIOR to the service upon himTwo Dismissal Rule - when the same complaint of the plaintiff’s motion for dismissal, thehad twice been dismissed by the plaintiff without dismissal shall be limited to theorder of the court by simply filing a notice of complaint.dismissal, the 2nd dismissal operates as anadjudication on the merits. Such dismissal shall be without prejudice to the right of the defendant to either: 1. Prosecute his counterclaim in a separate c. Since plaintiff’s presence is now action; required only during the presentation a. In this case, the court should render of his evidence in chief, his absence the corresponding order granting and during the presentation of defendant reserving his right to prosecute his or other parties’ evidence, or even at claim in a separate complaint rebuttal or subsequent stages, is not a 2. OR to have the same resolved in the ground for dismissal. same action a. In this case, defendant must manifest 2. To prosecute his action for an such preference to the trial court unreasonable length of time (nolle within 15 days from notice to him of prosequi); plaintiff’s motion to dismiss a. The test for dismissal of a case due to failure to prosecute is WON, under the NOTE: These alternative remedies of the circumstances, the plaintiff is defendant are available to him regardless chargeable with want of due diligence of whether his counterclaim is in failing to proceed with reasonable compulsory or permissive promptitude. [Calalang v. CA (1993)] b. The dismissal of an action pursuant to this rule rests upon the soundDISMISSAL DUE TO FAULT OF PLAINTIFF discretion of the court ( Smith Bell and(Rule 17, Sec. 3) Co. v. American President Lines Ltd.) c. The action should never be dismissedDistinction between Sec. 2 and Sec. 3 of Rule 17 on a non-suit for want of prosecution when the delay was caused by the SECTION 2 SECTION 3 parties looking towards a settlement. Dismissal is not (Goldloop Properties Inc. v. CA) Dismissal is at the procured by plaintiff instance of the though justified by 3. To comply with the Rules or any court plaintiff causes imputable to order. him a. The order must be valid Dismissal is a matter b. Failure to comply with order: of procedure, without Dismissal is a matter (1) Dismissal for failure to comply prejudice unless of evidence, an with order to amend complaint to otherwise stated in adjudication on the make claims asserted more the court order or on merits definite is ground for dismissal motion to dismiss (Santos v. General Wood Craft) Dismissal is without (2) Failure to comply with an order to prejudice to the right include indispensable parties is of defendant to ground for dismissal (Aranico- Dismissal is without Rubino v. Aquino) prosecute his prejudice to the right (3) The failure to comply with order of counterclaim in a of defendant to new judge to recall witness so he separation action prosecute his may observe demeanor is unless within 15 days counterclaim on the sufficient ground for dismissal from notice of motion same or separate (Castillo v. Torres) he manifests his action c. Failure to comply with rules intention to have his counterclaim resolved (1) The failure of the parties to submit in the same action a compromise agreement within period granted to them by court isDismissal under this Section not a ground for dismissal (Goldloop Properties Inc. v. CA)The case may be dismissed motu proprio or (2) Dismissal is improper where a 3rdupon the defendant’s motion if, without party complaint has beenjustifiable cause, plaintiff fails either: admitted and the 3rd party 1. To appear on the date of the presentation defendant had not yet been of his evidence-in-chief on the complaint; summoned (Sotto v. Valenzuela) a. The plaintiff’s failure to appear at the (3) A case may be dismissed for trial after he has presented his failure to answer written evidence and rested his case does not interrogatories under Rule 25 even warrant the dismissal of the case on without an order from the court to the ground of failure to prosecute. answer. (Arellano v. CFI- Sorsogon) b. It is merely a waiver of his right to cross-examine and to object to the Effect of Dismissal: admissibility of evidence. [Jalover v. General Rule: Dismissal of actions under Sec. 3 Ytoriaga (1977)] which do not expressly state whether they arewith or without prejudice are held to be withprejudice on the merits Provisions of Rule 17 shall apply to the dismissalExceptions: of any counterclaim, cross-claim, or third-party 1. The court declares otherwise, without complaint prejudice to the right of the defendant to prosecute his counter-claim in the same Voluntary dismissal by claimant by notice as in or separate action Sec. 1, shall be made: 2. If court has not yet acquired jurisdiction 1. Before a responsive pleading or motion over the person of the defendant for summary judgment is served; or 2. If there is none, before introduction ofEffect on Counterclaim: evidence at trial or hearing
Remedy of Party who has been non-suited: PROCEEDINGS AFTER TERMINATION OF PRE- 1. For a non-suited plaintiff: TRIAL a. Motion to set aside the order of non- suit Record of Pre-Trial: The pre-trial proceedings b. Affidavit of merit is not necessary in a shall be recorded. Upon termination of such simple motion for reconsideration of proceedings, the court shall issue the pre-trial the order of non-suit EXCEPT as to order. show the cause of the failure to appear at the pre-trial (Jonathan Contents of Pre-Trial Order: Landoil International Inc. v. 1. Matters taken up in the conference; Mangudadatu) 2. Action taken thereon; 3. Amendments allowed on the pleadings; 2. For a non-suited defendant: 4. Agreements/admissions made by the a. File a motion for reconsideration parties as to any matters considered; without need for affidavits of merits 5. Should the action proceed to trial, the regarding the fraud, accident, explicit definition and limit of the issues mistake, or excusable negligence to be tried. (Lucero v. Dacayo) Effect of Pre-Trial Order: The contents of the order shall control the subsequent course of the action; UNLESS: 1. Modified before trial to prevent manifest injustice (Rule 18, Sec. 7)PRE-TRIAL BRIEF; EFFECT OF FAILURE TO 2. Issues impliedly included therein or mayFILE be inferable therefrom by necessary implication (Velasco v. Apostol)Rule 18, Sec. 6 makes it the MANDATORY duty of 3. Amendment to conform to evidence (Rulethe parties to seasonably file their pre-trial briefs 10, Sec. 5)under the conditions and with the sanctionsprovided therein. On Compromise:When to File Pre-Trial Brief: Parties shall file and - Upon manifestation of the parties of theirserve their respective pre-trial briefs, ensuring willingness to discuss a compromise, thereceipt by adverse party at least 3 days before TC should order the suspension of thethe date of the pre-trial. proceedings to allow them reasonable time to discuss and conclude an amicableContents of a Pre-Trial Brief settlement. 1. Statement of their willingness to enter - If despite all efforts exerted by the TC and into amicable settlement or alternative the parties the settlement conference still modes of dispute resolution, indicating fails, then the action should have the desired terms thereof; continued as if no suspension had taken 2. Summary of admitted facts and proposed place. [Goldloop Properties v. CA (1992)] stipulation of facts; - NOTE: AM 03-1-09-SC - No termination of 3. Issues to be tried/resolved; pre-trial for failure to settle 4. Documents/exhibits to be presented, stating the purpose thereof; 5. Manifestation of their having availed or DISTINCTION BETWEEN PRE-TRIAL IN CIVIL their intention to avail themselves of CASE AND PRE-TRIAL IN CRIMINAL CASE discovery procedures or referral to commissioners; 6. Number and names of the witnesses, and Civil Case Criminal Case the substance of their respective testimonies. [AM No. 03-1-09-SC] Set when the Ordered by the plaintiff moves ex court and no motionFailure to File Pre-trial Brief: Failure to file the parte to set the to set the case forpre-trial brief shall have the same effect as case for pre-trial pre-trial is requiredfailure to appear at the pre-trial. [Rule 18, Sec. 1] from either the prosecution or theRemedy of defendant is to file a motion for defense [Rule 118,reconsideration, showing that his failure to file a Sec. 1] Made after the Ordered by thepleading has been court after The Alternative Dispute Resolution System served and filed arraignment and Means any process or procedure used to resolve [Rule 18, Sec. 1] within 30 days from a dispute or controversy, other than by the sate the court adjudication of a presiding judge of a court or an acquired jurisdiction officer of a government agency, as defined in over the person of this Act, in which a neutral third party the accused [Rule participates to assist in the resolution of issue 118, Sec. 1] [RA 9285, Sec. 3] Considered the Does not include possibility of an the considering of Policy Behind the ADR: To actively promote party amicable the possibility of autonomy in the resolution of disputes or the settlement as an amicable freedom of the party to make their ownimportant objective settlement of one’s arrangements to resolve their disputes [RA 9285, [Rule 118, Sec. criminal liability as Sec. 2] 2(a)] one of its purposes [Rule 118, Sec. 1] In Relation to Pre-Trial: The arrangements (Stricter procedure) 1. At the start of the pre-trial conference, and admissions in All agreements or the judge shall immediately refer thethe pre-trial are not admissions made or parties and/or their counsel if authorized required to be entered during the by their clients to the PMC mediation unit signed by both pre-trial conference for purposes of mediation if available.[AM parties and their shall be reduced in No. 03-1-09-SC]counsels. Under the writing and signed Rules, they are by both the accused 2. The pre-trial briefs of parties must include instead to be and counsel; the parties’ statement of their willingness contained in the otherwise, they to enter into an amicable settlement record of pre-trial cannot be used indicating the desired terms thereof or to and pre-trial order against the submit the case to any of the alternative [Rule 18, Sec. 7] accused. [Rule 118, modes of dispute resolution [AM No. 03-1- Sec. 2] 09-SC] [AM No. 03-1-09] - requires the Exception to the Application of RA 9285:proceedings during 1. labor disputes covered by the Labor the preliminary Code; conference to be 2. the civil status of persons; recorded in the 3. validity of a marriage; “Minutes of 4. any ground for legal separation; Preliminary 5. the jurisdiction of courts; Conference” to be 6. future legitime; signed by both 7. criminal liability; and parties and/or 8. those which by law cannot be counsel. compromised. (Note: either party or his counsel is Modes of Alternative Dispute Resolutions: allowed to sign) The sanctions for Sanctions are 1. Arbitration (RA 9285, Sec. 1)non-appearance are imposed upon the a. A voluntary dispute resolution process imposed upon the counsel for the in which one or more arbitrators, plaintiff and the accused or the appointed in accordance with thedefendant [Rule 18, prosecutor [Rule agreement of the parties, or rules Sec. 4] 118, Sec. 3] promulgated pursuant to this Act, A pre-trial brief is A pre-trial brief is resolve a dispute by rendering anspecifically required not specifically award\ to be submitted required. b. Different Kinds: [Rule 18, Sec. 6] (1) Domestic Arbitration – an arbritration that is not international; governed by RA 876ALTERNATIVE DISPUTE RESOLUTION (ADR) (Arbitration Law) [RA 9285, Sec.Special Rules of Court on ADR (AM No. 07- 32]11-08-SC) (2) International Arbitration - An arbitration is international if:The parties may be submitted to ADR during pre- (a) the parties to an arbitrationtrial. If ADR fails, judge will schedule the agreement have, at the time ofcontinuance of the pre-trial conference the conclusion of that agreement, their places of 9. Recognition and Enforcement or Setting business in different States; or Aside of an Award in International (b) one of the following places is Commercial Arbitration; situated outside the State in 10. Recognition and Enforcement of a Foreign which the parties have their Arbitral Award; places of business [Article 3, 11. Confidentiality/Protective Orders; and Model Law on International 12. Deposit and Enforcement of Mediated Commercial Arbritration] Settlement Agreements.
TRIAL
If evidence is insufficient to prove plaintiff’s cause of action or defendant’s counterclaim, court rules in favor
SUBPOENA Kinds: 1. Subpoena duces tecum (SDT)DEFINITION 2. Subpoena ad testificandum (SAT)
4. Order and Examination: If the court is Purpose - This mode of discovery is availed of by satisfied that the perpetuation of the the party to the action for the purpose of testimony may prevent a failure or delay eliciting material and relevant facts from any of of justice, it shall make an order the adverse party. [Rule 25, Sec. 1] designating or describing the persons whose deposition may be taken and Service of Interrogatories to Parties – Any party specifying the subject matter of the desiring to elicit material and relevant facts from examination and whether the depositions any adverse party shall file and serve upon the shall be taken upon oral examination or adverse party written interrogatories to be written interrogatories. answered by the party served.
Grounds: 1. They require the statements of conclusions of law or answers to hypothetical questions or opinion, or REQUEST FOR ADMISSION (Rule 26) mere hearsay, or matters not within the personal knowledge of the interrogated Rule 26, as a mode of discovery, contemplates party interrogatories seeking clarification in order to 2. Frivolous interrogatories need not be determine the truth of the allegation in a answered (Herrera) pleading.
Procedure:
Court Order: 1. The court may: a. Order any party to produce and permit the inspection and copying or photographing, (1) By or on behalf of the moving party (2) Of any designated documents, PHYSICAL AND MENTAL EXAMINATION OF papers, books, accounts, letters, PERSONS (Rule 28) photographs, objects or tangible things, not privileged, which When available: In an action in which the mental constitute or contain evidence or physical condition of a party is in controversy. material to any matter involved in (Rule 28, Sec. 1) the action - NOTE: It is the mental and physical (3) And which are in his possession, condition of a PARTY not a WITNESS that custody or control is in controversy
GENERAL RULE: When an issue exists, trial is AGREED STATEMENT OF FACTS (Rule 30, Sec.necessary. Decision should not be made without 6)trial. The parties may agree in writing upon the factsEXCEPTIONS: When there may be judgment involved in the litigation and submit the case forwithout trial judgment in the facts agreed upon without the 1. Judgment on the pleading (Rule 34) introduction of evidence 2. Summary Judgment (Rule 35) 3. Judgment on Compromise If the parties agree only on some of the facts in 4. Judgment on Confession issue, trial shall be held as to the disputed facts 5. Dismissal with Prejudice (Rule 17) in such order as the court shall prescribe. 6. Judgment under Rule on Summary Procedure, and Stipulation Of Facts in Stipulation Of Facts in 7. Stipulation of fact Civil Cases Criminal Cases May be signed by the Must be signed by counsel alone who both counsel andADJOURNMENTS AND POSTPONEMENTS has an SPA accused(Rule 30, Sec. 2) May be made verbally Strict; it must always or in writing be in writingGENERAL RULE: A court may adjourn a trial fromday to day, and to any stated time, as the An agreed statement of facts is conclusive onexpeditious and convenient transaction of the parties, as well as on the court. Neither ofbusiness may require the parties may withdraw from the agreement, nor may the court ignore the same. [McGuire v.LIMITATION: The court has no power to adjourn a Manufactures Life]trial for: 1. A period longer than one month for each adjournment; or ORDER OF TRIAL; REVERSAL OF ORDER 2. More than 3 months in all (Rule 30, Sec. 5)
EXCEPTION: Unless authorized in writing by General Rule: Trial shall be limited to the issues the Court Administrator, SC stated in the pre-trial order.
Where the answer of the defendant This provision permitting separate trials admitted the obligation stated in the presupposes that the claims involved are within complaint, although special defenses the jurisdiction of the court were pleaded, the plaintiff has every right - When one of the claims is not within its to insist that it was for the defendant to jurisdiction, the same should be come forward with evidence to support dismissed, so that it may be filed in the his special defenses (Yu v. Mapayo) proper court
MOTION GRANTED Denial of demurrer MOTION DENIED BUT REVERSED ON Grant of demurrer APPEAL The case shall be The defendant shall Movant shall have the Movant is deemed to dismissed have the right to right to present his have waived his right present evidence evidence to present evidence. The decision of the The court should set appellate court will be the date for the based only on the reception of the evidence of the plaintiff as the complaint acquittal. defendant loses his The judgment of right to have the case dismissal is remanded for appealable. reception of his If plaintiff appeals and evidence judgment is reversed Denial is by the appellate INTERLOCUTORY court, it will decide Judgment of acquittal Order of the court is Sec. 1, Rule 36 (that the case on the basis is NOT appealable. an ADJUDICATION ON judgment should state of plaintiff’s evidence Double jeopardy sets THE MERITS clearly and distinctly with the consequence in. Hence, the the facts and the law that the defendant requirement in Sec. 1, on which it is based) already loses his right Rule 36 should be will NOT apply. to present evidence. complied with The denial is NOT There is no res appealable judicata in dismissal due to demurrer. The plaintiff files a The court may motuDEMURRER TO EVIDENCE IN CIVIL CASES motion to deny proprio deny theVERSUS CRIMINAL CASES motion to demurrer to motion evidence CIVIL CASES CRIMINAL CASES If court denies the May be filed with or demurrer filed with without leave of court. leave, accused may Leave of court is present his evidence. Defendant need not necessary so that the If court denies the If court denies the ask for leave of court accused could present demurrer, defendant demurrer filed without his evidence if will present his leave, accused can no demurrer is denied evidence longer present his If the court finds If the court finds the evidence and submits plaintiff’s evidence prosecution’s evidence the case for decision insufficient, it will insufficient, it will based on the grant demurrer by grant demurrer by prosecution’s evidence dismissing the rendering judgment of
JUDGMENTS AND ineffective. [Corpus v. Sandiganbayan (2004)] 6. Judgment must state clearly the facts and
POST-JUDGMENT DEFINITION
The motions are filed with the court which Court action – The court may: (Rule 37, Sec. 3)rendered the questioned judgment or final order. 1. Set aside the judgment or final order and grant a new trial; or upon such terms asThe period for appeal is within 15 days after may be justnotice to the appellant of the judgment or final 2. Deny the motionorder appealed from. The 15-day period is 3. Amend such judgment or final orderdeemed to commence upon receipt by the accordingly if:counsel of record, which is considered notice to a. The court finds that excessivethe parties. Service upon the parties themselves damages have been awarded or that;is prohibited and is not considered as official orreceipt of judgment. b. That the judgment or final order is contrary to the evidence or lawEffect of Filing – The filing of a timely motioninterrupts the period to appeal. Resolution (Rule 37, Sec. 4) – he motion shall be resolved within 30 days from submissionFORM AND CONTENTS (Rule 37, Sec. 2) The 30-day period to resolve the motion is heldForm: to be mandatory [Gonzales v. Bantolo (2006)] 1. The motion must comply with the provisions of Rule 15 otherwise it will not GRANT OF THE MOTION; EFFECT be accepted for filing and/or will notGrant of motion for reconsideration - The court to run again from receipt of the notice of themay amend the judgment or final order movant of the order denying his motion (fresh 15accordingly. The amended judgment is in the day period) (Phil. Commercial and Industrialnature of a new judgment, which supersedes the Bank v. Ortiz)original judgment. Remedies if Motion is DENIED:Grant of motion for new trial - The original 1. To appeal from the judgment or finaljudgment shall be vacated, and the action shall order itselfstand for trial de novo. The recorded evidence 2. The order denying the motion may itselfupon the former trial shall be used at the new be assailed by a petition for certioraritrial without retaking them (if they are material under Rule 65and competent). 3. Rule 37, Sec. 9 says that an order denying a motion for new trial orPartial grant – Rule 37, Sec. 7 allows the court to reconsideration is NOT appealableorder a new trial or grant reconsideration as to a. NOTE HOWEVER: AM 07-7-12such issues if severable without interfering with amended Sec. 1 of Rule 41 bythe judgment or final order upon the rest. deleting “An order denying a motion for new trial or reconsideration” from the non-appealable orders.REMEDY WHEN MOTION IS DENIED; FRESH15-DAY RULE MOTION FOR MOTION FOREffect of Denial of Motion – The judgment or final NEW TRIAL RECONSIDERATIONorder shall stand as is Grounds: Grounds: 1. Fraud, 1. DamagesSingle-Motion Rule (Rule 37, Sec. 5) – A party accident, awarded areshall not be allowed to file a 2nd motion for mistake, or excessivereconsideration. excusable 2. That evidence - Follow the Omnibus Motion Rule negligence is insufficient to 2. Newly justify theNOTE: While a 2nd motion for reconsideration is discovered decision or finalnot allowed, a second motion for new trial is evidence orderauthorized Note the 3. That decision - However, it must be based on a ground qualificatio or final order is not existing nor available when the 1 st ns of each contrary to law motion was made within the period Second motion from allowed but excluding the time during Second motion may the same party is which the first motion had been pending. be allowed so long as prohibited. based on grounds not The prohibition appliesFresh 15-Day Rule: The aggrieved party has a existing or available only to final orders or“fresh period” of 15 DAYS within which to file his at the time the first judgments, hence it isappeal. motion was made allowed in interlocutory ordersIf the motion is denied, the movant has a “fresh If the court finds thatperiod” of 15 days from receipt or notice of the If a new trial is excessive damagesorder denying the motion for new trial or motion granted, original have been awarded orfor reconsideration within which to file an judgment or final that the judgment orappeal. (Neypes v. CA, 2005) order is vacated. final order is contrary The case stands for to the evidence or law,NOTES: trial de novo and will it may amend such 1. This fresh period becomes significant only be tried anew judgment or final order when a party opts to file a motion for new accordingly trial or reconsideration Available even on Available against the 2. This rule does not refer to the period appeal but only on the judgments or final within which to appeal from the order ground of newly orders or both the trial denying the motion for reconsideration discovered evidence and appellate courts but to the period within which to appeal Both are prohibited motions under Summary from the judgment itself. ProcedureFiling of a proper motion for new trial interruptsthe running of the period of appeal which begins APPEALS IN GENERAL 1. Not a natural right nor a part of due processNATURE OF APPEAL 2. It is merely a statutory right, and may be exercised only in the manner and in accordance with provisions of the law. It Not appealable must comply with the requirements; except through a failing to do so, the right to appeal is lost Appealable petition for 3. Once granted, appeals become part of certiorari under Rule due process and should be liberally 65 applied in favor of the right to appeal Must clearly and No need to comply distinctly state the with such a law and the factsJUDGMENTS AND FINAL ORDERS SUBJECT requirement on which it is basedTO APPEAL; MATTERS NOT APPEALABLE An interlocutory order is one that does not finallyRule 41, Sec. 1, as amended by AM 07-7-12-SC dispose of the case, and does not end the court's(2007) provides: task of adjudicating the parties’ contentions and 1. Appeal may be taken from a judgment or determining their rights and liabilities as regards final order that completely disposes of each other, but obviously indicates that other the case, or of a particular matter therein things remain to be done. [BPI v. Lee (2012)] when declared by the Rules to be appealable REMEDY AGAINST JUDGMENTS AND ORDERS 2. No appeal may be taken from: WHICH ARE NOT APPEALABLE a. An order denying a petition for relief or any similar motion seeking relief The aggrieved party may file a special civil from judgment; action under Rule 65. (Rule 41, Sec. 1) b. An interlocutory order; c. An order disallowing or dismissing an appeal; MODES OF APPEAL d. An order denying a motion to set 1. Ordinary appeal – Rule 40 and 41 aside a judgment by consent, a. Notice of appeal confession or compromise on the b. Record on appeal ground of fraud, mistake or duress, or 2. Petition for review – Rule 42 any other ground vitiating consent; 3. Petition for review on certiorari – Rule 45 e. An order of execution; f. A judgment or final order for or PETITION FOR against one or more of several parties ORDINARY PETITION FOR REVIEW ON or in separate claims, counterclaims, APPEAL REVIEW CERTIORARI cross-claims and third-party Appeal by complaints, while the main case is Rule 42 Rule 45 writ of error pending, unless the court allows an Case is Case decided Case decided appeal therefrom; and decided by by RTC in the by the RTC, g. An order dismissing an action without RTC in its exercise of its CA, CTA, and prejudice. original appellate Sandiganbaya jurisdiction jurisdiction n NOTE: AM 07-7-12-SC removed from Petition for the original list “an order denying a Appealed to Appealed to review with motion for new trial or the CA the SC the CA reconsideration.” File verified File a verified petition for NOTE, HOWEVER: Rule 37, Sec. 9 petition for review on which states that no appeal can be review with File notice of certiorari with made from an order denying MR or CA. appeal or the SC. MNT. Pay docket record of Pay docket and lawful appeal with and lawfulOnly final judgments or orders can be appealed fees and P500 court of fees and P500as distinguished from interlocutory judgments or as deposit for origin and for costs.orders which are not appealable. costs with the give a copy Submit proof CA. to adverse of service of a Furnish RTC party copy to the Final Order Interlocutory Order and adverse lower court party a copy of and adverse Disposes of the such Does not dispose of party matter in its Within 15 Within 15 days Within 15 a case completely entirety, leaving days from from notice of days from but leaves nothing more to be notice of decision to be notice of something more to done but to enforce judgment for reviewed or judgment or be decided upon. execution notice of from denial of order of appeal and the most 30 days for denial of MFR compelling a MFR or MFNT records on or MFNT reasons and appeal in no case longer than 15 days. QJA to CAISSUES TO BE RAISED ON APPEAL The CA may grant a 15Limited to cognizable judgments/issues. day 15 days from notice extension.The appellate court has no jurisdiction to review of the award, No furthera judgment which is immediately final and judgment, final extension Freshexecutory by express provision of law. [Republic order or resolution shall be period tov. Bermudez-Lorino (2005)] or from date of last granted appeal publication if except for from denialRationale: Appeal is merely a privilege conferred required by law OR the most MR or MNTby law upon the litigants. from denial of MR compelling or MNT reasons andA party cannot change the theory on appeal. in no caseOnly issues pleaded in the lower court and longer thanproperly raised may be resolved by the appellate 15 days.court. [Medina v. CA (1992)] RTC to SC RTC to CA to SCHowever, issues which are inferred from or CA to SCnecessarily connected with the issue properly 15 days from notice The SC mayraised and pleaded may be resolved by the Fresh of judgment or final grant a 30appellate court. [Espina v. CA (1992)] period to order OR from day appeal denial of extension for from denial petitioner’s MR or justifiablePERIOD OF APPEAL MR or MNT MNT. reasons.
By Notice of Appeal 1. File a notice of appeal with the trial court that rendered the judgment or final order appealed from 2. The notice of appeal must indicate the parties, the judgment or final order or part thereof appealed from; the material date showing timeliness of appeal 3. A copy served on the adverse party; and 4. Payment in full of docket fees and other lawful fees inconsistent with or may serve to supplementBy Record on Appeal the provisions of this Rule. 1. Record on appeal is required for the following cases: a. Special proceedings b. In such other cases where multiple appeals are allowed 2. Form and contents of the record on appeal: (Rule 41, Sec. 6) a. Within 15 days from perfection of appeal, clerk of court or the branch clerk of the lower court shall transmit to the RTC: (1) Original record or record on appeal (2) Together with transcripts and exhibits b. Clerk shall make a certification that the documents are complete c. Clerk shall also furnish the parties a copy of his letter of transmittal of the records to the appellate court 3. Copy is served on the adverse party 4. Payment in full of docket fees and other lawful fees
PERFECTION OF APPEAL
Two Scenarios:
2. PETITION FOR REVIEW, where judgment Approval of the Record on Appeal (Rule was rendered by the RTC in the exercise 41, Sec. 7) – Upon filing of the record for of its appellate jurisdiction approval and if no objection is filed by the a. This mode of appeal, covered by Rule appellee within 5 days from receipt of a 42, is brought to the CA on question copy thereof, the trial court may: of fact, of law, or mixed questions of 1. Approve it as presented; or fact and law 2. Direct its amendment by the inclusion of any omitted matters which are 3. PETITION FOR REVIEW ON CERTIORARI, or deemed essential appeal by certiorari to the SC a. This mode of appeal, provided for by Joint Record on Appeal (Rule 41, Sec. 8) – Rule 45, is brought to the SC from the Where both parties are appellants, they decision of the RTC in the exercise of may file a joint record on appeal. its original jurisdiction and only on questions of law PERIOD TO APPEAL (Rule 41, Sec. 2)HOW ORDINARY APPEAL VIA RULE 41 IS 1. 15 days from notice of judgment or finalMADE: order appealed from 2. 30 days from notice of judgment or finalAppeal via Rule 41 presupposes that: order where a record on appeal is 1. The RTC rendered the judgment or final required order in the civil action or special 3. 48 hours from notice of judgment or final proceeding in the exercise of its ORIGINAL order appealed from in habeas corpus jurisdiction; and cases 2. That the appeal is taken to the CA on: a. Questions of fact or Reckoning point of reglementary period: Period b. Mixed questions of fact and law for filing the appeal should be counted from the date when the party’s counsel received a copy ofNotice of Appeal – Filed with the court which the judgment or final orderrendered the judgment or final order appealedfrom. A copy is served on the adverse party. When a party is represented by a counsel,(Rule 41, Sec. 5) service of process must be made on counsel, not on party (Fajardo v. CA) Contents of the Notice of Appeal: 1. Parties to the appeal Effect of Motions for New Trial and 2. Judgment or final order or part thereof Reconsideration – Originally, the period to appealed from appeal is interrupted by a timely motion for new 3. The court to which the appeal is being trial and reconsideration. However, with the taken; and Neypes doctrine, a party has a fresh 15-day 4. The material dates showing the period from a denial of the motion to perfect an timeliness of the appeal appeal.
NOTE: In petitions for review under Rules PERFECTION OF APPEAL (Rule 42, Sec. 8) 42, 43, and 45, the docket fee is paid in the appellate courts Appeal is deemed perfected as to PETITIONER upon: 2. Deposit for costs 1. Timely filing of the petition 3. Proof of service of petition 2. Payment of docket and lawful fees 4. Contents of the documents, which should accompany the petition Jurisdiction of the RTC 1. RTC loses jurisdiction upon:ACTION ON PETITION (Rule 42, Sec. 4) a. Perfection of appeals filed in due time; andThe CA may: b. Expiration of the time to appeal of 1. Require respondent to file a comment on other parties the petition not a motion to dismiss 2. RTC may exercise residual jurisdiction within 10 days from notice; or before the CA gives due course to the petition 2. Dismiss the petition if it finds the same to be: General Rule: Perfected appeal stays the a. Patently without merit challenged judgment or final order b. Prosecuted manifestly for delay; or c. The questions raised therein are too Exceptions: unsubstantial to require consideration 1. Unless the CA, law, or Rules, provide otherwiseREMEMBER: Under this Rule, appeal is 2. Also in civil cases decided under thediscretionary on the CA which may give its due Rule on Summary Procedure; Stay ofcourse only when the petition shows prima facie judgment is not applicable here sincethat the lower court has committed error. these are immediately executory
COMMENT BY RESPONDENT (Rule 42, Sec. 5) SUBMISSION OF DECISION (Rule 42, Sec. 9)
SCOPE
ACTION ON THE PETITION (Rule 43, Sec. 8) Exception: When the CA shall direct otherwise upon such terms as it may deem justThe CA may: 1. Require respondent to file Comment within 10 days from notice SUBMISSION FOR DECISION (Rule 43, Sec. 13) 2. Dismiss the petition if CA finds the same to be: If petition is given due course, the CA may set a. Patently without merit the case for oral argument or require parties to b. Prosecuted manifestly for delay, or submit memoranda within 15 days from notice.Upon filing of last pleading or memorandum 1. In criminal cases, ruling of Ombudsmanrequired, case is deemed submitted for decision. shall be elevated to the SC via Rule 65 2. In cases in which it is alleged that the Ombudsman has acted with grave abuseAPPEAL FROM JUDGMENTS OR FINAL of discretion amounting to lack or excessORDERS OF THE CTA of jurisdiction, a special civil action of certiorariunder Rule 65 may be filed withA party adversely affected by a decision or ruling this Court to set aside the Ombudsman’sof the CTA en banc may file with the Supreme order or resolution. [Nava v. NBI (2005)]Court a verified petition for review on certioraripursuant to Rule 45. (Sec. 19, RA 1125 asamended by RA 9282) APPEAL FROM JUDGMENTS OR FINAL ORDERS OF THE NLRC
APPEAL FROM JUDGMENTS OR FINAL Rule 43, Sec. 2 states that Rule 42 shall notORDERS OF THE COMELEC apply to judgments or final orders issued under the Labor Code.Unless otherwise provided by law, or by anyspecific provisions in these Rules, any decision, The law no longer provides for an appeal fromorder or ruling of the Commission may be decisions of the LA or from the NLRC. Mode ofbrought to the Supreme Court on certiorari by review from said decisions is the special civilthe aggrieved party within thirty (30) days from action for Certiorari under Rule 65 in the CA.its promulgation. (Rule 37, Sec. 1, COMELECRules of Procedure) NLRC judgments and final orders or resolutions are now reviewable, in the first instance, by theDecisions in appeals from courts of general or Court of Appeals on certiorari under Rule 65, butlimited jurisdiction in election cases relating to those of the Employees Compensationthe elections, returns, and qualifications of Commission should be brought to the Court ofmunicipal and barangay officials are not Appeals through a petition for review under thisappealable. (Rule 37, Sec. 2, COMELEC Rules of Rule. Also, appeals from the Office of theProcedure) Ombudsman in administrative disciplinary cases are now covered by this Rule. [Fabian v. DesiertoDecisions in pre-proclamation cases and (1998)]petitions to deny due course to or cancelcertificates of candidacy, to declare a candidateas nuisance candidate or to disqualify acandidate, and to postpone or suspend electionsshall become final and executory after the lapseof five (5) days from their promulgation, unlessrestrained by the Supreme Court. (Rule 37, Sec.3, COMELEC Rules of Procedure)
Jurisdiction of the CA 1. CA has jurisdiction over orders, directives, and decisions of the Office of Ombudsman in administrative disciplinary cases only 2. It cannot review orders, directives, decisions in criminal and non- administrative cases
Jurisdiction of the SC APPEAL BY CERTIORARI TO THE SUPREME COURT (RULE 45) The petition may include an application for a writ of preliminary injunction or other provisional remedies and shall raise only questions of law,CERTIORARI AS A MODE OF APPEAL (RULE which must be distinctly set forth. The petitioner45) AND CERTIORARI AS A SPECIAL CIVIL may seek the same provisional remedies byACTION (RULE 65) verified motion filed in the same action or proceeding at any time during its pendency. (Rule 45, Sec. 1, as amended by A.M. 07-7-12- APPEAL BY CERTIORARI AS AN SC) CERTIORARI ACTION Rule 45 Rule 65 OUTLINE OF PROCEDURE Petition raises the issue as to whether Based on questions of RTC, Sandiganbayan, CTA en banc, or CA renders a the lower court acted law which appellant decision without or in excess of desires the appellate jurisdiction or with court to resolve grave abuse of discretion May be directed against an interlocutory order of the court prior to Involves review of appeal from the judgment, award or judgment or where final order on merits there is no appeal or Any party files a petition for review on certiorari any other plain, Within 15 days from notice speedy, or adequate of final judgment or order of lower court remedy or notice of denial of motion for reconsideration or new trial May be filed not later Must be made within than 60 days from the reglementary notice of judgment, period of appeal order or resolution sought to be assailed Does not stay the challenged Stays the judgment, proceedings award, or order Appellant serves copies of petition on adverse parties (unless a writ of And to the lower court, appealed from preliminary injunction And pay the corresponding docket fees or TRO is issued) The parties are the Petitioner and aggrieved party respondent are against the lower court original parties to the or quasi-judicial action agency as prevailing parties A filing of a MR is a Prior filing of MR not condition precedent, required subject to certain SC may dismiss the petition or require appellee to exceptions comment Higher court exercises original jurisdiction Appellate court is in under its power of the exercise of control and appellate jurisdiction supervision over and power of review proceedings of lower courts
SC may affirm, reverse, or modify judgment of lower APPEAL FROM RTC TO SC UNDER RULE 45 court
The Neypes doctrine is also applicable in Appeal to the SC is NOT a matter of right. It will Rule 45. be granted only when there are special and important reasons therefor.Extension of Period: 30 days upon 1. Motion duly filed and served; and Some indications of the character of reasons 2. Payment of docket and lawful fees and which will be considered: deposit for costs 1. When the court a quo has decided the 3. And for justifiable reasons question of substance, not theretofore determined by the SC, or has decided it in a way probably not in accord with law orFORM OF PETITION with the applicable provisions of the SC; 1. The petition must be VERIFIED or 2. Following the Efficient Use of Paper Rule: 2. Court a quo has so far departed from a. One original, properly marked, and 4 accepted and usual course of judicial copies proceedings, or so far sanctioned such b. If the case is referred to En Banc, 10 departure by a lower court, as to call for additional copies is filed an exercise of power of supervision 3. Payment of docket and other lawful fees and deposit of P500 for costs is made with the SC Clerk at the time of filing ELEVATION OF RECORDS: (Rule 45, Sec. 8) 4. Proof of service of the petition to the lower court and adverse party are If the petition is given due course, the Supreme attached Court may require the elevation of the complete record of the case or specified parts thereof within fifteen (15) days from noticeCONTENTS OF PETITION (Rule 45, Sec. 4) 1. State full names of the parties a. Appealing party = as Petitioner GROUNDS FOR DISMISSAL OF comply with orders, circulars, directives APPEAL of the court without justifiable cause 9. Fact that the order or judgment appealedDISMISSAL BY THE CA (RULE 50) from is not appealable
NOTE: This is not applicable to the SC since it is not a trier of facts. WHEN PROPER
RULE 37 v. RULE 38 Rule 38 can be availed of once the judgment has become final and executory. RULE 37 RULE 38 Available BEFORE Available AFTER The relief provided for by Rule 38 is of equitable character and is only judgment becomes judgment has become allowed in exceptional cases, that is where there is no other available or final and executory final and executory adequate remedy. A petition for relief is not regarded with favor and judgment will not be disturbed where the party complaining has or by Applies to judgments, Applies to judgments his exercising proper diligence would have had an adequate remedy at final orders and other or final orders only law, as where petitioner could have proceeded by appeal to vacate or proceedings modify the default judgment. [Manila Electric v. CA (1990)] Grounds: (1) FAME and (2) Newly Ground: FAME Under Sec. 1, it is also available when “any other proceeding is discovered evidence thereafter taken against the petitioner in any court through FAME” Filed within 60 days from knowledge of Filed within the time Thus, it was held that a petition for relief is also applicable to a judgment and within 6 to appeal proceeding taken after entry of judgment or final order such as an order months from entry of of execution (Cayetano v. Ceguerra) or an order dismissing an appeal judgment (Medran v. CA) If denied, order If denied, order of denying a petition for denial is not relief is not appealable; hence, WHERE FILED appealable; remedy is remedy is appeal from appropriate civil action Rule 38 is not an independent action but a continuation of the old case. judgment under Rule 65 Hence, it is filed with the same court and same branch which decided Legal remedy Equitable remedy the case. Motion need not be Petition must be 4. When judgment was entered by mistake or was obtained byGROUNDS: (Rule 38, Sec. 1 and 2) fraud; or 1. When judgment or final order is entered or any other proceeding 5. Other similar cases. is thereafter taken against petitioner through FAME 2. When petitioner has been prevented from taking an appeal by FAME ORDER TO FILE ANSWER (Rule 38, Sec. 4)
The two periods for the filing of a petition for relief are not extendibleand never interrupted. Both periods must be complied with. (Phil. PROCEEDINGS AFTER ANSWER IS FILED (Rule 38, Sec. 6)Rabbit Bus Lines Inc. v. Ariaga) After filing of answer or expiration of the period therefor, court shallReckoning points: hear the petition. 1. The 60-day period is reckoned from the time the party acquired knowledge of the order, judgment or proceeding. Not from the If the court finds that the allegations are not true – Petition is dismissed. date he actually read the same (Perez v. Araneta) 2. 6-months period is computed from the date of entry of the order If the court finds that allegations are true: or judgment 1. It shall set aside the judgment, final order, or other proceeding complained of upon such terms as may be just 2. Thereafter, case shall stand as if such had never been rendered,FORM AND CONTENTS OF THE PETITION issued, or taken 1. The petition for relief must be verified 3. The court shall then proceed to hear and determine the case as 2. The petition must be accompanied by an affidavit showing the if timely motion for new trial or reconsideration has been FAME relied upon; and granted by it 3. The affidavit of merit accompanying the petition must also show the facts constituting the petitioner’s good and substantial cause of action or defense as the case may be REMEDY FOR DENIAL OF PETITION FOR RELIEF.
The absence of an affidavit of merits is a fatal defect and warrant denial Appeal from an order denying a petition for relief is no longer availableof the petition (Fernandez v. Tan Tiong Tick) under the present rules.
However, it is not a fatal defect so long as the facts required to be set The remedy against a denial of a petition for relief is certiorari underout also appear in the verified petition (Fabar Inc. v. Rodelas) Rule 65, when proper.
The purpose of such action is to have the final and executory judgment A person who is not a party to the judgment may sue for its annulmentset aside so that there will be a renewal of litigation. provided that he can prove the same was obtained through fraud or collusion and that he would be adversely affected thereby. (Alaban v.Resorted to in cases where ordinary remedies of new trial, appeal, CA)petition for relief, or other appropriate remedies are no longer availablethrough no fault of petitioner GROUNDS (Rule 47, Sec. 2)
It is not a mode of appeal but an Independent Civil Action. Annulment may be based only on TWO grounds: 1. Extrinsic Fraud 2. Lack of JurisdictionWHEN PROPER (Rule 47, Sec. 1) Although Sec. 2 provides that annulment of judgment or order may beIt is available when the petitioner failed to move for new trial in, or based only on extrinsic fraud and lack of jurisdiction, jurisprudenceappeal from, or file a petition for relief against, or take other appropriate recognizes DENIAL OF DUE PROCESS as an additional ground (Sps.remedies assailing the questioned judgment or final order or resolution Benatiro, et al. v. Heirs of Cuyos et al.) This was recognized in the 2013through no fault attributable to him case of Leticia Diona, represented by her Attorney-in-fact, Marcelina Diona v. Romeo Balangue, Sonny Balangue, Reynaldo Balangue, andThe remedy may no longer be invoked where the party has availed Esteban Balangue, Jr.himself of the remedy of new trial, appeal, petition for relief, or otherappropriate remedy and lost or where he has failed to avail himself of Extrinsic or Collateral Fraud - Refers to any fraudulent act of thethose remedies through his fault or negligence prevailing party in the litigation which is committed outside of the trial of the case, whereby the defeated party has been prevented from exhibiting fully and fairly presenting his side of the caseWHERE FILED Lack of Jurisdiction - Lack of jurisdiction refers to either lack of JUDGMENTS, FINAL JUDGMENTS, FINAL jurisdiction over the person of the defending party or over the subject ORDERS, OR ORDERS, OR matter of the claim, and in either case, the judgment or final order and RESOLUTIONS OF THE RESOLUTIONS OF THE resolution are void. RTC MTC Filed with the CA Filed with the RTC NOTE: In a petition for annulment of judgment based on lack of jurisdiction, petitioner must show an ABSOLUTE LACK of CA has exclusive and RTC as a court of jurisdiction not merely abuse of jurisdictional discretion. original jurisdiction general jurisdiction over said action under under Sec. 19(6) BP As to Evidence Sec. 9 (2) of BP 129 129 1. When the ground invoked is extrinsic fraud, extraneous evidence The CA may dismiss The RTC has no such is admitted the case outright; it discretion, it is 2. However, when the ground is lack of jurisdiction, only evidence found in the records of the case can justify nullity of judgment NOTE: Prima facie determination is not available in annulment of judgments or final orders of MTCs before the RTC. (Rule 47, Sec. 10)
PERIOD FOR FILING (Rule 47, Sec. 3) EFFECT OF JUDGMENT OF ANNULMENT (Rule 47, Sec. 7)
The rule does not fix the period to annul judgment based on lack of Effect of annulment based on extrinsic fraudjurisdiction but recognizes the principle of estoppel as first laid down by 1. The same shall be set aside and considered null and voidTijam v. Sibonghanoy. 2. On motion of the prevailing party on justifiable grounds, he may be allowed to no longer refile the action a. The trial court which rendered the questioned judgment shallFORM AND CONTENTS OF PETITION (Rule 47, Sec. 3) be ordered to try the case anew 1. Verified petition, alleging therein: a. With particularity, the facts and the law relied upon The prescriptive period for the refiling of the aforesaid original action b. Petitioner’s good and substantial cause of action or defense shall be deemed suspended from the filing of said original action until 2. Filed following the Efficient Use of Paper Rule the finality of the judgment of annulment. However, the prescriptive 3. Certified true copy of the judgment or final order or resolution period shall not be suspended where the extrinsic fraud is attributable shall be attached to the original copy of the petition to the plaintiff in the original action. (Rule 47, Sec. 8) 4. Affidavits of witnesses or documents supporting the cause of action or defense; and 5. Certificate of non-forum shopping
PROCEEDINGS
ON ATTACKING THE VALIDITY OF A JUDGMENT A void judgment may be likened to a lawless thing which can be treated as an outlaw and slain at sight, or ignored wherever and whenever itDirect Attack v. Collateral Attack: rears its head. [Banco Espanol-Filipino v. Palanca (1918)] 1. Direct attack upon a judgment is an action or proceeding to annul it, this being the main object of the proceeding A judgment may be void for lack of due process of law. [Spouses 2. Collateral attack upon a judgment is one made to obtain relief Benatiro v. Heirs of Cuyos (2008)) other than the setting aside of the judgment, the attack on the judgment itself being incidental ATTACKING A VOID JUDGMENTWhen Collateral Attack Proper: This is proper only when the judgmenton its face is null and void as where it is patent that the court which It may be assailed anytime, collaterally or in a direct action or byrendered said judgment has no jurisdiction resisting such judgment or final order in any action or proceeding whenever it is invoked, unless barred by laches. [Spouses Benatiro v.The validity of a judgment or order of the court, which has become final Heirs of Cuyos (2008))and executory, may be attacked in three ways: 1. Only by a direct action or proceeding to annul the same This proceeding is a direct attack against the order of REMEDIES judgment because it is not incidental to, but is the main object of, the proceeding If the reglementary period for appeal has not yet lapsed, some A direct action to annul and enjoin enforcement of the remedies are New Trial and Reconsideration. Appeal, Petition for Relief, and Other Appropriate Remedies such as Certiorari may also be used. judgment where the alleged defect is not apparent on its face or from the recitals contained in the judgment If the appropriate remedies are no longer available without the fault of See Rule 47 the petitioner, the equitable and extraordinary remedy of Petition for Annulment of Judgment may be resorted to. 2. Or by direct action, as certiorari, or by collateral attack in case of apparent nullity When all else fails, there is jurisprudence to the effect that a patently The collateral attack must be against a challenged judgment void judgment may be dealt with by a Main Action for Injunction. [See which is void upon its face or that the nullity of the judgment Barrameda v. Moir (1913)] is apparent from its own recitals
EXECUTION, presented at the trial, declares categorically what the rights and obligations of the parties are and which party is in the right; or a judgment or order that dismisses an action on the ground, for instance,
Once rendered, the task of the Court is ended, as far as deciding theEFFECT OF JUDGMENTS DIFFERENCE BETWEEN FINALITY OF JUDGMENT FOR judgment once it becomes 'final or, to use the established and more PURPOSES OF APPEAL; FOR PURPOSES OF distinctive term, 'final and executory. EXECUTION Execution is a matter of right upon the expiration of the period toThe term “finality of judgment for purposes of appeal” refers to appeal and no appeal was perfected from a judgment or order thatinterlocutory orders which: disposes of the action or proceeding. [Rule 39, Sec. 1] 1. Are not decisions within the constitutional definition [Armargo v. CA (1973)] 2. are those that determine incidental matters that do not touch on It can be noted that the Supreme Court made a hairline distinction the merits of the case or put an end to proceedings. The between finality of order for appeals and for execution. It is submitted following are examples of an interlocutory order: that upon court’s issuance of a judgment touching upon the merits of a a. An order denying a motion to dismiss; case, it is final for the purposes of an appeal, but NOT for execution. b. An order granting an extension of time to file a pleading, or one authorizing an amendment thereof; NOTE: Finality for the purposes of execution refers to the expiration of c. Order granting or denying applications for postponement or the period to appeal and no appeal was perfected. inspection of documents. [Riano]
The word interlocutory refers to something intervening between the WHEN EXECUTION SHALL ISSUEcommencement and the end of a suit which decides some point ormatter but is not a final decision of the whole controversy. [Ramiscal, Jr. Execution is a process provided by law for the enforcement of a finalv. Sandiganbayan (2004)] judgment. Enforcement is part of court’s jurisdiction. It is not an action but is included in the phrase “Process in an action – part of theA final judgment or order is one that finally disposes of a case, leaving proceedings considered as still pending.nothing more to be done by the Court in respect thereto, e.g., anadjudication on the merits which, on the basis of the evidence Cases where Execution may Issue even if judgment NOT Final: 1. Support pendente lite acquired only after filing of ejectment suit (Cordova v. 2. Judgments of inferior courts in ejectment cases Tornilla) 3. Execution pending appeal 4. Injunction, accounting, receivership, support (Rule 39, Sec. 4) 5. Decision of the RTC in appealed civil cases under Summary EXECUTION AS A MATTER OF RIGHT (Rule 39, Sec. 1) Procedure, including forcible entry and unlawful detainer 6. Decision of the LA reinstating dismissed employee, insofar as The finality of judgment has the effect of entitling prevailing party to reinstatement aspect is concerned execution as a matter of right. It is the ministerial duty of the court to do execution. (Herrera)Writ of Execution: A judicial writ issued to an officer authorizing him toexecute the judgment of the court. Execution as a matter of right, TWO INSTANCES: 1. No appeal has been perfected or period of appeal has expiredDispositive Portion as Subject of Execution 2. Appeal has been perfected and finally resolved 1. General Rule: The dispositive portion of the decision is that part that becomes the subject of execution How Done: 2. Exceptions: a. Where there is ambiguity, the body of the opinion may be CASE HOW EXECUTION IS CARRIED referred to for purposes of construing the judgment because If no appeal has Prevailing party applies by the dispositive part of a decision must find support from been perfected, motion for a writ of execution decision’s ratio decidendi or the period of which is granted by the judge b. Where extensive and explicit discussion and settlement of appeal has since it is a matter of right the issue is found in the body of the decision expired Prevailing party:Two Whom Issued: 1. Files a motion in the 1. General Rule: Only real parties in interest in an action are bound court of origin, by judgment rendered therein and by the writs of execution 2. Submitting certified 2. Exceptions: There are certain cases where the writ may be true copies of the issued against non-parties judgment or final a. One who is privy to judgment debtor can be reached by an orders sought to be order of execution and writ of demolition (Vda. De Medina v. enforced Cruz) If appeal has 3. Submitting the entry b. Issued against one who not being originally a party to the been perfected thereof, case submits his interest to the court for consideration in the and finally 4. With notice to adverse same case and invites adjudication regarding said interest resolved party (Jose v. Blue) Appellate court may also c. Where non-parties voluntarily signed the compromise direct the court of origin to agreement or voluntarily appeared before court (Rodriguez v. issue the writ of execution: Alikpala) 1. Upon motion in the d. Where the remedy of a person not a party to the case which same case AND he did not avail of, was to intervene in the case in question 2. When the interest of involving rights over the same parcel of land and said person justice so requires in another case was adjudged buyer in bad faith thereof (Lising v. Plan) General Rule: It is a matter of right on the part of the winning party e. In an ejectment case, where 3rd party derived his right of when the judgment or order becomes executory. The court cannot possession from defendant particularly when such right was refuse execution. the court courtExceptions: The issuance of a writ of execution which issues as a matter Upon showing of good Provided there are noof right can be countered in any of the following cases reason for execution supervening events 1. ): 2. When a PETITION FOR RELIEF or an action to enjoin judgment is Under the Rule on Discretionary Execution (also called execution filed and a preliminary injunction is prayed for and granted (Rule pending appeal), the court rendering the judgment, if it still has 38, Sec. 5); jurisdiction, may exercise discretion and order execution pending 3. When the judgment turns out to be INCOMPLETE OR IS appeal. CONDITIONAL since as a matter of law, such judgment CANNOT BE FINAL; It is the execution of a judgment or final order before it attains finality. 4. When the judgment has been NOVATED BY THE PARTIES The court which rendered the decision can grant an execution pending 5. When SUBSEQUENT FACTS AND CIRCUMSTANCES transpire as to appeal if it still retains jurisdiction over the case and is in possession of render such execution unjust or impossible the records at the time of the filing of the motion; otherwise, the motion 6. On EQUITABLE GROUNDS as when there has been a change in shall be acted upon by the appellate court. the situation of the parties which makes execution INEQUITABLE. To be valid, there should be a good reason to justify the execution of the 7. When the judgment becomes DORMANT, the 5-year period under judgment pending appeal, the same to be stated in the order granting Rule 39.6 having expired without the judgment having been it. revived
NOTE: Execution may only issue upon motion with notice of hearing. Discretionary Execution is NOT applicable in the case of the Court of Appeals:Supervening Event Doctrine – A supervening event can be invoked for 1. The Rule on Discretionary Execution contemplates a situationthe modification or alteration of a final judgment. This refers to: where a judgment or final order rendered in the exercise of its 1. Facts which transpire after judgment has become final and original jurisdiction and the prevailing party in said decision executory. Or seeks immediate execution during the pendency of an appeal. 2. New circumstances which developed after the judgment has 2. The CA has no authority to issue IMMEDIATE EXECUTION acquired finality PENDING APPEAL OF ITS OWN DECISIONS THEREIN. 3. Matters which the parties were not aware of prior to or during 3. Discretionary execution is allowed pending appeal of judgment the trial as they were not yet in existence at that time or final order of the trial court upon good reasons to be stated in 4. The supervening facts or circumstances must either bear a direct a special order. effect upon the matters already litigated and settled or create a substantial change in the rights or relations of the parties therein A judgment of the CA cannot be executed pending appeal. (Heirs of which render execution of the final judgment unjust or Justice JBL Reyes v. CA, 2000) impossible (Lim v. Jabalde)
2. The judgment obligor shall pay the amount of the judgment debt a. Payable in Cash, Certified bank check payable to judgment obligee, or any other form of payment acceptable to judgment obligee (1) In no case shall sheriff demand that any payment by check be made payable to him (2) Amount of judgment under proper receipt directly to the judgment obligee or his authorized representative if present at time of payment
3. The judgment obligor shall pay the lawful fees handed over to the sheriff. Sheriff shall turn over the said amount within the same day to the clerk that issued the writ
SATISFACTION BY LEVYLevy is the act whereby a sheriff sets apart or appropriates for the Garnishment is considered as a species of attachment for reachingpurpose of satisfying the command of the writ, a part or the whole of credits belonging to the judgment debtor and owing to him from athe judgment debtor’s property. stranger to the litigation
Levy means the act or acts by which an officer sets apart or The Officer may levy on:appropriates a part or the whole of the property of the judgment debtor 1. Debts due the judgment obligor and other credits,for purposes of the prospective execution sale [Llenares v. Vandevella 2. Including bank deposits, financial interests, royalties,(1966)]. commissions, 3. And other personal property not capable of manual delivery inIf susceptible of appropriation, the officer removes and takes the possession and control of third partiesproperty for safekeeping; otherwise the same is placed under sheriff’sguards. Without valid levy having been made, any sale of the property The process of levying shall be called garnishment if the propertythereafter is void. involved is money, stocks, or other incorporeal property in the HANDS OF THIRD PERSONS. Garnishment merely sets apart such funds but does not constitute the creditor as owner of the garnished property.Conditions to be met before resort to satisfaction by levy: 1. If the judgment obligor cannot pay all or part of the obligation Garnishment is not a violation of RA 1405 on the secrecy of bank then the officer shall levy upon the properties of the judgment deposits. [Chinabank v. Ortega (1973)] obligor 2. Characteristics of properties to be levied Notes: Upon service of the writ of garnishment, the garnishee becomes a. Properties of every kind and nature whatsoever a “virtual party” or “forced intervenor” to the case and the trial court b. Which may be disposed of for value thereby acquires jurisdiction to bind the garnishee to comply with its c. Not otherwise exempt from execution orders and processes. [BPI v. Lee (2012)]
Procedure: UP’s funds, being government funds, are not subject to garnishment. 1. The judgment obligor have the option to immediately choose Moreover, The execution of the monetary judgment against the UP was which property or part thereof may be levied upon, sufficient to within the primary jurisdiction of the COA. [UP v. Dizon (2012)] satisfy judgment Procedure: 2. If judgment obligor does not exercise the option: 1. Levy shall be made by serving notice upon: a. The officer shall first levy on personal properties, if any a. The person owing such debts, or b. If personal properties are insufficient, then on the real b. Having in his possession or control such credits to which properties judgment obligor is entitled
3. Sheriff shall sell only sufficient portion of personal or real 2. Garnishment to cover only such amount as will satisfy judgment property of the judgment obligor levied upon and lawful fees
4. If there is more property than is sufficient to satisfy judgment 3. If there are 2 or more garnishees, holding deposits or credits and lawful fees, then sell only so much as is sufficient sufficient to satisfy judgment, judgment obligor shall have the right to indicate the garnishee/s who shall be required to deliver. Otherwise, the choice shall be made by judgment obligeeGARNISHMENT OF DEBTS AND CREDITS 4. The garnishee shall make a written report to the court within 5 days from service of notice of garnishment. The report shall state whether: a. Judgment obligor has sufficient funds or credits to satisfy EXECUTION OF JUDGMENTS FOR SPECIFIC ACTS judgment, OR b. Judgment obligor has insufficient funds or credits to satisfy When proper: (Rule 39, Sec. 10) judgment 1. Resorted to if the judgment directs a party to: a. Execute a conveyance of land or personal property, or5. Garnish the amount which may be in cash, or certified bank b. Deliver deeds or other documents, or check issued in the name of judgment obligee c. Perform any other specific act in connection therewith. 2. AND the party fails to comply within the time specified6. Garnished amount shall be delivered directly to judgment obligee within 10 working days from service of notice on said Procedure: garnishee requiring such delivery 1. Court may direct the act to be done a. At the cost of disobedient party7. Follow procedure under “Immediate Payment on Demand” with b. Or by some other person appointed by the court respect to delivery 2. In case of directing conveyance of real or personal property8. Lawful fees shall be paid directly to court located in the Philippines: a. Court may divest the title of any party and vest it in others by court order b. This shall have the force and effect of conveyance executed in due form.
Examples: 1. A judgment in mandamus to reinstate petitioner as chief clinic of the hospital (Vital-Gozon v. CA) 2. A judgment directing petitioner to vacate the land which is a judgment to deliver possession of real property and not special judgment. No contempt for refusal (Moslem v. Soriano) 3. A judgment directing defendant to remove a fence from a certain place is a special judgment (Marquez v. Marquez) EFFECT OF LEVY ON THIRD PERSONS PROPERTIES EXEMPT FROM EXECUTIONThe levy on execution shall create a lien in favor of the judgment General Rule: Except as otherwise expressly provided by law, theobligee over the right, title and interest of the judgment obligor in such following property, and no other, shall be exempt from execution (Ruleproperty at the time of the levy, subject to liens and encumbrances 39, Sec. 13)then existing. (Rule 39, Sec. 12) 1. The judgment obligor's family home as provided by law, or the homestead in which he resides, and land necessarily used inNOTE: The power of the court in execution extends only over properties connection therewith;UNQUESTIONABLY belonging to judgment debtor. 2. Ordinary tools and implements personally used by him in his trade, employment, or livelihood;
8. One fishing boat and accessories not exceeding the total value of one hundred thousand pesos owned by a fisherman and by the lawful use of which he earns his livelihood;
The exemptions MUST BE CLAIMED, otherwise they are deemed waived. 2. The writ shall continue in effect during the period within whichIt is not the duty of the sheriff to set off the exceptions on his own judgment may be enforced by motioninitiative. (Herrera v. Mcmicking, 1909) 3. Officer shall make a report to the court every 30 days on the proceedings taken thereon, until either: a. Judgment is satisfied in full, or b. Its effectivity expires
The writ shall continue in effect during period within which the judgment may be enforced by motion which is 5 years from date of entry. After the first 5 years, judgment becomes dormant and subject to revival action.PROCEEDINGS WHERE PROPERTY CLAIMED BY THIRD PERSON Effect of Third-Party Claim: When a third-party claim is filed, sheriff is not bound to proceed with the levy of the property unless judgment creditor or latter’s agent posts an indemnity bond against the claim.CONCEPTS
Rule 39, Sec. 16 and other provisions which provide for a mode of SUMMARY HEARING BEFORE COURT AUTHORIZING EXECUTIONrecovering property allegedly to have been wrongfully taken by sheriffpursuant to a writ of execution or other process, refers to a STRANGER A third-person whose property was seized by a sheriff to answer for anto an action. obligation of a judgment debtor may invoke the supervisory power of the court which authorized such executionRemedies of Third-Party Claimant: 1. Summary hearing before the court which authorized the Procedure: execution 1. Claimant files application 2. “Terceria” or third-party claim filed with the sheriff (Rule 39, Sec. 16) 2. Court conducts summary hearing 3. Action for damages on the bond posted by the judgment creditor a. The court may command that the property be released from 4. Independent reivindicatory action the mistaken levy and restored to rightful owner or possessor b. If claimant’s proofs do not persuade, the claim will be deniedThe aforementioned are cumulative remedies and may be resorted to by the courtby a third-party claimant independently of or separately from andwithout need of availing of the others. [Sy v. Discaya (1990)] 3. Note however that the court determination is limited a. Limited only to a determination of whether the sheriff hasFor a Third-Party Claim to be Sufficient: acted rightly or wrongly in performance of his duties 1. Must be filed by a person other than the defendant or his agent, b. The court does not and cannot pass upon the question of at any time before sale title. It can treat of the matter only insofar as may be 2. Must be under oath or supported by affidavit stating the necessary to decide if sheriff acted correctly or not claimant’s title to, or right of possession of, the property, and grounds therefor 3. Must be served upon the officer making levy and a copy thereof TERCERIA upon the judgment creditor Independent of the foregoing, a third-party claimant may also avail ofThe timing of the filing of the claim is important because it determines the remedy of Terceria. Terceria is provided in Sec. 16, Rule 39.the remedies available to the claimant: 1. If the claim is filed under Rule 39, Sec. 16: This is an action for damages by claimant against officer within 120 a. Claimant may vindicate his claim in a separate action days from date of filing of bond for taking or keeping the property b. Intervention is no longer allowed since judgment has already subject of the terceria been rendered Procedure 2. If the claim is filed under Sec. 14, Rule 57 (Attachment) or under 1. Claimant serves on the officer making levy an affidavit of his title Sec. 7, Rule 60 (Replevin) and a copy thereof to judgment creditor a. Claimant may vindicate his claim by intervention as he has a legal interest in the matter of litigation 2. Officer shall not be bound to keep property b. Intervention is allowed as these actions are still pending in court a. Unless judgment creditor, or his agent, on demand of officer, posts indemnity bond not lesser nor greater than value of 3. In such proper action, validity and sufficiency of title of claimant property will be resolved.
3. Where a third-party claim has been filed in due form: 4. A writ of preliminary injunction against sheriff may be issued a. Prevailing party can compel the sheriff to proceed by filing of a bond to answer for damages as a consequence of the execution b. If sheriff proceeds with the sale without such bond, he will be personally liable for such damages as may be sustained by and awarded to the claimant
REINVINDICATORY ACTION
Procedure 1. He must institute an action, distinct and separate from that which the judgment is being enforced, with the court of competent jurisdiction
2. No need to file a claim in the court which issued a writ. The latter is not a condition sine qua non for the former. RULES ON REDEMPTION WHEN CAN REDEMPTION BE MADE (Rule 39, Sec. 28)
He is a creditor with a lien SUBSEQUENT to the judgment which was the REDEMPTION PRICEbasis of the execution sale. 1. By the Judgment Debtor or First Redemptioner:Unlike the judgment debtor, a redemptioner must prove his right to a. Purchase PRICEredeem by producing the documents required in Sec. 30, to wit: b. 1% INTEREST thereon up to time of redemption 1. Copy of the judgment or final order under which he claims the c. Any amount of ASSESSMENTS OR TAXES which purchaser right to redeem certified by the clerk wherein judgment or final may have paid after purchase as well as interest on such last order was entered OR named amount at the same rate 2. If he redeems upon a mortgage or other lien, a memorandum of d. If purchaser is also a creditor having a PRIOR LIEN to that of the record thereof, certified by the Register of Deeds; OR redemptioner, other than the judgment under which such 3. An original or certified copy of any assignment necessary to purchase was made, the AMOUNT of such OTHER LIEN, also establish his claim; OR with interest 4. An affidavit executed by him or his agent showing the amount then actually due on the lien (Sec. 30) 2. By all Subsequent Redemptioners a. AMOUNT paid on last redemptionIf the lien of the creditor is PRIOR to the judgment under which the b. 2% INTEREST thereonproperty was sold: c. Any amount of ASSESSMENTS OR TAXES which purchaser 1. He is not a redemptioner may have paid after purchase as well as interest on such last 2. He cannot redeem since his interests in his lien are fully named amount at the same rate protected. Any purchaser at a public auction takes the same d. Amount of any LIENS held by said last redemptioner prior to subject to such prior lien which he has to satisfy his own, also with interestNOTE: The redemption price for subsequent redemption shall be the 6. Collect rents, earning and income derived from property until thesame, so the price becomes higher and higher. expiration of period of redemption
EFFECT OF REDEMPTION BY THE JUDGMENT OBLIGOR (Rule 39, EXPIRATION OF REDEMPTION PERIOD (Rule 39, Sec. 33)Sec. 29) Judgment obligor shall have the entire period of ONE YEAR from date ofIf Judgment debtor redeems the property: registration of sale to redeem the property 1. No further redemption is allowed 2. He is restored to his estate Entitlement to a CONVEYANCE and POSSESSION: 1. To the PURCHASERWhen a judgment debtor redeems the property, what is effected is the If there is no redemption made within 1 year from date ofelimination of the lien created by the levy on attachment or judgment registration of the certificate of saleon the registration of mortgage thereon. Note that he never lost 2. To the LAST REDEMPTIONERownership so there is no recovery of ownership. If there was redemption, and 60 days have elapsed and no other redemption has been madePayments mentioned in Sec. 28 and 29 may be made to the: Notice must have been given, and the redemption period has 1. Purchaser, or elapsed 2. Redemptioner, or 3. For him to the officer who made the sale Two Documents which the Sheriff Executes in case of Real Property 1. CERTIFICATE OF SALEThe person to whom redemption payment is made must execute and After auction sale, he will execute in favor of the purchaserdeliver to him a CERTIFICATE OF REDEMPTION the certificate of sale under Sec. 25 1. Acknowledged by a notary public or other officer authorized to From registration of said certificate, the one year redemption take acknowledgements of conveyances of real property 2. Filed and recorded in the registry of deeds of the place which the period starts property is situated Certificate of sale after execution sale is merely a memorial 3. Registrar must note the record on the margin of the record of the of the fact of sale and does not operate as conveyance certificate of sale 2. DEED OF CONVEYANCE Issued if after expiration of redemption period there is noRIGHTS PENDING REDEMPTION (Rule 39, Sec. 31 and 32) redemption Operates to transfer to purchaser whatever rights theRight of Judgment Creditor Pending Redemption judgment debtor had in the property 1. Apply for injunction to restrain the commission of waste on the The effect of a final deed of sale transfers the right as of the property time of the levy
NATURE EFFECT Judgment is In judgments against a CONCLUSIVE upon the specific thing (in rem) title to the thing In judgments against a Judgment is person (in personam) PRESUMPTIVE evidence of a right as between parties and their successors-in-interest A foreign judgment is presumed to be valid and binding in the country by a subsequent title from which it comes, until a contrary showing, on the basis of a presumption of regularity of proceedings and the giving of due notice inIn both cases, judgment may be repelled by evidence of: the foreign forum. 1. Want of jurisdiction 2. Want of notice Before our courts can give the effect of res judicata to a foreign 3. Collusion judgment, it must be shown that the parties opposed to the judgment 4. Fraud had been given ample opportunity to do so on grounds under Section 5. Clear mistake of law or fact 48 of Rule 39 of the Rules of Court. [Roehr v. Rodriguez (2003)]
Provisional remedies are writs and processes available during the Inferior courts may also grant all appropriate provisional remedies in anpendency of the action which may be resorted to by a litigant for the action pending with it and is within its jurisdiction (Sec. 33, (1), BP 129)preservation or protection of their rights and interests therein pendingrendition, and for purposes of the ultimate effects, of a final judgment inthe case; also known as ancillary or auxiliary remedies.
They are applied to a pending litigation, for the purpose of securing thejudgment or preserving the status quo, and in some cases afterjudgment, for the purpose of preserving or disposing of the subjectmatter. [Calo v. Roldan (1946)]
Issuance of the Order of Attachment The bond shall only be applied to all damages sustained due to the 1. The order may be issued either: attachment. It cannot answer for those that do not arise by reason of a. Ex parte (service of summons to defendant required) the attachment [Riano]. b. Or upon motion with notice and hearing 2. The order is issued by the court in which the action is pending or the CA, or the SC THE RULE ON PROR OR CONTEMPORANEOUS SERVICE OF SUMMONSContents of the Order of Attachment: 1. It must require the sheriff to attach so much of the property of General Rule: A writ of attachment may be issued ex parte even before the party against whom it is issued as may be sufficient to the summons is served upon the defendant. BUT a writ may not be satisfy applicant’s demand implemented until jurisdiction over the person is acquired by service of a. Property must be within the Philippines summons. Otherwise, the implementation is null and void. [Riano]Exceptions to Contemporaneous Service of Summons: [Rule 57, Sec. 5] 4. Debts, credits, bank deposits, financial interest, royalties, 1. Summons could not be served personally or by substituted commissions and other personal property not capable of manual service despite diligent efforts, or delivery 2. Defendant is a resident of the Philippines temporarily absent 1. Leave a copy of the writ and a notice that the debts owing, therefrom, or credits, and other personal property are attached in 3. Defendant is a non-resident, or pursuance of such writ 4. The action is in rem or quasi in rem. 2. Leave these documents with: a. The person owing such debts, or b. Having in his possession or under his control, such creditsMANNER OF ATTACHING PROPERTY (Rule 57, Sec. 5) or other personal property, or c. With his agentThe sheriff enforcing the writ shall attach only so much of the propertyin the Philippines of the adverse party not exempt from execution as 5. The interest of the party against whom attachment is issued inmay be sufficient to satisfy the applicant’s demand, UNLESS property belonging to the estate of decedent, whether as heir, 1. Party against whom writ is issued makes a deposit with the court legatee, or devisee from which the writ is issued, or a. By service of a copy of the writ, and notice that said interest 2. He gives a counter-bond executed to the applicant is attached b. Service is made to: (1) The executor, or administrator, orATTACHMENT OF REAL AND PERSONAL PROPERTY (Rule 57, Sec. (2) Other personal representative of the decedent7) c. Copy of the writ and notice: (1) Shall be filed with the clerk in which said estate is being 1. Real property, or growing crops thereon, or any interest therein settled, and a. File with the Registry of Deeds: (2) Served upon the heir, legatee, or devisee concerned (1) A copy of the order together with a description of the property Property in custodia legis may be attached by: (2) And a notice that the property is attached 1. Filing a copy of the writ of attachment with the proper court or b. The registrar of deeds must index attachments in the names quasi-judicial agency of the applicant, adverse party, or person by whom the 2. Serving a notice of attachment upon the custodian of the property is held or in whose name it stands in the records property [Rule 57, Sec. 7] c. If attachment is not claimed on the entire area of land, description sufficiently accurate for identification of such A previously attached property may also be subsequently attached. But shall be included in the registration the first attachment shall have priority over subsequent attachments. [Riano] 2. Personal property capable of manual delivery a. Issue a corresponding receipt therefor b. Then sheriff takes it and safely keeps it in his custody PROCEEDINGS WHERE ATTACHED PROPERTY IS CLAIMED BY THIRD PERSON 3. Stocks or Shares, or an Interest therein, of any corporation or company A third person who has a claim to the property attached may avail of a. Leave a copy of the writ and a notice stating that these the following remedies: properties are attached in pursuance of such writ b. Leave these documents with the president, or managing 1. File terceria or third-party claim (Rule 57, Sec. 14) agent thereof a. Note that a third-party claim may be filed with the sheriff Only the defendant or party whose property is attached may move for while has possession of the properties levied upon, this being its lifting. If the attachment is proper, the discharge should be by the only time fixed for the purpose counterbond under Sec. 12 (KO Glass v. Valenzuela) b. The claimant makes an affidavit of his title or right to possession, stating the grounds of such right or title. The Effect of Dissolution on Plaintiff’s Attachment Bond affidavit must be served upon the sheriff 1. Dissolution of preliminary attachment upon security given, or a c. Substantial identical procedure as in terceria in Rule 39, Sec. showing if its irregular issuance, does not operate to discharge 16 the sureties on the attachment bond 2. That bond is executed to adverse party conditioned that the 2. File independent action to recover property; or applicant will pay all the costs which may be adjudged to adverse party and all damages which he may sustain by reason 3. File motion for intervention of the attachment, if the court shall finally adjudge that a. This is available only before judgment is rendered applicant was not entitled thereto (Sec. 4) 3. Until that determination is made, as to applicant’s entitlement to attachment, his bond must stand and cannot be withdrawnDISCHARGE OF ATTACHMENT AND COUNTER-BOND
After a writ of attachment has been enforced, the party whose property SATISFACTION OF JUDGMENT OUT OF PROPERTY ATTACHED (Rulehas been attached, or the person appearing on his behalf, may move 57, Sec. 15)for the discharge of the attachment wholly or in part on the securitygiven. Procedure: 1. Pay to judgment obligee the proceeds of sale of perishableWays of Discharging Attachment property 1. Counterbond under Sec. 12 2. If there is any balance that remains due, sell property as may be 2. Motion for Discharge under Sec. 13 necessary to satisfy the balance if enough remains in the sheriff or those of the clerkGrounds for Discharge of Preliminary Attachment: 3. Collection of property of garnishee and proceeds paid to 1. Debtor has posted a counterbond or has made the requisite cash judgment oblige without need of prior permission to file action deposit (Sec. 12) but may be enforced in the same action 2. Attachment was improperly or irregularly issued (Sec. 13) 4. Return must be made within 10 days from receipt of writ a. As where there was no ground for attachment, or b. The affidavit and/or bond filed are defective or insufficient (Sec. 3) 3. Judgment is rendered against attaching creditor (Sec. 19) 4. Attachment is excessive, but the discharge shall be limited to the excess (Sec. 13) 5. Property attached is exempt from execution
NOTE: There is a difference between the bond for issuance of writ andbond for lifting the writ 1. Bond for issuance of writ (Sec. 4) – This is for damages by reason of the issuance of the writ 2. Bond for lifting of writ (Sec. 5 and 12) – This is to secure the payment of the judgment to be recovered PRELIMINARY INJUNCTION Same requirements for application as preliminary injunction.
DEFINITIONS AND DIFFERENCES An application for a TRO shall be acted upon only after all parties are heard in a summary hearing, which shall be conducted within 24 hoursInjunction is a judicial writ, process, or proceeding whereby a party is after the sheriff's return of service and/or the records are received byordered to do or refrain from doing a particular act the branch selected by raffle. [Rule 58, Sec.4
The injunction should not establish new relations between the parties REQUISITES:but merely re-establish the pre-existing relationship between them. 1. There must be a verified application 2. The applicant must establish that:TRO v. Injunction a. He has a right to relief or a right to be protected and b. The act against which the injunction is sought violates such right c. There is a need to restrain the commission or continuance of TRO Injunction the acts complained of and if not enjoined would work injustice to himMay be granted ex parte if great Cannot be granted without notice 3. A bond must be posted unless otherwise exempted by the court and irreparable injury would and hearing 4. The threatened injury must be incapable of pecuniary estimation result otherwise 5. Prior notice and hearing for party/person sought to enjoined (except in 72-hour TROs)A TRO is issued in order to preserve the status quo until the hearing ofthe application for preliminary injunction. [Bacolod City Water v.Labayen (2004)]KINDS OF INJUNCTION 1. To compel cohabitation [Arroyo v. Vasquez (1921)] 2. Cancellation of attachment [Levy Hermanos v. Lacson (1940)]Kinds of Injunction: 3. Release imported goods pending hearing before the 1. Preliminary Preventive Injunction – Prohibits the performance of Commissioner of Customs. [Commissioner of Customs v. Cloribel a particular act or acts (1967)] 4. To take property out of the possession or control of one party 2. Preliminary Mandatory Injunction – Requires the performance of and place it into that of another whose title has not clearly been a particular act or acts. This is an extreme remedy which will be established [Pio v. Marcos (1974)] granted only on showing that: a. The invasion of the right is material and substantial b. Right of complainant is clear and unmistakable WHEN WRIT MAY BE ISSUED c. There is an urgent and paramount necessity When: It may be issued at ANY stage PRIOR to the judgment or final PRELIMINARY PRELIMINARY order PROHIBITORY MANDATORY INJUNCTION INJUNCTION Who: It may be granted by the court where the action or proceeding is Purpose is to prevent pending. If the action or proceeding is pending in the Court of Appeals Purpose is to require a or in the Supreme Court, it may be issued by said court or any member a person from the person to perform a thereof. (Rule 58, Sec. 2) performance of a particular act particular act The act has already The act had not yet been performed and GROUNDS FOR THE ISSUANCE OF PRELIMINARY INJUNCTION been performed this act has violated (Rule 58, Sec. 3) the rights of another Status Quo is Preliminary injunction may be granted when it is established that: Status Quo is restored 1. Applicant is entitled to the relief demanded, or preserved 2. Commission, continuance, or non-performance of the actWhen preventive injunction does not lie; examples: complained of would work injustice to applicant, or 1. To restrain collection of taxes [Valley Trading v. CA](1989), 3. Party, court, agency or a person is doing, threatening, or is except where there are special circumstances that bear the attempting to do, or is procuring or suffering to be done, some existence of irreparable injury. [Churchill & Tait v. Rafferty act or acts probably in violation of the rights of the applicant (1915)] respecting the subject of the action or proceeding 2. To restrain the sale of conjugal properties where the claim can be annotated on the title as a lien, such as the husband’s obligation to give support. [Saavedra v. Estrada (1931)] GROUNDS FOR OBJECTION TO, OR FOR MOTION OF DISSOLUTION 3. To restrain a mayor proclaimed as duly elected from assuming OF, INJUNCTION OR RESTRAINING ORDR (Rule 58, Sec. 6) his office. [Cereno v. Dictado (1988)] 4. To restrain registered owners of the property from selling, Grounds for objection or dissolution disposing and encumbering their property just because the 1. Upon showing of its insufficiency respondents had executed Deeds of Assignment in favor of petitioner. [Tayag v. Lacson (2004)] 2. Other grounds upon affidavits of the party or person enjoined. 5. Against consummated acts. [PNB v. Adi (1982); Rivera v. This may be opposed by the applicant by affidavits Florendo (1986); Ramos, Sr. v. CA (1989)] 3. If it appears after hearing that although applicant is entitled toWhen mandatory injunction does not lie; examples injunction or TRO, the issuance or continuance thereof, would cause irreparable damage to party enjoined while applicant can be fully compensated for such damages as he may suffer 2. If the matter is of extreme urgency and the applicant will suffer a. PROVIDED that he files a bond grave injustice and irreparable injury (1) Amount to be fixed by the court a. A TRO may be issued ex parte (after raffling of case) ordered (2) Conditioned that he will pay all damages which the by the Executive judge of a multiple sala court or the applicant may suffer by denial or dissolution of the presiding judge of a single-sala court injunction or TRO b. Effective for 72 hours from issuance (1) The applicant must then immediately comply with Sec. 4If it appears that the extent of the preliminary injunction or restraining as to service of summons and documentsorder granted is too great, it may be modified. (2) The Executive Judge shall then summon the parties to a conference and raffle the case in their presence
This prohibition shall NOT APPLY when the matter is of extreme urgencyinvolving a constitutional issue, such that unless a temporaryrestraining order is issued, grave injustice and irreparable injury willarise. The applicant shall file a bond, in an amount to be fixed by thecourt, which bond shall accrue in favor of the government if the courtshould finally decide that the applicant was not entitled to the reliefsought.
1. When it appears from the verified application and other proof REQUISITES; REQUIREMENTS BEFORE ISSUANCE OF AN ORDER that the applicant has an interest in the property or fund which is the subject of the action or proceeding, and that such property Procedure: or fund is in danger of being lost, removed, or materially injured 1. Verified application filed by the party requesting for the unless a receiver be appointed to administer and preserve it; appointment of the receiver; 2. Applicant must have an interest in the property or funds subject 2. When it appears in an action by the mortgagee for the of the action; foreclosure of a mortgage that the property is in danger of being 3. Applicant must show that the property or funds is in danger of wasted or dissipated or materially injured, and that its value is being lost, wasted, or dissipated; probably insufficient to discharge the mortgage debt, or that the 4. Application must be with notice and must be set for hearing; parties have so stipulated in the contract of mortgage; 5. Before appointing a receiver, the court shall require applicant to post a bond in favor of the adverse party. When the receiver is 3. After judgment, to preserve the property during the pendency of appointed, the receiver shall file a bond then take his oath. an appeal, or to dispose of it according to the judgment, or to aid 6. Before entering upon his duties, the receiver must be sworn to execution when the execution has been returned unsatisfied or perform his duties faithfully. 10. Invest funds in his hands, ONLY by order of the court upon theWho Appoints Receiver: written consent of all the parties. [Rule 59, Sec. 6] 1. Court where the action is pending 2. CA Liability for refusal or neglect to deliver property to receiver: 3. SC 1. Contempt; and 4. During the pendency of an appeal, the appellate court may allow 2. Be liable to the receiver for the money or the value of the an application for the appointment of a receiver to be filed in property and other things so refused or neglected to be and decided by the court of origin. [Rule 59, Sec. 1] surrendered together with all damages that may have been sustained by the party or parties entitled thereto as aReceivership may be denied or lifted: consequence of such refusal or neglect. [Rule 59, Sec. 7] 1. If the appointment was sought or granted without sufficient cause (Sec. 3) Remedies Against the Receiver 2. Adverse party files a sufficient bond to answer for damages (Sec. 1. No action against receiver can be maintained without leave of 3) court 3. Bond posted by applicant for grant of receivership is insufficient 2. An aggrieved party may: (Sec. 5) a. Take the matter into the court which appointed the receiver 4. Bond of the receiver is insufficient (Sec. 5) and ask either for an accounting or take some other proceeding, and ask for consequent judgment on the acts complained of; orTHE RECEIVER b. Ask for leave of court to bring him an action directly
WHEN MAY WRIT BE ISSUED NOTE: The writ of replevin may be served anywhere in the Philippines.
Return of Property (Sec. 5) However, the rule requires that upon such order, the sheriff must serve 1. If the adverse party objects to the sufficiency of the bond, he a copy on the adverse party together with the required documents. cannot immediately require the return of the property even by counterbond. A sheriff’s prerogative does not give him the liberty to determine who among the parties is entitled to possession. 2. If the adverse party DOES NOT object to the sufficiency of the bond, he may require the return of the property When a writ is placed in the hands of a sheriff, it is his duty to proceed a. When: At any time before delivery to applicant with reasonable celerity and promptness to execute it according to its b. How: By filing a redelivery bond mandate.
1. Serve a copy of the order, together with the copies of the NOTE: These remedies are alternative. application, the affidavit, and bond to the adverse party
No claim for damages for the taking or keeping of the property may be After trial of the issues, the court shall determine who has the right ofenforced against the bond UNLESS the action is filed within 120 days possession to and the value of the property and shall render judgmentfrom filing of the bond. in the alternative for the delivery thereof to the party entitled to the same, or for its value in case delivery cannot be made, and also forThe procedure in Rule 60, Sec. 7 is similar to that in third-party claims in such damages as either party may prove, with costs.execution (Sec. 16, Rule 39) and in attachment (Sec. 14, Rule 57). A COMPARATIVE CHART ON THE PROVISIONAL REMEDIES Preliminary Attachment Preliminary Injunction Receivership Replevin To have the property of adverse party attached as security for To require a party or a court, satisfaction of judgment that may agency, or a person to reframe be recovered in cases falling from doing a particular act/s To place the property subject of under Sec. 1, Rule 57 an auction or proceeding under To enable the court to acquire the control of a third party for its To recover possession of personal PURPOSE jurisdiction over the action by the preservation and administration property actual or constructive seizure of pendente lite or as an aid to Or to require the performance of the property in those instances execution particular act/s where personal service of summons on creditor cannot be effected SUBJECT Personal property capable of Personal or real property Particular act/s Personal or real property MATTER manual delivery At any time prior to satisfaction of WHEN At the commencement of action judgment At the commencement of the At any stage prior to final APPLIED/ OR `At any time prior to entry of It may be availed of even after action judgment or final order GRANTED judgment judgment becomes final under BUT before the filing of answer Sec. 41, Rule 39 File verified application and File verified application and applicant’s bond applicant’s bond If application is included inHOW APPLIED File affidavits and applicant’s File affidavits and applicant’s initiatory pleading, adverse party Application may also be included FOR bond bond should be served with summons in initiatory pleading in actions for together with a copy of initiatory foreclosure of mortgage pleading and applicant’s bond Required EXCEPT: Great or irreparable injury wouldREQUIREMENT Not required Not Required result or Extreme urgency and RequiredOF A HEARING May be issued ex parte May be issued ex parte applicant will suffer grave injustice and irreparable injury (Sec. 5, Rule 58 Only the court where the action is Court where action is pending pending The CA or SC even if action is Courts where the action is Lower court, CA or SC provided WHO MAY pending in the lower court Only the court were action is pending, the CA or the SC even if action is pending in the same GRANT Appellate court may allow pending action is pending in lower court court which issues the injunction application for receivership to be Also with the Sandiganbayan and decided by the court of origin CTA REQUISITES 1. Sufficient cause of action 1. Applicant is entitled to relief 1. Applicant has interest in 1. Applicant is owner of theFOR GRANTING 2. Case is covered by Sec. 1, Rule demanded property or fund, subject property claimed or is APPLICATION 57 2. Act/s complained of would matter of action entitled to possession 3. No other sufficient security for work injustice to applicant if 2. Property or fund is in danger 2. Property is wrongfully the claim exists not enjoined of being lost, or removed, or detained by the adverse party 4. Amount due to applicant or 3. Acts sought to be enjoined material injured 3. Property is not distrained or probably violates applicant’s 3. Appointment is the most value of property he is entitled taken for tax assessment or rights respecting the subject convenient and feasible to recover is equal to the sum fine pursuant to law, or seized of the action or proceeding means of preserving, which the order of attachment (if seized, that the property is 4. Threatened injury incapable of administering, disposing of is granted exempt) pecuniary estimation property in litigation
WHEN TO FILE
PROCEDURE
1. A complaint is filed.
6. Pre-trial is conducted. DECLARATORY RELIEFS AND SIMILAR REMEDIES 2. If action involves the validity of a statute/executive order/regulation/other governmental regulation, the SolicitorNATURE General shall be notified. [Rule 63, Sec. 3] 3. If action involves the validity of a local government ordinance,In Declaratory Relief, the subject matter is a deed, will, contract, or the prosecutor/attorney of the LGU involved shall be notified.other written instrument, statute, executive order, or regulation, or [Rule 63, Sec. 4]ordinance; Non-joinder of interested persons is not a jurisdictional defect; but Note: The enumeration of the subject matter is EXCLUSIVE persons not joined shall not be prejudiced in their interests unless otherwise provided by the Rules. (Baguio Citizens Action v. City CouncilIssue is the validity or construction of the subject matter of Baguio, 1983)
Purpose: To relieve the litigants of the common law rule that no It is filed In the appropriate RTC (incapable of pecuniary estimation)declaration of rights may be judicially adjudged unless a right has beenviolated and for the violation of which relief may be granted. Original jurisdiction of a petition for declaratory relief is with the RTC.
Characteristics 1. The concept of a cause of action is not applicable to declaratory REQUISITES OF ACTION FOR DECLARATORY RELIEF relief since this SCA presupposes that there has been no breach or violation of the 1. Subject matter of controversy must be a deed, will, contract, or 2. instruments involved other written instrument, statute, executive order or regulation, 3. Unlike other judgments, judgment in an action for declaratory or ordinance. (Enumeration is exclusive) relief does not essentially entail any execution process 2. Actual justiciable controversy or “ripening seeds” of one between person whose interests are adverseWHO MAY FILE THE ACTION (Rule 63, Sec. 1) 3. No breach of documents in question 1. Any person interested under a deed, will, contract or other written instrument 4. Doubtful as to the terms and validity of the document and a. He must file before breach require judicial construction
2. Any person whose rights are affected by a statute, executive 5. Issue is ripe for judicial determination, as where all order or regulation, or ordinance, or any other governmental administrative remedies have been exhausted regulation a. He must file before violation 6. Adequate relief is not available through other means or other forms of action or proceeding
PARTIES WHEN COURT MAY REFUSE TO MAKE JUDICIAL DECLARATION 1. All persons who have or claim any interest which would be affected by the declaration [Rule 63, Sec. 2] Court has DISCRETION to REFUSE to Grant Declaratory Relief when: (Rule 63, Sec. 5) 1. The decision will not terminate the controversy or uncertainty REVIEW OF JUDGMENTS AND FINAL ORDERS OR giving rise to the action; or RESOLUTION OF THE COMELEC AND COA 2. The declaration or constitution is not necessary and proper under the circumstances SCOPE (Rule 64, Sec. 1)How Done: Motu proprio, or on motion Applicable only to judgments and final orders of the COMELEC and COA [Rule 64, Sec. 1]CONVERSION TO ORDINARY ACTION (Rule 63, Sec. 6) Judgments/orders of the Civil Service Commission are now reviewableWhen proper: If before the final termination of the case, a breach or by the Court of Appeals under Rule 43, eliminating recourse to theviolation of the instrument or status occurs. Then, petition is converted Supreme Court (SC). [RA 7902; SC Revised Administrative Circular No.into an ordinary action 1-95]Effect of Conversion: Parties shall be allowed to file such pleadings as An aggrieved party may bring the questioned judgment, etc. directly tomay be necessary or proper the SC on certiorari under Rule 65. [Rule 64, Sec. 2]NOTE: If there has been breach or violation BEFORE filing of the Basis: This new rule is based on the provisions of Art. IX-A, 1987petition, declaratory relief cannot be availed of. Constitution regarding the three constitutional commissions provided for therein.PROCEEDINGS CONSIDERED AS SIMILAR REMEDIES
Actions similar to Declaratory Relief and may be brought under Rule 63: APPLICATION OF RULE 65 UNDER RULE 64(may be filed with the MTC) 1. Action for reformation (See Art. 1359-1369 Civil Code) The aggrieved party may bring a judgment or final order or resolution of 2. Action to quiet title or remove cloud (See Art. 476-481 Civil the COMELEC and COA to the SC on certiorari under Rule 65 and not on Code) appeal by certiorari under Rule 45 3. Action to consolidate ownership (See Art. 1607 Civil Code) NOTE: The petition should be filed EXCLUSIVELY with the SCThese remedies are considered similar to declaratory relief becausethey also result in the adjudication of the legal rights of the litigants Unlike in Rule 65, petition should be filed within 30 days from notice ofoften without the need of execution to carry the judgment into effect judgment or final order or resolution sought to be reviewed.However we must make a distinction: Filing of MFR or MNT, if allowed under the procedural rules of the 1. In those cases similar to declaratory relief, the court is BOUND to Commission, shall interrupt the 30-day period. render judgment 2. In actions for declaratory relief, the court MAY REFUSE to If denied, aggrieved party may file petition within the remaining period exercise the power to declare rights and to construe instruments but it shall not be less than 5 days in any event from notice of denial.
PROCEDURE
Questions of fact cannot be raised in an original action for certiorari. A writ of mandamus will not issue to control the exercise of officialOnly established or admitted facts may be considered. (Suarez, NLRC, discretion or judgment, or to alter or review the action taken in the1998) proper exercise of the discretion of judgment, for the writ cannot be used as a writ of error or other mode of direct review.Where appeal is available, certiorari will not lie. Exceptions: 1. Where the appeal does not constitute a speedy and adequate However, in extreme situations generally in criminal cases, mandamus remedy lies to compel the performance of the fiscal of discretionary functions 2. Where orders were also issued either in excess or without where his actuations are tantamount to a wilful refusal to perform a jurisdiction required duty. [Regalado] 3. For certain special considerations, as public welfare or public policy Grounds for Mandamus: 4. Where, in criminal actions, the court rejects the rebuttal 1. When any tribunal, corporation, board, officer or person, evidence for the prosecution as, in case of acquittal, there could UNLAWFULLY NEGLECTS the performance of an act which the law be no remedy specifically enjoins as a duty resulting from an office, trust, or 5. Where the order is a patent nullity station 6. Where the decision in the certiorari case will avoid future 2. When any tribunal, corporation, board, officer, or person, litigations UNLAWFULLY EXCLUDES another from the due and enjoyment of a right or office to which the other is entitled
Such order shall be served on the respondents in such manner Rule 65, Sec. 7 provides for the issuance of a temporary restraining as the court may direct, together with a copy of the petition and order, and not only for a writ of preliminary injunction, but such order any annexes thereto. [Rule 65, Sec. 6] shall be subject to the rules on the grounds and duration thereof. [Regalado] 3. Hearing or Memoranda - After the comment or other pleadings required by the court are filed, or the time for the filing thereof General Rule: The petition shall not interrupt the course of the principal has expired, the court may hear the case or require the parties case. to submit memoranda. [Rule 65, Sec. 8] The public respondent shall proceed with the principal case WITHIN 10 4. Judgment - If after such hearing or submission of memoranda or DAYS from filing of the petition for certiorari with the higher court, the expiration of the period for the filing thereof, the court finds absent a TRO or preliminary injunction, or upon its expiration. Failure that the allegations of the petition are true, it shall render may be a ground for an administrative charge (AM No. 07-7-12-SC) judgment for the relief prayed for or to which the petitioner is entitled. Exception: Unless a TRO or preliminary injunction has been issued against the public respondent from further proceedings in the case The court, however, may dismiss the petition if it finds the same to be: a. Patently without merit, FACTS/OMISSIONS OF MTC/RTC IN ELECTION CASES b. Prosecuted manifestly for delay, or c. The questions raised therein are too unsubstantial to require In election cases involving an act or an omission of a municipal or consideration. [Rule 65, Sec. 8] regional trial court, the petition shall be filed EXCLUSIVELY with the Commission on Elections, in aid of its appellate jurisdiction (Rule 65, 5. Service and Enforcement of Order or Judgment - A certified copy Sec. 4, as amended in AM No. 07-7-12-SC) of the judgment rendered shall be served upon the court, quasi- judicial agency, tribunal, corporation, board, officer or person concerned in such manner as the court may direct, and EFFECTS OF FILING AN UNMERITORIOUS PETITION disobedience thereto shall be punished as contempt. The court, however, may dismiss the petition if it finds the same to be patently without merit, prosecuted manifestly for delay, or that theRELIEFS PETITIONER IS ENTITLED TO questions raised therein are too unsubstantial to require consideration. (Rule 65, Sec. 8)Petitioner may be entitled to: 1. Injunctive relief – Court may may issue orders expediting the In these cases, the court may award TREBLE COSTS solidarily against proceedings, and it may also grant a temporary restraining order petitioner and counsel, in addition to administrative sanctions or a writ of preliminary injunction for the preservation of the rights of the parties [Rule 65, Sec. 7] Court may impose, motu proprio, based on res ipsa loquitur, other 2. Incidental reliefs as law and justice may require [Rule 65, Secs. 1 disciplinary sanctions for patently dilatory and unmeritorious petitions and 2] (AM No. 07-7-12-SC) 3. Other reliefs prayed for or to which the petitioner is entitled [Rule 65, Sec. 8] QUO WARRANTO NATUREQuo Warranto literally means “by what authority”. public office, position or franchise;
It is a prerogative writ by which the government can call upon any A public officer, who does or suffersperson to show by what warrant he holds a public office or exercises a an act which, by provision of law,public franchise. constitutes a ground for forfeiture of officeWhen the inquiry is focused on the legal existence of a body politic, theaction is reserved to the State in a proceeding for quo warranto or any In fine, Rule 66 applies to quo warranto IN GENERAL while election lawother direct proceeding. governs quo warranto against SPECIFIED elective officials.
Subject Matter: The subject matter of a quo warranto may be a public AGAINST WHOM MAY THE ACTION BE BROUGHT (Rule 66, Sec. 1)office, franchise, or position. 1. A PERSON who USURPS, intrudes into, or unlawfully holds or NOTE: NOTE: Rule 66 deleted an office in a corporation created exercises a public office, position, or franchise by authority of law. This falls under the jurisdiction of the SEC 2. A PUBLIC OFFICER who does or suffers an act, which, by under PD 902-A. provision of law, constitutes a ground for FORFEITURE OF OFFICE 3. An ASSOCIATION which acts as a corporation within theJurisdiction to Issue Writ: Original jurisdiction to issue the writ of quo Philippines without being legally incorporated or without lawfulwarranto is vested in the SC, CA, and RTC. authority to act
Period to File: The action must be commenced within 1 year from thedate after the cause of such ouster or the right of the petitioner to holdsuch office or position arose. (Sec. 11)
Reduction of Period: The court may reduce the period for filing and forall other proceedings in the action to secure most expeditiousdetermination of the matters involved therein, consistent with the rightsof the parties.
Eminent Domain is the right and authority of the State, as sovereign, to TWO STAGES IN EVERY ACTION FOR EXPROPRIATIONtake private property for public use upon observance of due processand payment of just compensation. First Stage: Determination of the authority of the plaintiff to exercise the power of eminent domain and the propriety of its exercise in theIt is a government’s right to appropriate, in the nature of a compulsory context of the facts involved. This ends with either:sale to the State, private property for public use or purpose. 1. An order of dismissal, or 2. An order of expropriationRequisites for the Valid Exercise of the Right 1. There must be due process of law Second Stage: Determination of the just compensation for the property 2. Payment of just compensation sought to be taken. 3. Taking must be for public use NOTE: Multiple appeals is allowed in expropriation. Aggrieved party maySubject Matter of Expropriation: All properties can be expropriated, appeal in each stage separately.EXCEPT: 1. Money (futile; because of just compensation) 2. Choses in action (conjectural in nature; validity and its value) WHEN PLAINTIFF CAN IMMEDIATELY ENTER INTO POSSESSION OF THE REAL PROPERTY, IN RELATION TO R.A. NO. 8974When is Expropriation Proper: 1. When the owner refuses to sell Plaintiff shall have the right to take or enter upon possession of the real 2. When he agrees to sell but an agreement as to the price cannot property upon: be reached. 1. Filing of complaint or at any time thereafter, and after due notice to defendant 4. Making preliminary deposit (Rule 67, Sec. 2)MATTERS TO ALLEGE IN COMPLAINT FOR EXPROPRIATION Preliminary deposit:Contents of the Complaint (Rule 67, Sec. 1) 1. State with certainty the right and purpose of expropriation Provide damages if court finds that a. Where the right of the plaintiff to expropriate is conferred by the plaintiff has no right to law, complaint does not have to state with certainty the right expropriate of expropriation (MRR Co. v. Mitchel) Purpose 2. Describe the real or personal property sought to be expropriated s Advance payment for just 3. Joining of defendants compensation, if property is finally a. All persons owning or claiming to own, or occupying, any part expropriated thereof or interest therein. showing separate interest of each defendant, as far as practicable If Real Property - Equivalent to the b. Make the following averments, if needed: assessed value of the property for (1) If title appears to be in the Republic, although occupied purposes of taxation Value by private individuals If Personal Property – Value shall be (2) If title is otherwise obscure or doubtful so that plaintiff provisionally ascertained and fixed by cannot with accuracy or certainty specify who the real the court owners are Where With the authorized government depositary required to immediate to Amount is to be held by such bank make payment to ownerdeposit TO ISSUE subject to the orders of the court preliminary upon filing of Deposit shall be in money deposit complaint Equal to the UNLESS, in lieu of money, court market value ofForm of authorizes deposit of a certificate of the property asDeposit deposit of a government bank of the Equal to stated in the tax Republic, payable on demand to the assessed declaration or authorized government depositary AMOUNT OF value of current relevant PAYMENT OR real zonal value of BIR,After the deposit, court shall order sheriff or proper officer to place DEPOSIT property for whichever isplaintiff in possession of the property. Such officer shall promptly submit purposes of higher, and valuea report to the court with service of copies to parties. taxation of improvements and/or structuresNOTE: Preliminary deposit is only necessary if the plaintiff desires entry using replacementon the land upon its institution of the action. Otherwise, he could always cost methodwait until the order of expropriation is issued before it enters upon theland. Remember the Applicable Rules: 1. RA 8974 specifically governs expropriation for nationalOnce the preliminary deposit has been made, the expropriator is government infrastructure projectsentitled to a writ of possession as a matter of right, and the issuance of 2. Sec 19, LGC governs the exercise of the power of eminentsaid writ becomes ministerial on the part of the trial court (Biglang-Awa domain by LGUs through an enabling ordinancev. Bacalla)
On Nov. 7, 2000, Congress enacted RA 8974, a special law to facilitate For the acquisition of right-of-way, site or location for any nationalthe acquisition of right of way, site, or location for national government government infrastructure project through expropriation, upon the filinginfrastructure projects: of the filing of the complaint, and after due notice to the defendant, the implementing agency shall immediately pay the owner of the property RULE 67, the amount equivalent to the sum of (1) 100 percent of the value of the RA 8974 SEC. 2 property based on the current relevant zonal valuation of the BIR; and Only when (2) the value of the improvements and/or structures as determined national under Sec. 7 of RA 8974 (Sec. 4, RA 8974) government Expropriati expropriates APPLICATION on in property for DEFENSES AND OBJECTIONS general national government No Objection Or Defense To The Has Objection Or Defense To infrastructure Taking The Taking projects What to file and serve FOR WRIT OF Governmen Government is POSSESSION t is required to make Notice of appearance and 2. No party appears to defend the case Answer to the complaint manifestation Contents of the Order: Period to file 1. That the plaintiff has a lawful right to take the property sought to Time stated in the summons be expropriated Contents 2. For public use or purpose described in the complaint Specifically 3. Upon payment of just compensation designating/identifying the a. To be determined as of the date of taking, or Manifestation to the effect that property in which he claims to b. The filing of the complaint, whichever came first he has no objection or defense; have an interest in and the nature and extent of the Remedy of Defendant: Order of condemnation is final, not interlocutory. Specifically interest; Hence, it is appealable. designating/identifying theproperty in which he claims to be ALL his objections and defenses Effects of the Order: interested to the complaint or any 1. Plaintiff not permitted to dismiss or discontinue the proceeding allegation therein a. EXCEPTION: On such terms as the court deems just and Prohibited equitable, plaintiff may be allowed to dismiss or discontinue 2. Forecloses any further objections to the right to expropriate, Counterclaim, cross-claim, third including the public purpose of the same party complaint in any pleading
NOTE: A defendant waives all defenses and objections not so alleged, ASCERTAINMENT OF JUST COMPENSATION (Rule 67, Sec. 5)but the court, in the interest of justice, may permit amendments to theanswer not to be made later than ten (10) days from filing thereof. Upon rendition of the Order of Expropriation, the court issues an Order of Appointment.NOTE: In any case, in the determination of just compensation,defendant may present evidence as to the amount of compensation to Order of Appointment:be paid. 1. Court appoints not more than 3 commissioners to ascertain and report to the court the just compensation for the propertyNOTE: The defendant CANNOT be declared in default for failure to fileAnswer. Failure to file an answer would result to the court’s judgment on 2. Contents:the right to expropriate without prejudice to the right to present a. It shall designate the time and place of the first session ofevidence on the just compensation and to share in the distribution of hearing to be held by commissionerthe award. b. Specify the time within which their report shall be submitted to courtORDER OF EXPROPRIATION (Rule 67, Sec. 4) 3. Procedures: a. Copies of the Order shall be served on the partiesOrder of Expropriation - It is the order declaring that the plaintiff has b. Objections to appointment:lawful right to take the property. (1) Filed with the court within 10 days from service (2) Objections shall be served to all commissionersWhen Issued: It is issued when: (3) Resolved within 30 days after all commissioners shall 1. Objections or defenses again | https://fr.scribd.com/document/385800531/Civil-Procedure-Reviewer | CC-MAIN-2019-39 | refinedweb | 31,318 | 51.99 |
K.
The code is available here.
Extensions in Kotlin
There are many types of extensions in Kotlin. I decided to focus only on extension functions and properties.
As an example, I extend the
java.lang.String class. First, I create an extension function,
skipFirst, which skips the first
N characters:
fun String.skipFirst(n: Int) = if (length > n) this.substring(n) else ""
Next, I create an extension property
answer, which is the Answer to the Ultimate Question of Life, the Universe, and Everything:
val String.answer get() = 42
Both extensions are declared in the package
com.github.alien11689.extensions, in the file
StringExtensions. However, the generated class in the target directory is named
StringExtensionsKt , and this is the name that must be used when accessing it from other languages. Specific class names can be forced by the annotation
@file:JvmName.
Using Kotlin Extensions in Groovy
There are two ways to use extensions in Groovy (that are supported by good IDEs). First, you can declare the scope where the extensions are available by the
use method:
def "should use extension method"() { expect: use(StringExtensionsKt) { input.skipFirst(n) == expected } where: input | n | expected "abcd" | 3 | "d" "abcd" | 6 | "" "" | 3 | "" } def "should use extension property"() { expect: use(StringExtensionsKt) { "abcd".answer == 42 } }
This is acceptable, but it is not very convenient. The second and much better way is to use an extension module definition. The extension module is defined in the file
org.codehaus.groovy.runtime.ExtensionModule in }
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/using-kotlin-extensions-in-groovy | CC-MAIN-2017-39 | refinedweb | 256 | 50.12 |
Get the offset and length of a mapped memory block
#include <sys/mman.h> int posix_mem_offset( const void *addr, size_t len, off_t *off, size_t *contig_len, int *fildes ); int posix_mem_offset64( const void *addr, size_t len, off64_t *off, size_t *contig_len, int *fildes );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The posix_mem_offset() and posix_mem_offset64() functions set the variable pointed to by off to the offset (or location), within a memory object, of the memory block currently mapped at addr. The posix_mem_offset64() function is a large-file support version of posix_mem_offset().
The posix_mem_offset() function sets the variable pointed to by fildes to the descriptor used (via mmap()) to establish the mapping that contains addr, or -1 if the descriptor has since been closed.
This function supports typed memory, shared memory, and memory-mapped files, but not anonymous memory.
The len argument specifies the length of the block of memory you want the offset for. On return, the value pointed to by contig_len is either len or the length of the largest contiguous block of the memory object that's currently mapped to the calling process starting at addr, whichever is smaller.
If the memory object mapped at addr is a typed memory object, then if you use the off and contig_len values that you obtained by calling posix_mem_offset() is exactly the same area that was mapped at addr in the address space of the process that called posix_mem_offset().
posix_mem_offset() is POSIX 1003.1 TYM; posix_mem_offset64() is for large-file support | http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/p/posix_mem_offset.html | CC-MAIN-2018-22 | refinedweb | 258 | 58.72 |
Hello everyone, in our last blog we saw that how we can execute ours test in headless mode and now in this blog we will see how we can achieve Data-driven framework with selenium, Scala, and SBT.
Need for data-driven framework
- A data-Driven framework helps us in separating the test script logic and the test data from one another. It allows us to write test automation scripts in which we can pass different sets of test data.
- The main reason behind a data-driven framework is the re-usability of code. The same block of code can be reused multiple times with different data sets every time.
- The data is usually stored in an excel sheet or a CSV file. This enables us to modify our tests without making any changes to the code. We can simply update our data files and we are done.
- The execution is faster as compared to the manual approach.
Data-driven testing using Apache POI
- Apache POI is an open-source library that is used to design and modify Microsoft Office product files.
- Using Apache POI we can read data from excel files and use them in our test suite. It is easy to use and implement.
DataDriven.scala file with Apache POI
import org.apache.poi.ss.usermodel.CellType import org.apache.poi.ss.util.NumberToTextConverter import org.apache.poi.xssf.usermodel.XSSFWorkbook import java.io.FileInputStream import java.util._ object DataDriven { def extractData(testSheetName: String, testCaseName: String, fieldName: String): ArrayList[String] = { val file = new FileInputStream(System.getProperty("user.dir") + "/Data/LoginData.xlsx") //taking location of the excel sheet val workbook = new XSSFWorkbook(file) //storing excel sheet in a XSSFWorkbook file val excelData = new ArrayList[String] val sheets = workbook.getNumberOfSheets //extracting number of sheets in the workbook for (i <- 0 until sheets) { if (workbook.getSheetName(i).equalsIgnoreCase(testSheetName)) { //Check for the expected name of sheet inside the workbook val sheet = workbook.getSheetAt(i) val rows = sheet.iterator val firstRow = rows.next val ce = firstRow.cellIterator var k = 0 var column = 0 while ( { ce.hasNext }) { val value = ce.next if (value.getStringCellValue.equalsIgnoreCase(fieldName)) column = k //Check for the expected name of column inside the workbook k += 1 } while ( { rows.hasNext }) { val r = rows.next if (r.getCell(column).getStringCellValue.equalsIgnoreCase(testCaseName)) { //Check for the expected name of row inside the workbook val cv = r.cellIterator while ( { cv.hasNext }) { val c = cv.next if (c.getCellType eq CellType.STRING) excelData.add(c.getStringCellValue) //handling of the input if it is of string type else excelData.add(NumberToTextConverter.toText(c.getNumericCellValue)) //handling of the input if it is of integer type } } } } } excelData } }
- In the above given code we have written a small function which takes three inputs.
- testSheetName : Sheet in which our tests is stored.
- testCaseName : Name of the row in which data is stored.
- fieldName : Name of the column from which we need to extract data.
- We will read the excel sheet from the given location.
- Then, store our whole workbook in an XSSFWorkbook type file.
- Extract the number of sheets inside the workbook and compare it with the required sheet name.
- When we find the correct sheet we will iterate through that sheet searching for the desired column name.
- Once we find the desired column, we will start looking for the desired row.
- After this, we will handle the scenario where if the input from the excel file is of integer instead of a string. Then we will convert it to string.
- Finally, we will be returning the data.
Selenium test script
import org.scalatest._ import org.scalatest.matchers._ import org.scalatestplus.selenium.Chrome.webDriver import org.scalatestplus.selenium._ class Test extends flatspec.AnyFlatSpec with should.Matchers with WebBrowser { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/DriverFiles/chromedriver") //reading location of chrome driver val host = "" // storing URL to be automated val extractedData = DataDriven.extractData("Sheet1", "Login", "TestCases") //call the function from DataDriven.scala "The blog app home page" should "have the correct title" in { go to host //Hit the required URL emailField("username").value = extractedData.get(1) //Find the email field and enter the email data from the excel sheet pwdField("password").value = extractedData.get(2) //Find the password field and enter the password data from the excel sheet click on id("Login") //Click on login button pageTitle should be("Login | Salesforce") //Validate that the title of the page is correct webDriver.close() //Close the web browser } }
- In the above code, we are extracting the chrome driver.
- Then we are calling the function which we described above and giving appropriate inputs to it.
- After this, we are hitting the Salesforce.com login page and trying to locate email and password fields.
- Once the fields are identified we are entering the data which we are reading from the excel sheet.
- After entering the data we are hitting on the login button to check if we can log in or not.
So, this was a short blog on how we can create a data-driven framework with selenium and Scala. See you in the next one | https://blog.knoldus.com/data-driven-framework-with-selenium-scala-and-sbt/ | CC-MAIN-2021-43 | refinedweb | 850 | 60.41 |
Greetings all,
Well, this is my second programming assignment, and I'm enjoying Java no more than when I started the course (probably reflected in the comments), so anyway, to help people, here's a Java "Applet" paint program, or at least the framework. There is still some work to do in implementing the various aspects, but it should be simple enough with a quick search of the Internet, and it's fairly well commented (very important, by the way, even if it's just to vent your frustrations). I've censored any expletives too.
okay, and to run it, you'll need do something in HTML like this:okay, and to run it, you'll need do something in HTML like this:// Hello, this is your pilot speaking... err, testing, testing, 1, 2, 3...!!! // We are about to enter a Volcanic Ash Could, please stand by whilst I divert // your attention to one of hope! // This assignment is a 'basic' paint package in an 'Applet', which again makes // me hate Java even more! Arrggghhhhhh!!! Where is the logic? Why can't I get // these damn booleans to work?!? And why the blummin' blazes to people choose // - yes *choose* - to create programs in such a language? // I've had more fun typing a 18,000 words whilst being partially blind-folded // with my nose! Is this progress? // // Anyways, let's get this party started, first we needs to do some of that // importing stuff, so here goes: import java.io.*; import java.applet.*; import java.awt.*; import java.awt.event.*; // Phew! That works without any red lines, and now we need to give our package // a name, extent it to an Applet and implement both a Mouse Listener and a // Motion Listener too, and so on: public class BasicPaint1 extends Applet implements MouseListener, MouseMotionListener, ActionListener, KeyListener { // Right, we're in to the program now. Let's declare some variables which // we'll need to use later on. // These first variables I tried to declare as booleans, but Java sux almost // as much as Adobe ActionScript. // What these do is give us conditions later on. int Fill,Rect,Oval,RoundRect,Triangle,Str; // Here is something for the KeyTyped routine if you're entering text // onto the canvas: int A,Z,TX,TY; // Now, just in case you want to type something on the package, there'll have // to be a String type thingymebob in the program somewhere, hence we need // to declare that right about now: String S$=""; // Right, now the above will set a condition to draw different shapes, // which will either be filled or not. The following two are used to set // the main parameters for the shape size: int XAxis,YAxis; // and now we have two sets of RGB values, the first set is for the background // colour and the second is for the foreground colour, ie, what you pain with: int R,G,B,R1,G1,B1; // These two integers will pass the set width and height through them: int width,height; // This is to set what part of the screen you may draw from, because of the // buttons at the top, we have 86 scan-lines used: int MinX,MinY; // Okay, let's add some kick-donkey buttons: Button Fill1=new Button("Fill on/off"); Button Rect1=new Button("Rectangle"); Button Oval1=new Button("Oval"); Button RoundRect1=new Button("Rounded rect"); Button Triangle1=new Button("Triangle"); Button String1=new Button("Text"); // Mint, and now we need to have some input boxes, and we also need to // label them up, don't we...??? or something :-P TextField RedFore=new TextField("255",3); Label label_RedFore=new Label("Red Foreground:"); TextField GreenFore=new TextField("255",3); Label label_GreenFore=new Label("Green Foreground:"); TextField BlueFore=new TextField("255",3); Label label_BlueFore=new Label("Blue Foreground:"); TextField RedBack=new TextField("000",3); Label label_RedBack=new Label("Red Background:"); TextField GreenBack=new TextField("000",3); Label label_GreenBack=new Label("Green Background:"); TextField BlueBack=new TextField("000",3); Label label_BlueBack=new Label("Blue Background:"); TextField CW=new TextField("640",4); Label label_CW=new Label("Canvas Width:"); TextField CH=new TextField("480",4); Label label_CH=new Label("Canvas Height:"); // Now here is where we declare our back buffer and main canvas: Image backbuffer; Graphics backg; // Okay, we need to initialize the above variables and set things in action: public void init() { // As you can see, we're using the variables above, one is on and // zero is off, like in a boolean that I couldn't get to work! Fill=1;Oval=0;Rect=0;RoundRect=0;Triangle=0;Str=1; // Right, now to set the default RGB values: R=0;G=0;B=0;R1=255;G1=255;B1=255; // Now let's set the minimum parameters that can be drawn to: MinX=0;MinY=86; // Okays, so now we needs to the the default size of the brush painty // bit that will be 'drawn' on the canvas: XAxis=30;YAxis=30; // Here is where we get the width and height of the canvas: width=getSize().width;height=getSize().height; // Now, as we have buttons at the top, we need to add MinY to the // canvas height: height=height+MinY; // So we need to create a back buffer at the same width and height: backbuffer=createImage(width,height); // And of course we call the image *from* the back buffer!!!111ONE backg=backbuffer.getGraphics(); // First, we need to add white to the background of the buttons and // stuff: backg.setColor(new Color(255,255,255)); backg.fillRect(MinX,0,width,MinY); // So, we tell the program to set the background colour, sending it // to the above sub-routine, drawing a rectangle of the same size // and using the default background RGB colour: backg.setColor(new Color(R,G,B)); backg.fillRect(MinX,MinY,width,height); // Now I see where this is going, we need to set the foreground colour // here: backg.setColor(new Color(R1,G1,B1)); // Right, now let's have a look at them buttons! Fill1.addActionListener(this); Rect1.addActionListener(this); Oval1.addActionListener(this); RoundRect1.addActionListener(this); Triangle1.addActionListener(this); String1.addActionListener(this); add(Fill1);add(Rect1);add(Oval1);add(RoundRect1); add(Triangle1);add(String1); // Right, now let's add the text fields: add(label_RedFore);add(RedFore);add(label_GreenFore);add(GreenFore); add(label_BlueFore);add(BlueFore);add(label_RedBack);add(RedBack); add(label_GreenBack);add(GreenBack);add(label_BlueBack);add(BlueBack); add(label_CW);add(CW);add(label_CH);add(CH); // As this is an 'object' we need to add the mouse listeners to 'this' addMouseListener(this); addMouseMotionListener(this); // Okay, so here's a bit of an anomoly in Java - because you've got a // MouseListener and MouseMotionListener active, an Applet can't focus // on the two things at once - because it sux - so we need to remind // it to set its' focus to different things, like the keyboard. You do // this with the following before adding the KeyListener: setFocusable(true); addKeyListener(this); } public void mouseMoved (MouseEvent e) { // So let's show the status of X and Y axis, innit int x=e.getX(); int y=e.getY(); // This routine, or 'method' just shows the X and Y co-ordinates // of the mouse pointer as it's moved about, good though: showStatus("Donkeysoft Sketchpad V1.7, mouse at: "+x+" "+y); // This has something to do with consuming a method - don't ask // me! e.consume(); } public void mouseClicked (MouseEvent e) { // Okay, so now we'll check which condition is true and set // up some variables perhaps or do some drawing to the canvas // Str is set for if you want to type onto the canvas like in Paint if (Str==1) { TX=e.getX(); TY=e.getY(); S$=""; repaint(); e.consume(); return; } // Get X and Y co-ords now generically for the rest of the // method to use in this sub routine: int x=e.getX(); int y=e.getY(); // Now we'll check if the cursor is in the paint area: if (y<MinY) { // If it is, let's get the rock outta here!!! return; } // Use those pre-set colours now, in RGB values: backg.setColor(new Color(R1,G1,B1)); // And now we need to decide what's going to be drawn, so if the // read integer is 1 then that means do it, like drawing rectangles // and if Fill is 1 then it does a fill, otherwise you get an outline: if (RoundRect==1 && Fill==1) { backg.fillRoundRect(x-(XAxis/2),y-(YAxis/2),XAxis,YAxis,XAxis/2,YAxis/2); } // The rest should be obvious:); } // This bit writes something to the status bar: showStatus("Donkeysoft Sketchpad V1.7, mouse at: "+x+" "+y); // Now let's clear the area behind the buttons, just in case: backg.setColor(new Color(255,255,255)); backg.fillRect(MinX,0,width,MinY); // Now we call a repaint and consume this mouse action or it'll repeat. repaint(); e.consume(); } public void mouseDragged (MouseEvent e) { // As above, but this is a mouse click-and-drag rather than a single // click :-) int x=e.getX(); int y=e.getY(); if (y<MinY) { // See above if you're unsure of what this and the following does: return; } backg.setColor(new Color(R1,G1,B1)); if (RoundRect==1 && Fill==1) { backg.fillRoundRect(x-(XAxis/2),y-(YAxis/2),XAxis,YAxis,XAxis/2,YAxis/2); }); } showStatus("Donkeysoft Sketchpad V1.7, mouse at: "+x+" "+y); // Now let's clear the area behind the buttons, just in case: backg.setColor(new Color(255,255,255)); backg.fillRect(MinX,0,width,MinY); repaint(); e.consume(); } public void keyTyped (KeyEvent e) { // This is for typing (or drawing Strings) onto the canvas :-) if (Str!=1) { return; } // Okay, let's get the keyboard input :-) char C$=e.getKeyChar(); Z=C$; A=S$.length(); // We need to check two conditions, one is whether or not there has // been a keypress, and the other is to check the integer value of // that keypress to make sure that it's not equal to 8, which is // the delete key! if(C$!=KeyEvent.CHAR_UNDEFINED && Z!=8) { // As long as the conditions are correct as above, we need to add // or something to the string to draw it to the canvas later: S$=S$+C$; Z=C$; backg.setColor(new Color(R1,G1,B1)); backg.drawString(S$,TX,TY); showStatus("Key value is ("+Z+")"); repaint(); e.consume(); } // Right, so what do we do if the delete key is pressed? // Well, here's a good one, let's take the value of the background // colour and redraw the string first, this makes it invisible, // and then let's make the string one character less before redrawing // it onto the screen, thus elimenating the last char, ie, the one // that has been deleted. Magic! else if(Z==8 && A>0) { backg.setColor (new Color(R,G,B)); backg.drawString(S$,TX,TY); S$=S$.substring(0,A-1); backg.setColor (new Color(R1,G1,B1)); backg.drawString(S$,TX,TY); showStatus("Key value is ("+Z+")"); repaint(); e.consume(); } } public void keyPressed(java.awt.event.KeyEvent keyEvent) { } public void keyReleased(java.awt.event.KeyEvent keyEvent) { } public void actionPerformed(ActionEvent e) { } // Okay, so this is there the back buffer is drawn to and syncronised public void update (Graphics g) { g.drawImage(backbuffer,0,0,this); if (Str==1) { // This is the Str condition again, it draws a maker to the canvas // but not to the back buffer, because that'd be bad: g.setColor(new Color (R1,G1,B1)); g.drawLine(TX,TY,TX,TY-10); g.drawLine(TX,TY,TX+10,TY); } // This seems to do some sort of syncronisation and stuff, don't ask me: getToolkit().sync(); } // This then updates (or flips) the back buffer so we can see the last // action added to the canvas, good, innit? public void paint (Graphics g) { update(g); } // All this stuffs here needed to be added to this program or Java doesn't // like it and it takes *hours* to work this out, even though it's not // actually doing anything whatsoever. I'd like to meet the sadistic // idiots who created all of these useless bits in Java, I'm sure it's // been created just to annoy people rather than being in any way // whatsoever helpful. public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } public void mousePressed(java.awt.event.MouseEvent mouseEvent) { } public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { } }.<HTML> <applet width=640 height=480 </applet> </HTML>
Have fun,
Shaun. | http://www.javaprogrammingforums.com/java-swing-tutorials/4286-applet-paint-program-frame-work.html | CC-MAIN-2015-40 | refinedweb | 2,080 | 58.92 |
Archived:How to get system information.
S60 5th Edition
Overview
This article shows how to retrieve system information in Python.
Preconditions
Note: The function ring_type is not available for S60 1st Edition.
The value returned by the battery function may be incorrect while the device is being charged.
Source code
from sysinfo import *
print "Battery level:", battery()
print "Signal strenght:", signal_bars()
print "Signal strenght in dBm:", signal_dbm()
print "Display resolution:", str(display_pixels()[0]) + "x" + str(display_pixels()[1])
print "Display size:", str(display_twips()[0]) + "x" + str(display_twips()[1]), "twips"
print "Free space:", free_drivespace()
print "IMEI:", imei()
print "RAM free/total:", str(free_ram()) + "/" + str(total_ram())
print "ROM:", total_rom()
print "Active profile:", active_profile()
print "Ring type:", ring_type()
print "Operating system version:", os_version()
print "Firmware version:", sw_version()
Postconditions
The information is displayed.
Additional information
The following functions are available in the sysinfo module:
- active_profile()
Returns the currently active profile as a string, which can be one of the following: 'general', 'silent', 'meeting', 'outdoor', 'pager', 'offline', , 'drive' or 'user <profile value>'.
- battery()
Returns the current battery level. On devices based on S60 2nd Edition Feature Pack 1 (S60 2.1) or earlier the value ranges from 0 (empty) to 7 (full). On newer devices the value ranges from 0 (empty) to 100 (full). On the emulator the value is always 0.
- display_twips()
Returns the width and height of the display in twips. A twip is 1/1440 of an inch or 1/567 of a centimeter.
- display_pixels()
Returns the width and height of the display in pixels.
- free_drivespace()
Returns a dictionary with the available drive letters as keys and the free storage space on each drive as values.
- imei()
Returns the IMEI code of the device as a Unicode string. If used on an emulator, the returned string will always be u'000000000000000'.
- max_ramdrive_size()
Returns the maximum size of the RAM drive on the device.
- total_ram()
Returns the amount of RAM memory on the device.
- free_ram()
Returns the amount of free RAM memory available on the device.
- total_rom()
Returns the amount of read-only ROM memory on the device.
- ring_type()
Returns the current ringing type as a string, which can be one of the following: 'normal', 'ascending', 'ring once', 'beep', or 'silent'.
- signal_bars()
Returns the current network signal strength ranging from 0 to 7, with 0 meaning no signal and 7 meaning a strong signal. If used on an emulator, the returned value will always be 0.
- signal_dbm()
Available starting with SDK 2.8. Returns the current network signal strength in dBm. If used on an emulator, the returned value will always be 0.
- sw_version()
Returns the software version as a Unicode string. If used on an emulator, the returned string will always be u'emulator'. For example, a software version can be returned as u'V 30.0.015 15-07-08 RM-159 N95(c)NMP'.
- os_version()
Returns the operating system version number of the device as a three element tuple (major version, minor version, build number). The elements are as follows:
- The major version number, ranging from 0 to 127 inclusive
- The minor version number, ranging from 0 to 99 inclusive
- The build number, ranging from 0 to 32767 inclusive.
Known issues
On Nokia N80 the sw_version function returns error -46.
On Nokia N95 and Nokia E90 the max_ramdrive_size function returns KErrNotSupported.
04 Sep
2009 | http://developer.nokia.com/community/wiki/Archived:How_to_get_system_information_using_PySymbian | CC-MAIN-2014-41 | refinedweb | 553 | 56.66 |
A.
In this article, I explore the Linux SCI, demonstrate adding a system call to the 2.6.17 and prior 2.6 kernels, and then use this function from user-space. I also investigate some of the functions that you'll find useful for system call development and alternatives to system calls. Finally, I look at some of the ancillary mechanisms related to system calls, such as tracing their usage from a given process. (The system call interface changed in kernels 2.6.18 and later to simplify coding. (If you're using a 2.6.18 kernel or later, see the sidebar "Using Linux kernels 2.6.18 and later.")
The SCI
The implementation of system calls in Linux is varied based on the
architecture, but it can also differ within a given architecture. For
example, older x86 processors used an interrupt mechanism to migrate from
user-space to kernel-space, but new IA-32 processors provide instructions
that optimize this transition (using
sysenter
and
sysexit instructions). Because so many
options exist and the end-result is so complicated, I'll stick to a
surface-level discussion of the interface details. See the
Resources at the end of this article for the gory
details.
You needn't fully understand the internals of the SCI to amend it, so I
explore a simple version of the system call process (see Figure 1). Each
system call is multiplexed into the kernel through a single entry point.
The eax register is used to identify the particular system call that
should be invoked, which is specified in the
C
library (per the call from the user-space application). When the
C library has loaded the system call index and
any arguments, a software interrupt is invoked (interrupt 0x80), which
results in execution (through the interrupt handler) of the
system_call function. This function handles all
system calls, as identified by the contents of eax. After a few simple
tests, the actual system call is invoked using the
system_call_table and index contained in eax.
Upon return from the system call,
syscall_exit
is eventually reached, and a call to
resume_userspace transitions back to
user-space. Execution resumes in the
C library,
which then returns to the user application.
Figure 1. The simplified flow of a system call using the interrupt method
At the core of the SCI is the system call demultiplexing table. This table,
shown in Figure 2, uses the index provided in eax to identify which system
call to invoke from the table (
sys_call_table).
A sample of the contents of this table and the locations of these entities
is also shown. (For more about demultiplexing, see the sidebar,
"System call
demultiplexing.")
Figure 2. The system call table and various linkages
Adding a Linux system call
Adding a new system call is mostly procedural, although you should look out for a few things. This section walks through the construction of a few system calls to demonstrate their implementation and use by a user-space application.
You perform three basic steps to add a new system call to the kernel:
- Add the new function.
- Update the header files.
- Update the system call table for the new function.
Note: This process ignores user-space needs, which I address later.
Most often, you create a new file for your functions. However, for the sake of simplicity, I add my new functions to an existing source file. The first two functions, shown in Listing 1, are simple examples of a system call. Listing 2 provides a slightly more complicated function that uses pointer arguments.
Listing 1. Simple kernel functions for the system call example
asmlinkage long sys_getjiffies( void ) { return (long)get_jiffies_64(); } asmlinkage long sys_diffjiffies( long ujiffies ) { return (long)get_jiffies_64() - ujiffies; }
In Listing 1, two functions are provided for jiffies monitoring. (For more
information about jiffies, see the sidebar,
"Kernel
jiffies.") The first function
returns the current jiffies, while the second returns the difference of
the current and the value that the caller passes in. Note the use of the
asmlinkage modifier. This macro (defined in
linux/include/asm-i386/linkage.h) tells the compiler to pass all function
arguments on the stack.
Listing 2. Final kernel function for the system call example
asmlinkage long sys_pdiffjiffies( long ujiffies, long __user *presult ) { long cur_jiffies = (long)get_jiffies_64(); long result; int err = 0; if (presult) { result = cur_jiffies - ujiffies; err = put_user( result, presult ); } return err ? -EFAULT : 0; }
Listing 2 provides the third function. This function takes two arguments: a
long and a pointer to a
long that's defined as
__user. The
__user
macro simply tells the compiler (through
noderef) that the pointer should not be
dereferenced (as it's not meaningful in the current address space). This
function calculates the difference between two jiffies values, and then
provides the result to the user through a user-space pointer. The
put_user function places the result value into
user-space at the location that
presult
specifies. If an error occurs during this operation, it will be returned,
and you'll likewise notify the user-space caller.
For step 2, I update the header files to make room for the new functions in the system call table. For this, I update the header file linux/include/asm/unistd.h with the new system call numbers. The updates are shown in bold in Listing 3.
Listing 3. Updates to unistd.h to make room for the new system calls
Click to see code listing
Now I have my kernel system calls and numbers to represent them. All I need to do now is draw an equivalence among these numbers (table indexes) and the functions themselves. This is step 3, updating the system call table. As shown in Listing 4, I update the file linux/arch/i386/kernel/syscall_table.S for the new functions that will populate the particular indexes shown in Listing 3.
Listing 4. Update the system call table with the new Functions
.long sys_getcpu .long sys_epoll_pwait .long sys_getjiffies /* 320 */ .long sys_diffjiffies.long sys_pdiffjiffies
Note: The size of this table is defined by the symbolic constant
NR_syscalls.
At this point, the kernel is updated. I must recompile the kernel and make the new image available for booting before testing the user-space application.
Reading and writing user memory
The Linux kernel provides several functions that you can use to move system
call arguments to and from user-space. Options include simple functions
for basic types (such as
get_user or
put_user). For moving blocks of data such as
structures or arrays, you can use another set of functions:
copy_from_user and
copy_to_user. Moving null-terminated strings
have their own calls:
strncpy_from_user and
strlen_from_user. You can also test whether a
user-space pointer is valid through a call to
access_ok. These functions are defined in
linux/include/asm/uaccess.h.
You use the
access_ok macro to validate a
user-space pointer for a given operation. This function takes the type of
access (
VERIFY_READ or
VERIFY_WRITE), the pointer to the user-space
memory block, and the size of the block (in bytes). The function returns
zero on success:
int access_ok( type, address, size );
Moving simple types between the kernel and user-space (such as ints or
longs) is accomplished easily with
get_user and
put_user. These macros each take a value and a
pointer to a variable. The
get_user function
moves the value that the user-space address specifies
(
ptr) into the kernel variable specified
(
var). The
put_user
function moves the value that the kernel variable
(
var) specifies into the user-space address
(
ptr). The functions return zero on
success:
int get_user( var, ptr ); int put_user( var, ptr );
To move larger objects, such as structures or arrays, you can use the
copy_from_user and
copy_to_user functions. These functions move an
entire block of data between user-space and the kernel. The
copy_from_user function moves a block of data
from user-space into kernel-space, and
copy_to_user moves a block of data from the
kernel into user-space:
unsigned long copy_from_user( void *to, const void __user *from, unsigned long n ); unsigned long copy_to_user( void *to, const void __user *from, unsigned long n );
Finally, you can copy a NULL-terminated string from user-space to the
kernel by using the
strncpy_from_user function.
Before calling this function, you can get the size of the user-space
string with a call to the
strlen_user
macro:
long strncpy_from_user( char *dst, const char __user *src, long count ); strlen_user( str );
These functions provide the basics for memory movement between the kernel and user-space. Some additional functions exist (such as those that reduce the amount of checking performed). You can find these functions in uaccess.h.
Using the system call
Now that kernel is updated with a few new system calls, let's look at what's necessary to use them from a user-space application. There are two ways that you can use new kernel system calls. The first is a convenience method (not something that you'd probably want to do in production code), and the second is the traditional method that requires a bit more work.
With the first method, you call your new functions as identified by their
index through the
syscall function. With the
syscall function, you can call a system call by
specifying its call index and a set of arguments. For example, the short
application shown in Listing 5 calls your
sys_getjiffies using its index.
Listing 5. Using syscall to invoke a system call
#include <linux/unistd.h> #include <sys/syscall.h> #define __NR_getjiffies 320 int main() { long jiffies; jiffies = syscall( __NR_getjiffies ); printf( "Current jiffies is %lx\n", jiffies ); return 0; }
As you can see, the
syscall function includes as
its first argument the index of the system call table to use. Had there
been any arguments to pass, these would be provided after the call index.
Most system calls include a
SYS_ symbolic
constant to specify their mapping to the
__NR_
indexes. For example, you invoke the index
__NR_getpid with
syscall as:
syscall( SYS_getpid )
The
syscall function is architecture specific
but uses a mechanism to transfer control to the kernel. The argument is
based on a mapping of
__NR indexes to
SYS_ symbols provided by
/usr/include/bits/syscall.h (defined when the libc is built). Never
reference this file directly; instead use /usr/include/sys/syscall.h.
The traditional method requires that you create function calls that match
those in the kernel in terms of system call index (so that you're calling
the right kernel service) and that the arguments match. Linux provides a
set of macros to provide this capability. The
_syscallN macros are defined in
/usr/include/linux/unistd.h and have the following format:
_syscall0( ret-type, func-name ) _syscall1( ret-type, func-name, arg1-type, arg1-name ) _syscall2( ret-type, func-name, arg1-type, arg1-name, arg2-type, arg2-name )
The
_syscall macros are defined up to six
arguments deep (although only three are shown here).
Now, here's how you use the
_syscall macros to
make your new system calls visible to the user-space. Listing 6 shows an
application that uses each of your system calls as defined by the
_syscall macros.
Listing 6. Using the _syscall macro for user-space application development
#include <stdio.h> #include <linux/unistd.h> #include <sys/syscall.h> #define __NR_getjiffies 320 #define __NR_diffjiffies 321 #define __NR_pdiffjiffies 322 _syscall0( long, getjiffies ); _syscall1( long, diffjiffies, long, ujiffies ); _syscall2( long, pdiffjiffies, long, ujiffies, long*, presult ); int main() { long jifs, result; int err; jifs = getjiffies(); printf( "difference is %lx\n", diffjiffies(jifs) ); err = pdiffjiffies( jifs, &result ); if (!err) { printf( "difference is %lx\n", result ); } else { printf( "error\n" ); } return 0; }
Note that the
__NR indexes are necessary in this
application because the
_syscall macro uses the
func-name to construct the
__NR index
(
getjiffies ->
__NR_getjiffies). But the result is that you
can call your kernel functions using their names, just like any other
system call.
Alternatives for user/kernel interactions
System calls are an efficient way of requesting services in the kernel. The biggest problem with them is that it's a standardized interface. It would be difficult to have your new system call added to the kernel, so any additions are likely served through other means. If you have no intent of mainlining your system calls into the public Linux kernel, then system calls are a convenient and efficient way to make kernel services available to user-space.
Another way to make your services visible to user-space is through the /proc file system. The /proc file system is a virtual file system for which you can surface a directory and files to the user, and then provide an interface in the kernel to your new services through a file system interface (read, write, and so on).
Tracing system calls with strace
The Linux kernel provides a useful way to trace the system calls that a
process invokes (as well as those signals that the process receives). The
utility is called
strace and is executed from
the command line, using the application you want to trace as its argument.
For example, if you wanted to know which system calls were invoked during
the context of the
date command, type the
following command:
strace date
The result is a rather large dump showing the various system calls that are
performed in the context of a
date command
call. You'll see the loading of shared libraries, mapping of memory, and
-- at the end of the trace -- the emitting of the date information to
standard-out:
... write(1, "Fri Feb 9 23:06:41 MST 2007\n", 29Fri Feb 9 23:06:41 MST 2007) = 29 munmap(0xb747a000, 4096) = 0 exit_group(0) = ? $
This tracing is accomplished in the kernel when the current system call
request has a special field set called
syscall_trace, which causes the function
do_syscall_trace to be invoked. You can also
find the tracing calls as part of the system call request in
./linux/arch/i386/kernel/entry.S (see
syscall_trace_entry).
Going further. See Resources to dig even further into the SCI.
Resources
Learn
- In "Access the Linux kernel using the /proc filesystem" (developerWorks, March 2006), learn how to develop kernel code that uses the /proc file system for user-space/kernel communication.
- Read "Sysenter Based System Call Mechanism in Linux 2.6" from Manugarg to get a detailed look at the system call gate between the user-space application and the kernel. This paper focuses on the transition mechanisms provided in the 2.6 kernel.
- This paper details the assembly language linkages between the user-space and the kernel.
- The GNU
CLibrary (glibc) is the standard library for GNU
C. You'll find the glibc for Linux and also for numerous other operating systems. The GNU
CLibrary follows numerous standards, including the ISO C 99, POSIX, and UNIX98. You can find more information about it at the GNU Project.
- The
syscallfunction allows a user-space program to make a system call. This function takes a system-call number and a set of arguments which are passed to the kernel-based system call. You can read more about
syscalland get a complete list of available system calls in the Linux syscalls man page.
- Wikipedia provides an interesting perspective on system calls, including history and typical implementations.
-. | http://www.ibm.com/developerworks/linux/library/l-system-calls/ | CC-MAIN-2014-15 | refinedweb | 2,547 | 62.17 |
I got the button put together and programmed
Super simple code
#include <ELECHOUSE_CC1101.h> ELECHOUSE_CC1101 cc1101; byte TX_NOTPUSHED_buffer[61] = {0}; byte TX_PUSHED_buffer[61] = {0}; byte i; int buttonState = 0; void setup() { pinMode(3, INPUT); // put your setup code here, to run once: Serial.begin(9600); cc1101.Init(); for (i = 0; i <61; i ++) { TX_NOTPUSHED_buffer[i] = 0; TX_PUSHED_buffer[i] = 1; } } void loop() { buttonState = digitalRead(3); if (buttonState == HIGH) { // NOT PUSHED Serial.println("Not Pushed"); cc1101.SendData(TX_NOTPUSHED_buffer,61); } else { // PUSHED Serial.println("Pushed"); cc1101.SendData(TX_PUSHED_buffer,61); } }
It does seem to work ... and it seems (even though it may not look like it) pretty reliabile ... I knocked it around a little bit and it still working just fine :-D
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In. | https://hackaday.io/project/8221-stop/log/27282-some-progress | CC-MAIN-2019-30 | refinedweb | 137 | 59.7 |
Button widget with an image displayed next to the text (or centered in the button without text) More...
#include <TGUI/Widgets/BitmapButton.hpp>
Makes a copy of the widget if you don't know its exact type.
This function should only be used when you don't know the type of the widget. If you know what kind of widget you are copying, you should use the copy function.
Implements tgui::Widget.
Makes a copy of another button.
Creates a new bitmap button widget.
Draw the widget to a render target.
Implements tgui::Widget.
Returns the image being displayed next to the text.
Returns the relative size of the image displayed next to the text.
Sets the image that should be displayed next to the text.
Sets the relative size of the image to display next to the text.
Changes the size of the widget.
Usage examples:
Reimplemented from tgui::Button.
Changes the size of the button.
Reimplemented from tgui::Widget.
Changes the size of the widget.
Changes the caption of the button.
Reimplemented from tgui::Button. | https://tgui.eu/documentation/0.8/classtgui_1_1BitmapButton.html | CC-MAIN-2022-21 | refinedweb | 177 | 70.5 |
Hello,
What is the formula to get the hourly time series with API in Python ?
Thanks a lot.
Hi,
You just have to specify the interval as below:
req = ek.get_timeseries(["MSFT.O"], interval="hour")
Possible values: 'tick', 'minute', 'hour', 'daily', 'weekly', 'monthly', 'quarterly', 'yearly' (Default 'daily')
Thanks for your answer.
It works very well, now can you please tell me how to decide the time zone ? it seems that all is using GMT timezone...
Thanks Gurpeet,
However I dont see how to adapt my script to get the output (df) in my local time zone:
year=2019
print(year)
first_date = datetime(year,1,1)
last_date = datetime.today() + timedelta(days =1)
df =pd.DataFrame(ek.get_timeseries(ric, start_date=first_date,end_date = last_date,interval="hour"))
Thanks in advance.
Hi
last_date is incorrect because datetime.today() + timedelta(days =1) is in the future
I suppose you want to get timeseries from 1st of January, 2019. If I'm right, you don't have to set end_date (because default end_date is today())
This should help you:
import eikon as ek from datetime import datetime from dateutil.tz import tzlocal year=2019 print(year) first_date = datetime(year,1,1, tzinfo=tzlocal()) df =ek.get_timeseries("AAPL.O", start_date=first_date, interval="hour") print(df) HIGH LOW OPEN CLOSE COUNT VOLUME Date 2019-09-09 09:00:00 53.4500 53.2725 53.425000 53.4025 40 9948 2019-09-09 10:00:00 53.5175 53.4050 53.417500 53.4200 33 3328 2019-09-09 11:00:00 53.5750 53.4375 53.500000 53.5325 39 12700 2019-09-09 12:00:00 53.6400 53.5000 53.502500 53.5850 336 171268 2019-09-09 13:00:00 53.6900 53.5000 53.549925 53.6500 547 314024 ... ... ... ... ... ... ... 2020-09-04 20:00:00 127.9900 116.6476 121.480000 120.9000 392570 42388645 2020-09-04 21:00:00 453.2631 117.8411 120.905000 120.1000 17844 16822104 2020-09-04 22:00:00 129.1490 119.6200 120.100000 120.1500 8557 1934439 2020-09-04 23:00:00 120.2500 119.7700 120.150000 119.8200 2101 165211 2020-09-05 00:00:00 120.0600 119.3500 119.830000 120.0000 2630 209387 [4026 rows x 6 columns]
(ek.get_timeseries() already returns a DataFrame)
According to the interval, size of timeseries is limited. In this example, hourly timeseries starts from 2019-09-09.
And you can see that current range of date is too large because timeseries stops on 2020-09-05.
You'll have to reduce the range of date or update the interval to get a result that correspond to [start_date, end_date] | https://community.developers.refinitiv.com/questions/65304/hourly-time-series-with-ekget-timeseries.html | CC-MAIN-2020-45 | refinedweb | 445 | 77.13 |
Fortran mex routine mxGetClassName
853 Downloads
Updated 25 Sep 2009
The Mathworks supplied mxGetClassName routine for Fortran does not work. This routine is a drop-in replacement. The following syntax and description is similar to The Mathworks documentation, except that this drop-in replacement routine returns a fixed 128 length character string. This routine only works for mex routines, since it relies on the mexCallMATLAB function. Thus, it will not work for engine applications.
IMPORTANT: Be sure to use my supplied version of the mxCopyPtrToCharacter routine, since the MATLAB supplied version in their API does not work. My version is listed at the end of the posted file.
Fortran Syntax
character*128 function mxGetClassName(pm)
mwPointer, intent(in) :: pm
Requires
#include "fintrf.h"
Arguments
pm
Pointer to any mxArray variable.
Description
Call mxGetClassName to determine the class of an mxArray. The class of an mxArray identifies the kind of data the mxArray is holding. For example, if pm points to a logical mxArray, then mxGetClassName returns logical.
This drop-in replacement routine fills the trailing part of the return string with blanks.
In addition to the routine itself, I have included a test driver routine, test_mxGetClassName.f and an associated file test_mxGetClassName.m. After running mex -setup and selecting a Fortran compiler, simply issue the command test_mxGetClassName(variable) and the mex function will self-build and then execute.
Cite As
James Tursa (2021). Fortran mex routine mxGetClass. | https://it.mathworks.com/matlabcentral/fileexchange/25406-fortran-mex-routine-mxgetclassname?s_tid=prof_contriblnk | CC-MAIN-2021-43 | refinedweb | 237 | 50.23 |
Additions to the .NET Compact Framework for Xbox 360
XNA Game Studio 2.0
The .NET Compact Framework for Xbox 360 implements a subset of the .NET Compact Framework and adds the following namespaces, types, or members.
New Methods
SetProcessorAffinity Method
Currently, the .NET Compact Framework for Xbox 360 adds just one additional method, to the System.Threading.Thread class.
The SetProcessorAffinity method sets the processor or hardware thread on which a software thread will execute (the thread's processor affinity). The Xbox 360 has six hardware threads (two on each of three cores); four of these can be used by applications. SetProcessorAffinity has the following signature:
Show: | http://msdn.microsoft.com/en-US/library/bb203911(v=xnagamestudio.20).aspx | CC-MAIN-2014-10 | refinedweb | 108 | 59.7 |
There is an array of strings in this format:
r = [["Name - Version - Author - Message"],[..],..]
from itertools import groupby
m = map(lambda x: x.split(" - ", 3), r)
group = groupby(m, lambda y: y[0]) # group by name
dot = re.compile('\.')
# "Names" have to be changed from first.last to first-last
output = map(lambda (n,g): (dot.sub('-', n), g), group)
for name,grp in output:
print list(grp)
grp
Py2's
map is eager, while the groups produced by
groupby are lazy. As soon as you iterate to the next group from
groupby, the previous group becomes invalid (the underlying iterator is advanced past it).
You have two options:
mapfunction
The former is easy:
from future_builtins import map
which gets you the Py3 version of
map (which returns a lazy generator, not an eagerly filled sequence).
As is the latter, you just wrap
g in the
list (or if you prefer,
tuple) constructor:
output = map(lambda (n,g): (dot.sub('-', n), list(g)), group)
Side-note: If you're using
map with
lambdas, it's going to be slower than just using the more Pythonic list comprehensions or generator expressions. If you need a
lambda to use
map (or
filter), don't use
map/
filter, the listcomp or genexpr equivalent will always be faster.
So if you really need the speed, use C built-ins for the mapping functions when available, otherwise, use list comps or genexpr.
Example:
from future_builtins import map # Generator based avoids temporary lists from operator import itemgetter, methodcaller m = map(methodcaller('split', " - ", 3), r) # Or with genexpr: m = (x.split(" - ", 3) for x in r) group = groupby(m, itemgetter(0)) # group by name # No good way to do this without lambda, so use listcomp or genexpr output = [(dot.sub('-', n), list(g)) for n, g in group] | https://codedump.io/share/0SQ4U6WndCqO/1/python-map-on-a-group | CC-MAIN-2017-13 | refinedweb | 301 | 61.56 |
This defines the Use class. More...
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/Support/CBindingWrapping.h"
#include "llvm/Support/Compiler.h"
#include <cstddef>
#include <iterator>
Go to the source code of this file.
This defines the Use class.
The Use class represents the operand of an instruction or some other User instance which refers to a Value. The Use class keeps the "use list" of the referenced value up to date.
Pointer tagging is used to efficiently find the User corresponding to a Use without having to store a User pointer in every Use. A User is preceded in memory by all the Uses corresponding to its operands, and the low bits of one of the fields (Prev) of the Use class are used to encode offsets to be able to find that User given a pointer to any Use. For details, see:
Definition in file Use.h. | http://llvm.org/docs/doxygen/html/Use_8h.html | CC-MAIN-2017-17 | refinedweb | 148 | 65.93 |
Note: A more recent article might provide better results. Check out this one first
It sounds sensationalist but it's true.
One of the projects I'm working on has an Angular 8 frontend with over 1000 unit/component tests. These used to all run in Karma and take around 15mins but now they take about 1 min.
But why?
What fast tests not good enough for you?
Some other things I've been loving:
- Nice error messages
- Easy debugging in VS Code (finally!)
- Really nice auto run and error message plugins for VS code
- Ability to write to disk (Maybe not that useful but I found it handy for some tests)
But how?
Well, let me tell ye a story.
Actually scrap that, you're reading this because you want to convert to jest, maybe you've tried it before and failed, maybe you just want to give it a go - either way let's dig into it.
The approach
If you have a decent sized project, (as with anything in Software) the best way to do it is incrementally.
As we have over 1000 tests, we knew it would take a while to convert them and couldn't do the "big bang" approach as we have about 5 different teams working on the app at any one time - we knew we'd need to run karma and jest side-by-side for a period of time. For us, this ended up being nearly a week but it could have taken way longer!
We naturally are following best software dev practices, so at the end of each step we should be able to create a pull request, run our build, tests and merge to master safely.
Just remember, this is a marathon not a sprint (pardon the pun). As soon as you get a test suite/file passing, commit it. Don't commit broken tests (sounds obvious but you can forget this in the heat of a conversion like this). And don't forget to enlist the help of your fellow developers. This will affect them too so they will want to help out - let them!
With this in mind, our basic approach was this:
- Install jest
- Get the first test running with Jest (perhaps a brand new test)
- Migrate an old test suite/file, using what we've learnt
- Write a script to migrate an old suite (based on the manual process we just went though)
- Migrate the next test suite using the script, adding anything to the script that is missing
- Rinse & Repeat until all the tests are migrated.
Remember, as soon as a test is green -> commit it!
(Jests
--onlyChanged flag is very handy here)
Getting started
We start by setting up the jest basics.
Install it:
npm install --save-dev jest @types/jest jest-preset-angular glob @angular-builders/jest
Create a
jest.config.js (for Angular) in the project folder:
var preset = require("jest-preset-angular/jest-preset"); module.exports = { ...preset, preset: "jest-preset-angular", setupFilesAfterEnv: ["./setupJest.js"], testMatch: ["**/*.test.ts"], globals: { ...preset.globals, "ts-jest": { ...preset.globals["ts-jest"], tsConfig: "src/tsconfig.test.json", isolatedModules: true, }, }, };
Create a
setupJest.js file with a single import (you may add others later):
import "jest-preset-angular/setup-jest";
Create a
src/tsconfig.test.json for jest:
This should be very similar to your main tsconfig, but with jest types added.
{ "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/spec", "baseUrl": "./", "module": "commonjs", "types": ["jest", "node", "jest-extended"] }, "files": ["polyfills.ts"], "include": ["**/*.test.ts", "**/*.d.ts", "../setupJest.ts"] }
If you use
jasmine.createSpy or
jasmine.createSpyObj, to aid in the migration, you may need a create-spy.ts:
export function createSpyObj<T>( baseName: string | (keyof T)[], methodNames?: (keyof T)[] ): jest.Mocked<T> { if (!methodNames) { methodNames = Array.isArray(baseName) ? baseName : []; } const obj: any = {}; for (let i = 0; i < methodNames.length; i++) { obj[methodNames[i]] = jest.fn(); } return obj; } export const createSpy = ( baseName? ) => { return jest.fn(); }
Import this where ever you have broken tests (after running the migration script) relating to creatSpy or createSpyObj.
In order to get jest to actually run, you'll need to create a new test config for karma in your
angular.json and replace the existing one with jest:
"test": { "builder": "@angular-builders/jest:run", "options": { "tsConfig": "<rootDir>/src/tsconfig.test.json" } },
If you simply replace karma with jest, you will not be able to run karma and jest tests side-by-side!
Instead, rename the existing "test" config in
angular.json to "karma:
Then add another script to your
package.json
"test-karma": "ng run <you project>:karma"
From now on,
jest will run your jest tests and
npm run test-karma will run the leftover karma tests.
Your npm test script should now look like this:
"test": "ng test && npm run test-karma"
Visualising Progress
Since this is a big job, we want to see some progress and get others involved, so having a script that outputs the percentage of tests that have been converted is also a really good morale boost.
Here is the script we used. We simply ran it at the end of our builds.
Create a file and name it something painfully obvious, like
check-progress.js:
var glob = require("glob") Reset = "\x1b[0m" FgRed = "\x1b[31m" FgGreen = "\x1b[32m" FgYellow = "\x1b[33m" FgWhite = "\x1b[37m" let specs = glob.sync("src/**/*.spec.ts"); let tests = glob.sync("src/**/*.test.ts"); console.log(FgYellow, `${specs.join('\n')}`, Reset) if (specs.length) { console.log(FgRed, specs.length + " slow karma tests") } else { console.log(FgGreen, 'Wooooooooooooooooooooo! Jest conversion complete!') } console.log(FgWhite, tests.length + " fast jest tests") console.log(FgGreen, (tests.length * 100 / (tests.length + specs.length)).toFixed(2) + "% complete in switching tests to jest", Reset)
Then just run
node check-progress.js
Finally, your npm test script should now look like this:
"test": "ng test && npm run test-karma && node check-progress.js"
Plugins
If you are using
VS Code, you may find the plugins
Jest and
Jest Runner very handy for running and also debugging your tests (Finally!).
The actual migration
With all our setup out of the way, we should be able to start incrementally converting tests.
There are tools out there like
jest-codemods that are meant to do the conversion for you but we didn't have any luck with this, so we built our own. Below is the simple script we used. When we found a case or type of test it couldn't handle, we simply added to the script. You will likely need to continue that pattern for your tests, but this might be a good start.
Note that since we want to run karma specs alongside jest tests (until we've finished converting all the tests), we have chosen the convention of
spec.ts for karma tests and
test.ts for jest tests. The script below will, after conversion, rename the spec to
*.test.ts so your git diff will likely show a bunch of deleted files (the spec.ts files). For this reason it's probably best to just run this on a single test file to start with.
Create a file called
convert-to-jest.js:
var fs = require('fs') var filename = process.argv[2] if (!filename) { let specs = require('glob').sync("src/**/*.spec.ts"); for (spec of specs) { if (!spec.includes('pact')) { convertToJest(spec); } } } else { convertToJest(filename); } function convertToJest(filename) { if (!filename.startsWith('C:')) { filename = './' + filename } fs.readFile(filename, 'utf8', function (err, data) { if (err) { return console.log(err); } var result = data; result = result.replace(' } from \'@ngneat/spectator\';', ', SpyObject } from \'@ngneat/spectator/jest\';'); result = result.replace('} from \'@ngneat/spectator\';', ', SpyObject } from \'@ngneat/spectator/jest\';'); result = result.replace(/SpyObj</g, 'SpyObject<'); result = result.replace(/\.and\.returnValue/g, '.mockReturnValue'); result = result.replace(/\.spec\'/g, '.test'); result = result.replace(/jasmine\.SpyObj/g, 'SpyObj'); result = result.replace(/jasmine\.createSpy/g, "createSpy"); result = result.replace(/spyOn/g, 'jest.spyOn'); result = result.replace(/spyOnProperty/g, 'spyOn'); result = result.replace(/expect\((.*)\.calls\.first\(\)\.args\)\.toEqual\(\[(.*)\]\);/g, 'expect($1).toHaveBeenCalledWith($2);') result = result.replace(/expect\((.*)\.calls\.any\(\)\)\.toBe\((.*)\);/g, 'expect($1).toHaveBeenCalledWith($2);'); result = result.replace(/expect\((.*)\.calls\.mostRecent\(\)(\.args\[.*\])?\)\.toEqual\((.*)\);/g, 'expect($1).toHaveBeenCalledWith($2);'); result = result.replace(/expect\((.*)\.calls\.count\(\)\)\.toBe\((.*)\);/g, 'expect($1).toHaveBeenCalledTimes($2);'); result = result.replace(/expect\((.*)\.calls\.count\(\)\)\.toEqual\((.*)\);/g, 'expect($1).toHaveBeenCalledTimes($2);'); result = result.replace(/\.calls\.first\(\).args/g, '.mock.calls[0].args'); result = result.replace(/and.callFake/g, 'mockImplementation'); // result = result.replace(/createService\(/g, 'createServiceFactory('); // result = result.replace(/createService,/g, 'createServiceFactory,'); if (result.includes('createSpyObj')) { result = result.replace(/jasmine\.createSpyObj/g, 'createSpyObj'); result = result.replace(/createSpyObject/g, 'createSpyObj'); var numberOfSlashesinFilename = (filename.replace('./src/app/', '').match(/\//g) || []).length; var prefix = "./" for (var i = 0; i < numberOfSlashesinFilename; i++) { prefix += "../" } result = 'import { createSpyObj } from \'' + prefix + 'shared/testing/SpyObj\';\r\n' + result; } result = result.replace('import SpyObj = SpyObj;', ''); result = result.replace('import Spy = jasmine.Spy;', ''); result = result.replace('import createSpyObj = createSpyObj;', ''); result = result.replace(/ Spy;/g, ' jest.SpyInstance;'); result = result.replace(/jasmine\.Spy;/g, 'jest.SpyInstance;'); if (!result.includes('@ngneat/spectator') && result.includes('SpyObject')) { result = 'import { SpyObject } from \'@ngneat/spectator/jest\';\r\n' + result; } if (result.includes('MatDialog') && !result.includes('@angular/material/dialog')) { result = result.replace(/import \{(.*)MatDialog, (.*)\}/g, 'import {$1$2}'); result = result.replace(/import \{(.*)MatDialogModule, (.*)\}/g, 'import {$1$2}'); result = result.replace(/import \{(.*)MatDialogModule(.*)\}/g, 'import {$1$2}'); result = result.replace(/import \{(.*)MAT_DIALOG_DATA, (.*)\}/g, 'import {$1$2}'); result = result.replace(/import \{(.*)MatDialogRef, (.*)\}/g, 'import {$1$2}'); result = 'import { MatDialog, MatDialogModule, MAT_DIALOG_DATA, MatDialogRef } from \'@angular/material/dialog\';\r\n' + result; } if (result.includes('withArgs')) { result = result.replace(/(.*)\.withArgs\((.*)\)\.mockReturnValue\((.*)\)/g, `$1.mockImplementation(flag => { switch (flag) { case $2: return $3; } })`); } result = result.replace(/jest\.jest/g, 'jest'); let newFile = filename.replace('.spec.ts', '.test.ts'); fs.writeFile(newFile, result, 'utf8', function (err) { if (err) return console.log(err); console.log('Successfully wrote ' + newFile); if (newFile != filename) { fs.unlinkSync(filename); } }); }); }
You'll just need to run:
node convert-to-jest.js <optional path to specific test>
The interesting bit
Now we get to the interesting bit - running the test.
Assuming you've setup your
angular.json for jest correctly, you should be able to just run
ng test.
I call this "the interesting bit" because I can't really give you much more guidance if it doesn't work. You'll need to figure out why your tests aren't working, for yourself. Of course, if you get lucky and they just work, it's time to convert the next test!
You may also find that if you bulk convert all the tests, there may be some that "just work". If this is the case, you can simply commit these and move on with the rest. You'll also find one command very handy:
ng test --onlyChanged
This is git aware and only runs tests that have changes sitting uncommitted in your git repo. You will find this very handy if you try to bulk convert your tests.
Also since jest outputs a lot of error info, when there are failures, you may want to additionally add:
ng test --onlyChanged --bail
This means that jest will stop on the first test failure, allowing you to focus on that.
Armed with these simple techniques alone, you should be able to convert a bulk of your tests quite quickly.
Results (Check my maths)
Our builds used to take about 15mins to run 1200 tests. After converting to jest our tests now take about 1.5mins. Thats a change from 80 test/min up to 800 test/min - 1000% faster! Ok technically I could just say 10x faster but bigger numbers are better right?
Discussion (17)
Hello, I do not doubt about the benefits, but I have one question when I read at the results. If this is so fast why is it not the default test runner packaged with Angular ? Are there any hidden tradeoffs when using jest instead of Karma ?
Hmm definitely a fair question. I'd say that the tradeoffs I've noticed relate to the fact that you are not running in a real browser (it uses jsdom).
This means that:
From my perspective, despite this, the trade-off has been worth it so far for my team.
although these things have been around a while, for example Web Components support in jsdom
Awesome post! Thanks for that!
Helped me a lot come with a strategy on migrating to Jest.
I have an Angular application with a bit more than 3000 tests so that's gonna be interesting.
One small remark, in the jest.config.js file this is the correct value for setupFilesAfterEnv:
Also, if you have aliases, I also had to declare them here like this:
Nice! Yep you can reference that setup-jest directly.
If you need to have further customization, you can create your own setup.ts and import that into it.
Nice one! Well explained and would be a massive time saver for anyone else in the same situation!
Checking your maths... you start at 100% and the final speed is 1000% which makes it 900% faster, right? But still pretty fast. I guess. 😜
Bahaha right you are!
Dylan,
You're awesome. I just used your guide to switch from Karma to Jest. I used Jest for the first time in another Angular project and loved how easy it was to create and manage tests. I couldn't wait to swap our karma tests out for it. I just updated angular in one of our projects then used this guide to switch over. Very clear and concise. Thanks a bunch!
You're welcome! Glad it could be of use!
What am i doing wrong? :-) Angular 9 app + 400 tests approx, 8 core CPU.
Karma runs in ~1m 20sec
Jest runs in ~40sec.
That makes Jest two times faster but:
It runs multiple node instances and takes all my CPU power. Literally I can't run anything else. The reason i think it's forced to compile multiple times because of many node instances.
I can't run some of my tests in Jest because they depend on WebRTC and i can hardly mock it. There's a small number of failed tests in Jest that i need to review as well.
That doesn't look like an ultimate solution for everybody.
Hmm yep I think thats definitely fair. Due to the fact that Jest runs jsdom and not a real browser, there is definitely some things it won't be able to test properly, I suppose WebRTC is one of them.
I have seen some issues in the jest github repo recently about jest slowing down in recent versions.. perhaps its related?
If you are having issues with speed you could try running sequentially: jestjs.io/docs/en/troubleshooting#...
Hi Dylan, thank you for this guide. I used a while ago back when we were using Angular 9 and it made such a big difference on execution time for our tests. I have however updated to Angular 10 and updated Jest dependencies alongside and have found an odd behaviour: when you do not provide a stub for a service used in the component, the test hangs indefinitely. I have raised an issue with jest-preset-angular but I was wondering if you have seen this behaviour before:
Thanks in advance.
EDIT:
It turns out it has to do with the Jest 26, and I believe some version after 26.0.1, because when I performed the migration, my package-lock was stamped with 26.0.1 dependant versions and if you install Jest ^26.0.1 now, you end up with 26.4+. I created this other branch with the Jest version on 25 and the problem no longer happens.
github.com/gustavobmichel/angular-...
Sorry only just saw this but good to hear it sounds like you've figured out your issue. Speaking of jest versions, jest 27 is out now and seems to be ever so slightly faster (though I haven't run my tests enough to be sure how much faster yet!)
What about using JSDOM (like jest does) to run tests on karma and jasmine? Will it still go slower than jest?
I've never tried but I'd love to hear if you try it!
That could certainly makes this whole process simpler if it has similar results!
This was incredibly helpful. Having many thousands of tests, we needed a way to gradually migrate to Jest, and this gave us what we need to get started.
Excellent to hear! Glad it was useful. Did you find any quirks/differences that would be worth updating the article with? | https://practicaldev-herokuapp-com.global.ssl.fastly.net/dylanwatsonsoftware/make-your-angular-tests-1000-faster-by-switching-from-karma-to-jest-1n33 | CC-MAIN-2022-33 | refinedweb | 2,764 | 59.4 |
An interesting old piece of writing
Most of the time, I cringe when I read something that I write a long time ago! I was reading this, though, and I actually still agree with something that I said several years ago. It’s even still a little relevant, as Spring is still popular in the Java world. I should warn you I haven’t kept up with recent developments in Spring.
For the sake of posterity, the following is what I wrote several years ago.
Last night, I went to see someone talk about Spring at the Pikes Peak Java Developer’s Group.
I will gladly join my voice with the loudest of the critics of Enterprise JavaBeans. Spring is supposed to be the way to avoid EJBs; the way to write simple, lightweight Java applications without all the stifling rules and framework-ness of EJBs. As a result, you might expect I’ll be a big fan of Spring. I hoped that I would be.
Spring is fundamentally built around beans, which are generally supposed to be described in an XML file. The beans are often called “POJOs”, which is a (fairly commonly used, and not invented by Spring) acronym for “plain old Java objects.” Now I start to get worried. If we were really working with plain old Java objects, Spring would call them “objects”. As a general rule, when someone says POJO, you can assume that they are either: (a) fundamentally uncomfortable with doing straight-forward object oriented design, because they are framework-dependent; or (b) talking to people who meet the description in (a). But Spring, in fact, is largely talking to people who are formerly dependent on J2EE application servers. So I move on.
Here’s the interesting part about that XML file, though. This XML file is basically an XML mapping of a limited subset of Java. There are elements for creating beans, with attributes for parameters. There are elements for specifying the constructor arguments for those beans, and for setting properties of those beans.
At this point, though, I was loudly wondering the following: why aren’t we writing this in Java?
The answers I heard:
“You don’t have to write initialization code.”
“This file can be maintained by managers who don’t know Java.”
“You can change your error handling strategy without changing a single line of code.”
All of these statements are complete B.S.! XML is nothing more than a framework for defining file formats. When XML is used to describe the process for creating an object, it qualifies as code in my book, and in the book of most other reasonable people.
Let me put this another way. I can open up the Java Language Specification, 3rd Edition to section 18.1, and I see a BNF grammar for Java. Given a few hours, I can write a simple application to convert this grammar into a DTD or XML Schema. Give me less than a week, and I’ll have javac running to parse the grammar from my XML format. Now, can managers who don’t know Java create powerful applications easily? After all, they possess this magical ability to express things if they are represented in XML, right?
“You can make a change without recompiling.”
This isn’t a good thing. The compiler performs important work, such as checking to make sure that we aren’t trying to use types that don’t exist. Yes, I hear you saying that there is the Spring IDE instead, which runs inside of Eclipse and checks that for us — wait a second; if we’re editing this file in Eclipse, isn’t it impossible to save a file without recompiling?!? (The answer is no, but everyone I know leaves the automatic build feature on.)
More to the point… Have we regressed from automated build procedures so much that the prospect of running the compiler as a part of deployment configuration scares us? Even more to the point, why are we willing to use other tools (such as the Spring IDE validator that checks for references to undefined classes) but not compilers?
“You can do lazy initialization.”
So can Java. In fact, one of the more useful little-known language features in Java is deferred class loading. If I declare a static fields in a class, they don’t get created until the first time that class is accessed. The correct way to do a lazily initialized object in Java is this:
public class MyClass
{
public static final MyType myObject
= new MyObject(someParameters);
}
That’s it! All done.
“There are tools to view this XML file visually.”
This is the first response that actually makes some sense. It’s true; there is the Spring IDE, and it can display (and, in the future, edit) this XML file visually as UML-ish boxes on the screen. There’s quite a cost, though, for this advantage. Perhaps the time would be better spent on producing good CASE tools.
What do we lose by using XML?
For one thing, it requires specialized tools to verify things that the average compiler would check, such as that any types used in the file are actually defined. More importantly, the average compiler –and especially IDE — would do a better job. If I build a source file in Eclipse, I can right-click on the method or field declaration and select the option to search for references in the workspace. If I define a bean only to be referenced from several other beans, I can make it private and the compiler in Eclipse will warn me if I don’t use it. If I use a deprecated constructor or method, I’ll get a warning. I could go on and on.
Second, it’s less readable. If XML to create arbitrary Java objects were more readable than Java, we’d write our code in an XML application. That prospect would scare me, and it would probably scare anyone else, too… even the most ardent Spring fanatic.
Third, you lose type-safety. There’s a whole slew of Spring-specific rules out there about resolving types when creating Java objects from the inherently untyped XML format. In the end, though, it comes down to this. Every fundamental configuration item spends at least some time as a string. This other important point: it’s absolutely impossible to ever get type-safe general collections from Spring.
Here’s the killer, though. If I take that XML file from a Spring project and translate it into Java source code, your average team code review would reject it. It’s not good code. It’s as simple as that. We are not just wrapping Java in a proprietary XML mapping; we’re wrapping bad Java in a proprietary XML mapping.
As a reaction to EJBs, Spring 95% of the unnecessary complexity of Enterprise JavaBeans. EJB developers seem to look at Spring and get really excited. It’s an alternative framework that’s less complicated. On the other hand, there is a fairly well-established community of Java developers who have spent the last seven years or so developing enterprise-class applications in Java without EJBs. To these people, Spring needs to solve specific programming problems to justify its existence and use. Otherwise, it’s just deployment hassle.
So what does Spring do?
One thing it does, and perhaps the single most important thing, is “dependency injection”. Dependency injection is a buzz word. Five years ago, many programmers would have described it using this alternate phrase: “design that is at least mediocre”.
Spring also suggests a few interesting third-party products. If someone is writing an application with Spring, then we assume that they are at least considering using Hibernate if they’ve got database access to take care of. We assume that they are looking at possible uses for aspects to remove some types of duplicated code.
Promoting third-party products can be quite useful, and teaching good design even more so. Nevertheless, it doesn’t justify creating a new framework! Robert Glass, in his book Facts and Fallacies of Software Engineering, marvels at the mindset that could lead someone to criticize stifling software methodologies by inventing a new methodology. The same appears to be true of Spring. It’s complaining about stifling frameworks by inventing a new framework.
It could be that this is a necessary intermediate step. After all, it is definitely true that it’s easier to convince a programmer to evaluate a new tool like Spring than to re-evaluate his or her design skills. If part of “learning Spring” is to start using basic modular design and separation of concerns (a.k.a., “dependency inversion”), then Spring can help. However, when it leaves a residue of XML-parsed JavaBeans in its wake, one is forced to wonder if the medicine is worse than the disease, or at least if there might be a less invasive cure. | http://cdsmith.wordpress.com/2007/05/27/an-interesting-old-piece-of-writing/?like=1&source=post_flair&_wpnonce=c1ce40f6e1 | CC-MAIN-2013-20 | refinedweb | 1,498 | 64.51 |
Sometimes a client and a service do not share the same types. They can still pass data to each other as long as the data contracts are equivalent on both sides. Data Contract Equivalence is based on data contract and data member names, and therefore a mechanism is provided to map types and members to those names. This topic explains the rules for naming data contracts as well as the default behavior of the Windows Communication Foundation (WCF) infrastructure when creating names.
Basic Rules
Basic rules regarding naming data contracts include:
A fully-qualified data contract name consists of a namespace and a name.
Data members have only names, but no namespaces.
When processing data contracts, the WCF infrastructure is case-sensitive to both the namespaces and the names of data contracts and data members.
Data Contract Namespaces
A data contract namespace takes the form of a Uniform Resource Identifier (URI). The URI can be either absolute or relative. By default, data contracts for a particular type are assigned a namespace that comes from the common language runtime (CLR) namespace of that type.
By default, any given CLR namespace (in the format Clr.Namespace) is mapped to the namespace "". To override this default, apply the ContractNamespaceAttribute attribute to the entire module or assembly. Alternatively, to control the data contract namespace for each type, set the Namespace property of the DataContractAttribute.
Note
The ""namespace is reserved and cannot be used as a data contract namespace.
Note
You cannot override the default namespace in data contract types that contain
delegate declarations.
Data Contract Names
The default name of a data contract for a given type is the name of that type. To override the default, set the Name property of the DataContractAttribute to an alternative name. Special rules for generic types are described in "Data Contract Names for Generic Types" later in this topic.
Data Member Names
The default name of a data member for a given field or property is the name of that field or property. To override the default, set the Name property of the DataMemberAttribute to an alternative value.
Examples
The following example shows how you can override the default naming behavior of data contracts and data members.
//. } } namespace Contoso.OrderProc { [DataContract] public class PurchaseOrder { // This data member is named "Amount" by default. [DataMember] public double Amount; // The default is overridden to become "Address". [DataMember(Name = "Address")] public string Ship_to; } // The namespace is the default value: // // The name is "PurchaseOrder" instead of "MyInvoice". [DataContract(Name = "PurchaseOrder")] public class MyInvoice { // Code not shown. } // The contract name is "Payment" instead of "MyPayment" // and the Namespace is "" instead // of the default. [DataContract(Name = "Payment", Namespace = "")] public class MyPayment { // Code not shown. } }
'. End Class End Namespace Namespace Contoso.OrderProc <DataContract()> _ Public Class PurchaseOrder ' This data member is named "Amount" by default. <DataMember()> _ Public Amount As Double ' The default is overridden to become "Address". <DataMember(Name:="Address")> _ Public Ship_to As String End Class ' The namespace is the default value: ' ' The name is "PurchaseOrder" instead of "MyInvoice". <DataContract(Name:="PurchaseOrder")> _ Public Class MyInvoice ' Code not shown. End Class ' The contract name is "Payment" instead of "MyPayment" ' and the Namespace is "" instead ' of the default. <DataContract(Name:="Payment", [Namespace]:="")> _ Public Class MyPayment ' Code not shown. End Class End Namespace
Data Contract Names for Generic Types
Special rules exist for determining data contract names for generic types. These rules help avoid data contract name collisions between two closed generics of the same generic type.
By default, the data contract name for a generic type is the name of the type, followed by the string "Of", followed by the data contract names of the generic parameters, followed by a hash computed using the data contract namespaces of the generic parameters. A hash is the result of a mathematical function that acts as a "fingerprint" that uniquely identifies a piece of data. When all of the generic parameters are primitive types, the hash is omitted.
For example, see the types in the following example.
[DataContract] public class Drawing<Shape, Brush> { // Code not shown. } [DataContract(Namespace = "urn:shapes")] public class Square { // Code not shown. } [DataContract(Name = "RedBrush", Namespace = "urn:default")] public class RegularRedBrush { // Code not shown. } [DataContract(Name = "RedBrush", Namespace = "urn:special")] public class SpecialRedBrush { // Code not shown. }
<DataContract()> _ Public Class Drawing(Of Shape, Brush) <DataContract([Namespace]:="urn:shapes")> _ Public Class Square ' Code not shown. End Class <DataContract(Name:="RedBrush", [Namespace]:="urn:default")> _ Public Class RegularRedBrush ' Code not shown. End Class <DataContract(Name:="RedBrush", [Namespace]:="urn:special")> _ Public Class SpecialRedBrush ' Code not shown. End Class End Class
In this example, the type
Drawing<Square,RegularRedBrush> has the data contract name "DrawingOfSquareRedBrush5HWGAU6h", where "5HWGAU6h" is a hash of the "urn:shapes" and "urn:default" namespaces. The type
Drawing<Square,SpecialRedBrush> has the data contract name "DrawingOfSquareRedBrushjpB5LgQ_S", where "jpB5LgQ_S" is a hash of the "urn:shapes" and the "urn:special" namespaces. Note that if the hash is not used, the two names are identical, and thus a name collision occurs.
Customizing Data Contract Names for Generic Types
Sometimes, the data contract names generated for generic types, as described previously, are unacceptable. For example, you may know in advance that you will not run into name collisions and may want to remove the hash. In this case, you can use the Name property of the
DataContractAttribute attribute to specify a different way to generate names. You can use numbers in curly braces inside of the
Name property to refer to data contract names of the generic parameters. (0 refers to the first parameter, 1 refers to the second, and so on.) You can use a number (#) sign inside curly braces to refer to the hash. You can use each of these references multiple times or not at all.
For example, the preceding generic
Drawing type could have been declared as shown in the following example.
[DataContract(Name = "Drawing_using_{1}_brush_and_{0}_shape")] public class Drawing<Shape, Brush> { // Code not shown. }
<DataContract(Name:="Drawing_using_{1}_brush_and_{0}_shape")> _ Public Class Drawing(Of Shape, Brush) ' Code not shown. End Class
In this case, the type
Drawing<Square,RegularRedBrush> has the data contract name "Drawing_using_RedBrush_brush_and_Square_shape". Note that because there is a "{#}" in the Name property, the hash is not a part of the name, and thus the type is susceptible to naming collisions; for example, the type
Drawing<Square,SpecialRedBrush> would have exactly the same data contract name.
See Also
DataContractAttribute
DataMemberAttribute
ContractNamespaceAttribute
Using Data Contracts
Data Contract Equivalence
Data Contract Names
Data Contract Versioning | https://docs.microsoft.com/de-de/dotnet/framework/wcf/feature-details/data-contract-names | CC-MAIN-2017-43 | refinedweb | 1,090 | 55.13 |
Asked by:
Silverlight xap caching?
I'm having a problem with updates to a silverlight application I deploy not being downloaded. If I put a xap on a web site and then goto the URL and use it for a while in IE, then deploy a new version of the xap and go back to the website in IE the browser never gets the updated XAP file until I delete my entire browser cache.
I've gone to the project and tried incrementing the version of the assembly etc etc and nothing works. Anyone know how to version xaps like XBAPS use to be versioned?
Question
All replies
I'm also having this problem. Happens regardless of whether I hit my app thru an html or aspx files (which makes sense because it downloads the xap with a separate request).
Maybe there's a way to configure IIS to issue special response headers that indicate cache directives for .xap requests?
You can turn the Enable Content Expiration HTTP header option on for your XAP file. Open IIS Manager, goto Default Web Site and find your Web site for the silverlight project. Find the XAP file under ClientBin. Goto the properties page of the XAP file, on HTTP Headers Tab, Turn on "Enable Content Expiration", click the "Expire Immediately" radio button. Save the change.
This way the new XAP (only there is a new XAP) will get downloaded when you refresh your page without having to close the browser.
Why the silverlight is not caching when I'm making a call through passing InitParameters that value is coming from Request...?
I have answered your question in this post.
Okay. I will paste the answer here again...
No. It won't download xap file everytime if you cache it.
For example:
Application Name: SL2Cache and SL2Cache_Web
SL2CacheTestPage.aspx
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
TagPrefix="asp" %>
<%@ OutputCache Duration="60" VaryByParam="None" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" style="height:100%;">
<head runat="server">
<title>Test Page For SL2Cache</SL2Cache.xap" InitParameters="id=00001" Version="2.0" Width="100%" Height="100%" />
</div>
<div> <% = System.DateTime.Now.ToString () %></div>
</form>
</body>
</html>
App.xaml.cs
private void Application_Startup(object sender, StartupEventArgs e)
{
// Load the main control
string id = e.InitParams["id"];
this.RootVisual = new Page (id);
}
Page.xaml
<UserControl x:Class="SL2Cache.Page"
xmlns=""
xmlns:
<Grid x:
<TextBlock x:
</Grid>
</UserControl>
Page.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SL2Cache {
public partial class Page :UserControl {
public Page()
{
InitializeComponent ();
}
public Page(string arg)
{
InitializeComponent ();
displayTextBlock.Text = arg;
}
}
}
Steps to Test:
1. Set InitParameters="id=00001" in SL2CacheTestPage.aspx
2. Run the application. I will see 00001 in Silverlight Content.
3. Close the brower.
4. Change InitParameters="id=1111" in SL2CacheTestPage.aspx
5. Run the application again.
I will still able to see "00001" . It's because it cached it.
You can test the different between ASP.NET page with cache and without cache by adding or removing this line "<%@ OutputCache Duration="60" VaryByParam="None" %>" from SL2CacheTestPage.aspxHope it helps.
This way the new XAP (only there is a new XAP) will get downloaded when you refresh your page without having to close the browser.
Mmmm....
This means that next time the user hits the page it will download the new xap file, isn't?
Or only if newer one no matter if he/she closes the browser and later come back to the page?
On the other hand, is some way to set such header without IIS manager? In web.config? some kind of manifest in the xap file?
I haven't access to it because I use hosting service.
Regards.
I have one question.
I am creating big silverlight application for my website.
I am expecting the size of XAP to be 3-4 MB ( may be ) at the end of project.
What will happen
- When user clicks and opens my site
- XAP file will be downloade to the client
- It will take time to download first time as I can understand it has big size.
- Client works on my site and close the browser
- After 2 days, again logs in.
- WILL XAP file downloaded again or not ? Or Client will use from cache.
I am expecting new release of my silverlight application at every three month after first release.
- Now, I have released new version
- Client comes again and logs in
- Will XAP file be downloaded automatically again ? OR client will still see old XAP's SL content.
Basically, I am not sure that silverlight is downloaded XAP file each time or only when it finds change ?
Thanks in advance.
The caching of SL applications gets a bit annoying during development, I've got round it by using a generic handler:
<%@ WebHandler Language="C#" Class="XAPHandler" %>
usingSystem;
usingSystem.Web; public class XAPHandler : IHttpHandler {
context.Response.Expires = -1;context.Response.BufferOutput = false;
context.Response.ContentType ="application/x-silverlight-app"; context.Response.WriteFile(context.Server.MapPath("SLQuake.xap"));
}
}
}
}
Then in my aspx pages, just change the Source attribute to the handler:
<asp:Silverlight
I've used this for Flash development too, SWF files are cached just like XAP files and it causes the same set of headaches. Once the site is developed and deployed, just use the XAP file as normal (without the ashx handler)
The approach of changing XAP name on every deploy is good as well on proxy based internet connections (I got a client that had an "assesine" proxy... no matter what you deployed your XAP would remain cached for ours :-( ).
I use the approach of adding a timestamp to the XAP names (to do that you need to change the XAP name in the Silverlight project properties, and on the web project: aspx OBJECT Tag, XAP File name).
Cheers
Braulio
Here is the approach that I took and it worked quite well. Like everyone else, I had a terrible time and many many hours wasted trying to see why my changes were not taking. I did try changing the Assembly and File version numbers, and the GUID value for the project as well. That did not work for me. What finally worked, was the change my <object> tags from this:
<object type="application/x-silverlight" height="611">
<param name="source" value="/ClientBin/SilverApp.xap" />
.....
</object>
and to something like this:
<object type="application/x-silverlight" height="611">
<param name="source" value="/ClientBin/SilverApp.xap?ignoreme=<%=System.DateTime.Now.ToUniversalTime()%>" />
.....
</object>
Then it worked like a charm everytime.
Brett
Presumably everyone here has the same objective concerning production environment deployments - we want to cache the XAP until such time as we change it.. and when we do change it, we want the new XAP to be distributed first time it is loaded.
We don't want the client to waste time + bandwidth downloading a new identical XAP every time they vist our page.
What is the best way of achiving this? It strikes me that setting content expiry headers in IIS or by code is not a great way as (depending on the setting), I may still get an old XAP or get force a download each time.
Won't the ideas using a dynamic query string with the time in it suffer a similar problem? depending on output caching, everytime time I hit the page presumably it will download the XAP all over again.
Renaming the XAP itself seems perfect except a bit of a hassle. Equally, we could rename a static query string (rather than a dynamic time) inside the .ASPX page each time which seems less of a hassle but still a bit of a pain. (e.g. "/ClientBin/SilverApp.xap?v1" .. v2) etc
Ideally IIS/HTTP would be clever enough to realise the file has changed and force-serve a new one.
More thoughts?
cheers
ewart.
Personally I hate clearing my browser cache all the time! :)
- You could do that if that's what you want. But do notice that my solution does not use the current datetime, so a new download will only be triggered when the XAP file has been written to. That the XAP file has been written to usually means that you have deployed a new version to the IIS.
Hi,
I have another idea to use Web Application Assembly Version Number to use as tag to control the xap fresh download, but it has only one drawback that if used just deploy Xap then it will not work properly.
I have found XAP modified date very much appealing.
Furthermore is there any way to read SilverLight Project dll assembly version in asp.net? so that we can use that as a control tag?
Thanks
You can try this. Replace the object tag in your aspx page with the following:
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<%
string orgSourceValue = @"ClientBin/Your>
Append XAP created data to the value on the Source parameter, this way when you have a new Version of XAP, the new XAP will get downloaded to replace the one in the cache.
Again this is also on my blog..
the solution works great for the main xap file.
But we're using prism and in firefox it sometimes happens that the modules we load in our shell are cached too and it seems I cannot use the same trick on the url of the module xaps, because I cannot change the way prism loads the xap from the server.
anybody with the same issue?
Hello guys,
Is there any update about this issue? I am still concerned about this. What if I changed the SL project assembly number? Would not this be considere a different assembly, consequently invalidating the client browser cache and the file would be downloaded?
For me this seems not to work.... I think that downloading the xap file every time is not also a good way of managing this....
Thank you,
Igor.
Hello,
But in my launcher XAP most of the dll respective to system, microsoft, telerik and our framework respective are common, which hardly change. It is one time download on client side is enough for me.
But I want that only other dll like my control library, XAP respective process dll which I want to download, when ever any change instead of all dll, which hardly will change.
How we can acheive this?
Regards,
Sandeep
You could use MEF in order to achieve that:
- You download your DLL the first time store it cached in isolated storage (you could add a timestamp or check the version).
- Then whenever you start the app you make an asynchronous call to check if there is a newer version of the DLL, in that case grab the DLL from the remote location.
On the other hand, how often do you make that changes? If you use the version trick parameter in the query string you will download your XAP only when you make a new deployment.
This is quite a serious issue for us. We also have more than one xap file since the application is spread over multiple xap files. Any tricks to modify the object tag or other to make sure the initial xap file is correct is only a small part of the solution for us.
The basic requirement is the same as mentioned above - cache as much as possible if the server side copy has not changed, but download immediately after any changes.
Content expiry is only partially solving the problem since the content can only expiry immediately, which means a download every time, or expire after a set period, which means any updates can be skipped for a while.
I've tried to read up on the use of ETags in IIS7 & 7.5 but have not found enough info yet. This seems to be an expiry tag that the server updates when the content updates. Has any tried this with Silverlight with any success.
The answer seems to lie in the fact that the server has to dictate when content expires and not the client or client cache (as with expiries).
ETags anyone?
Which framework are you using for the XAP partitioning?
If it's custom or Prism you can add your own module and in the http call to download the XAP just use as param in the query string the version (you could try to get that value from the XAP, or setup a XAP version numbers xml file and store it in the isolated storage).
Another better option is, instead of relying on the browser to provide you the cached XAP's rely on the isolated storage to do that, there are as well implementations of this kind of caching, but you have to be aware if the app is not OOB by default you only have 2 Mb caching.
HTH
Braulio
- );%>
You can try with this code in your server side page. Its downloading xaps with every new deployment.
);
%>
hi all,
as per one of the above post I enabled Content Expiration HTTP header option on for XAP file by checking "Expire Immediately" radio button.
but with this setting it never caches XAP & downloads every time from sever when I refresh page.
I need to download xap from server only if it newer than xap in cache.
can we acheive this by setting any property in IIS?
regards,
-Shwetank
Have not read the whole thread, but simply changing the value for 'cachepreventer'
is doing the job very well for me :
....
<div id="silverlightControlHost" >
<object id="siliobj" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/zoomBase.xap?cachepreventer=2011.09.20_22"/>
....
Well the .xap file gets downloaded on every page refresh ... in my case the zap file is 7.5mb. huge performance issue, the browser caches the file for a reason ... the solution should be browser should get the new file only after the deployment.
Krish | http://social.msdn.microsoft.com/Forums/silverlight/en-US/51673356-5bc1-43e0-8897-521f12a3bb45/silverlight-xap-caching?forum=silverlightnet | CC-MAIN-2014-35 | refinedweb | 2,375 | 73.58 |
CodePlexProject Hosting for Open Source Software
Hi,
I have 3 different roles (Administrators, Editors and Users) but I only want the pages widget to appear for 2 of them (Administrators and Editors). Is ir possible to hide this widget from Users and people who are not logged in?
Thanks,
Phil
You can use the System.Security.Principal namespace's objects and methods to detect what type of role the current user is in and act accordingly, here's an example
if(Page.User.IsInRole("[ROLENAME]")){
//Code which displays the widget
}
The only role you're going to be able to programmatically look up the name of is the AdministratorRole, I believe, which you can do using this:
if (Page.User.IsInRole(BlogSettings.Instance.AdministratorRole)){
//Code which executes only upon requests from users authenticated as admins...
}
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://blogengine.codeplex.com/discussions/217162 | CC-MAIN-2017-04 | refinedweb | 171 | 55.54 |
Hi,
I made a program for an exercise that is in a book I use to teach myself C++.
The code works, but I would be grateful if someone could have a look and write something about the structure of it. I'm a bit confused as to how member variables and functions are accessed. Sometimes a dot . is used, like in t[0].sn = 1 and sometimes the operator ->, like in head->nl . Could someone explain the difference between these two? I also wonder how I could detect if there is a memory leak?
The task is to make a stack object to hold videotape objects and then to display the videotape objects from the stack.
Seron
Code:// videostacktest.cpp // exercise 4.14 #include "videostack.h" #include "videostack.cpp" #include <string> using namespace std; void main() { const int arraysize = 3; videotape t[arraysize]; // creates a videotape array t[0].sn = 1; // creates three videotapes t[0].title = "The Warriors"; t[0].rp = 10; t[0].cust = "Mr Pink"; t[0].dout = 0; t[0].din = 0; t[1].sn = 2; t[1].title = "Ghost in the shell"; t[1].rp = 10; t[1].cust = "Mr White"; t[1].dout = 0; t[1].din = 0; t[2].sn = 3; t[2].title = "Lord of the rings"; t[2].rp = 15; t[2].cust = "Mr Blue"; t[2].dout = 0; t[2].din = 0; node videotapes; // creates a node (linked list) node* head = 0; // head is a nodepointer with the value 0 node* nl; // creates another nodepointer, (nodelink) videotape* vtp[arraysize]; // creates a videotape-pointer-array // copies videotapes to the stack for(int i = 0; i < arraysize; i++) { vtp[i] = new videotape; // allocates memory for a videotape and stores the address in an array *(vtp[i]) = t[i]; // copies tape information to memory nl = head; // copies the head pointer head = videotapes.add(vtp[i], nl); // passes videotape and node pointers // and returns a pointer to this node, // which becomes the head pointer // the node now contians a videotape pointer // and a node pointer (node link) } // prints videotape info, moves to the next node and // unallocates memory occupied by the nodes while(head != 0) { (*(head->vtp)).print(); // prints the data stored @ head->vtp nl = head->nl; // gets the nodelink from head->nl delete head; // unallocates memory used by node head = nl; // sets head to the node pointed to by nl } // unallocates memory occupied by videotapes for(int i = 0; i < arraysize; i++) delete vtp[i]; // unallocates memory used by videotape data }Code:// videostack.h // exercise 4.14 #include <string> using namespace std; struct videotape { int sn; // serial number string title; int rp; // rental price string cust; // customer int dout; // date out (rented) int din; // date in (returned) void print(); }; struct node { videotape* vtp; // videotape pointer node* nl; // node pointer void initialize(); node* add(videotape* vtp0, node* nl0); };Code:// videostack.cpp // exercise 4.14 #include <iostream> #include <string> using namespace std; void videotape::print() { cout << endl; cout << "s/n:\t\t" << sn << endl; cout << "Title:\t\t" << title << endl; cout << "Rental price:\t" << rp << endl; cout << "Last customer:\t" << cust << endl; cout << "Date rented:\t" << dout << endl; cout << "Date returned:\t" << din << endl; cout << endl; } node* node::add(videotape* vtp0, node* nl0) { node* newnode = new node; // crates a new node and passes the address // created for carrying a pointer to the videotape // and a pointer to the previous node newnode->vtp = vtp0; // passes pointer to the videotape newnode->nl = nl0; // passes pointer to the previous node return newnode; // return nodeaddress } | http://cboard.cprogramming.com/cplusplus-programming/8480-code-structure-program-i-made.html | CC-MAIN-2015-48 | refinedweb | 587 | 74.9 |
Pointers are used to solve many problems in C++. Some C++ tasks are performed more easily with pointers, and other C++ tasks, such as dynamic memory allocation, cannot even be performed without the use of pointers.
As we already know that a variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory.
Let us consider the following code which will print the address of the variables defined –
#include <iostream> int main () { int var1; char var2[10]; cout << "Address of var1 variable: "; cout << &var1 << endl; cout << "Address of var2 variable: "; cout << &var2 << endl; return 0; }
Output:
Address of var1 variable: 0xbfebd5c0 Address of var2 variable: 0xbfebd5b6
A pointer is a variable whose value is the address of another variable. Like any variable or constant, in C++ you must declare a pointer before you can work with it.
The general form of a pointer variable declaration is −
type *var_name;
Here, type is the pointer’s base type; it must be a valid C++ type and var_name is the name of the pointer variable.
Here, all the pointers return a long hexadecimal number that represents the memory address of the variable as shown in the above example.
The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
Report Error/ Suggestion | https://www.studymite.com/cpp/pointers-in-cpp/?utm_source=related_posts&utm_medium=related_posts | CC-MAIN-2020-50 | refinedweb | 236 | 53.55 |
In this article we will learn about CRUD operations in Web API using AngularJS.
In this article, we will learn about CRUD operations in Web API using AngularJS. We will use Visual Studio 2015 to create a Web API and perform the operation. In this project we are going to create a database and a table called tbl_Subcribers which actually contains a list of data. Here we will use Angular JS for all of our client side operations. If you are new to Web API, please read how to retrieve the data from database using Web API here. I am going to explain the complete process in a step by step manner. I hope you will like this. Download the source code
You can always download the source code here: Web API and Angular JS
Background
Yesterday, I got a call from one of my followers. He asked me about Web API, I explained to him all the things I know about the Web API. But he was not convinced with the information I shared through the phone. At last he asked me to write an article about Web API in a simple manner. So I agreed to do so. Here I am dedicating this article to him. I hope he will find this useful.
A Web API is a kind of a framework which makes building HTTP services easier than ever. It can be used almost everywhere including a wide range of clients, mobile devices, browsers, etc. It contains normal MVC features like Model, Controller, Actions, Routing, etc. It supports all HTTP verbs like POST, GET, DELETE, PUT.
Figure: Why Web API
Image Courtesy: blogs.msdn.com
Using the code
We will create our project in Visual Studio 2015. To create a project click File, New, then Project. And select Web API as template.
Figure: Web API Template
Once you have created a new project, your solution explorer will look like this.
Figure: Web API with Angular JS Solution Explorer
As I said, we are going to use AngularJS for our client side operations. So the next thing we need to do is, installing the AngularJS from NuGet packages.
Figure: Installing AngularJS
Now we will create a control in our project.
Figure: CRUD_in_MVC_Using_Web_API_Adding_Control
Now will create a database. Here I am using SQL Server Management Studio with SQL Server Express.
The following is the query to create a database.
Now we can create a table and insert data into it.
The following is the query to create table in database.
Insert data to table
Our database seems to be ready now. Then we can go ahead and create entity in our project.
To create an entity, please follow the steps as in the following images:
Figure: Creating Entity Model 1
Figure: Creating Entity Model 2
Figure: Creating Entity Model 3
Figure: Creating Entity Model 4
Figure: Creating Entity Model 5
Figure: Creating Entity Model 6
Now the time to create an API controller.
Select Empty API Controller as template.
Figure: Web API Controller With Actions
Read Operation
Now you can see some actions are already created for you by default. Cool, right? Now, as of now we will concentrate only on retrieving the data. So please change the method Get as follows.
Before that please do not forget to create an instance for your entity.
And make sure you have added the needed namespaces with the model.
As you can notice that we have selected Empty API Controller instead of selecting a normal controller. There are a few differences between our normal controller and Empty API Controller.
Controller VS Empty API Controller
A controller normally render your views. But an API controller returns the data which is already serialized. A controller action returns JSON() by converting the data. You can get rid of this using API controller.
Find out more: Controller VS API Controller
Now our API is ready for action. So it is time to create another controller and a view. Here I am creating a normal controller with Index view.
Once the view is created, we will create three JS files in the script folder.
Figure: AngularJS Operation FIles
Now we will start our AngularJS part.
Open the file Module.js and create an app.
Here APIModule is the name of our module. Check here for more information.
Open the file Service.js and create a service as follows.
Figure: Get Operation In API Controller
Now open Controller.JS and write the following code:
We are calling the getSubs function which we created in our service. Once we get the data we are assigning it to the $scope.subscriber, so that we can use it in our view.
Now the AngularJS part for retrieving all data is done. Can we do the needed changes in the view now?
Updating View
Open the Index.cshtml view and change it as below.
Please don’t forget to load the needed scripts. Here we have set body as our data-ng-app and table as our ng-controller. We are looping through the data using data-ng-repeat.
If everything is done, we can build the application and see the output.
Figure: Web API Get All Record
So far our READ operation is done. Now we will move into CREATE part.
Create Operation
Firstly, we will concentrate on the view part as of now. Just add the following code to your view.
This will give you an output as follows.
View Design For Create
As you can see, we are firing the function saveSubs() in data-ng-click. So let us see what we need to write in it.
In the Controller.js you need to create a function as below.
Did you saw that we are calling another function which is in our APIService? So now we need to create a function saveSubscriber in Service.js.
So all set, the rest is to create a function in our API Controller.
That’s cool, now you will be able to create data through our API with the help of AngularJS. Now we shall move into UPDATE operation.
Update Operation
Before going to the code part we will do some changes in our table design. We are going to make one field (Mail ID field) editable whenever the user double clicks on it. And of course we will update the edited data to the database whenever user leaves that field. Sounds cool, right? Now please change the view as follows.
The below is the main change we did.
In ng-blur we are calling the function updSubscriber with parameter $event and the current subscriber details. And in ng-dblclick we are calling the function makeEditable with parameter $event which actually holds the UI details and current events.
The following is the code for the function makeEditable in Controller.js,
As you can see we are setting the attribute contenteditable to true using setAttribute function. Now we will look into the function updSubscriber.
Add a function in Controller.js
Add a relative function in Service.js
Now we need to add a function in our Web API controller.
Now you will be able to update your record. What is pending now? Yes, DELETE operation.
Delete Operation
Make some changes in the view as follows.
Now add the new function in Controller.js
Create a service in Service.js now.
Now it is time to create our delete method in Web API controller.
That is all. We did it. Now build your application and you can see the following output:
Happy coding.
Did I miss anything that you may think is needed? Did you try Web API yet? Have you ever wanted to do this requirement? Did you find this post useful? I hope you liked this article. Please share | https://www.c-sharpcorner.com/UploadFile/65794e/web-api-with-angular-js/ | CC-MAIN-2019-35 | refinedweb | 1,297 | 76.93 |
Loading modules com.sencha.gxt.desktopapp.DesktopApp Loading inherited module 'com.sencha.gxt.desktop.Desktop' Loading inherited module 'com.sencha.gxt.ui.GXT' [ERROR] Unable to find 'com/sencha/gxt/ui/GXT.gwt.xml' on your classpath; could be a typo,
GXT Component Tutorial 1 - Basic Grid Colleagues chatting today and start with EXT-GWT tutorial is relatively small. He would like to talk about writing a book, we laugh, I would like to write a book after potential technical not, then write a blog s
This article contains a list of ruby on rails routing examples. If you find you have any questions please leave a comment. Routes are processed from the top of routes.rb down. If a route is matched it will stop processing the routes.rb file and use t
I wrote it myself a simple example of jsf1.2 + EJB3.0, mainly just for study JSF are brothers, for example, is very simple, one would look. Examples of content that is for a staff increase, deleted, changed, for example, includes two projects, one is
Following the vicinity of the DWR framework for Ajax are examples of entry, welcome to download ...............
Examples of instructions needs analysis 1.1 The purpose of the preparation At completion of the "file management system" software pre-market survey, at the same time with a number of software users a comprehensive and in-depth study and analysis
This section is to do user registration example RegisterDemo, Record ROR development of the general flow. DB Prepare ※ ROR family of all instances will use Mysql, installation and testing of environmental reference ROR prepare articles. Icons refer t
Today's topic is how to improve their own web interface or web enhance the visual experience, which allows users to remember. We have three main methods (from difficult to easy): Do-It-Yourself Script Writing; use jQuery and mooTools similar to the J
See the online article has a lot of ssh configuration, but there is a lot of the tune does not make sense, there are versions, not exactly the same configuration, the following is my configuration to do the ssh tutorial development for reference; Thi
DWR (Direct Web Remoting) is a WEB framework for long-distance calls. Use of the AJAX development framework can become very simple. DWR can use the use of JavaScript on the client side of a direct call service method and returns the value of Java to
First of all, create a blog called the "Seam Web Project" 1: blog-ejb project under the following ejbModule, create a package, the name is org.domain.blog.entity 2: the ~ ~ \ examples \ blog \ src \ domain \ under three java files, copied to the
ROR examples of user registration (a) ... Rails plural rules Rails agreement ControllerName (URL) for the plural, TableName plural. Judging from the perceptual knowledge, Table plural that is, before the section of the rules of ruby script / generate
The following analysis of these parameters are directed to the IE browser: Get screen coordinates of the mouse, as opposed to the entire page: x = event.clientX, y = event.clientY Be the width of the current window: w = document.body.clientWidth; h =
-------------------------------------------------- ------------------- First, a page of the bean: package com.leatherstore.other; public class Page { /** If there are previous */ private boolean hasPrePage; /** Is there a next page */ private boolean
Use ArrayAdapter custom To-Do List This example will be extended To-Do List works to a ToDoItem object to store each and every project, including the creation date of each project. You will extend ArrayAdapter class to bind a group of objects to the
Core Tip: Recently, we tried to show the tree menu using extjs. Really took some effort. Tree menu, menu items need to dynamically load, while the current version of extjs only supports JSON format. Check some information, the decision to use struts2
Ant's build.xml (2 )----- examples Build on the progress, then the above recurrence of an example: <? xml <property name="name&q
Spring 2.5 jar for all development kits and complete documentation, and examples of project development spring jar package Xiangjie spring.jar that contain a complete release of a single jar package, spring.jar includes spring-mock.jar where in addit
/ ** * Author: ahuaxuan (Rong-Hua Zhang) * Date 2010-2-25 * / Simple terms cassandra 3 examples of the model behind In the last article, ahuaxuan with everyone wrote a cassandra the insert and get examples. From this example, we also learned that the
JVM parameters tuning is a very difficult problem, set a poor job, JVM ongoing implementation of Full GC, cause the entire system becomes very slow, the website dead time can be up to 10 seconds or more, which, if not repeat it a few minutes to once,
Js: an array of examples of the various methods pop, push, unshift, splice, shift <script> Array.prototype.pop = function () ( if (this.length! = 0) this.length--; return this; ) / * pop method removes the last element of the array and returns that
Prototype examples of learning Prototype combat ---- 1. $ $ Java code <html> <head> <title> Test $ $ </ title> <script src="prototype.js"> </ script> <script> function test $$(){ /**//* in case CSS is no
FreeMarker Overview FreeMarker is a template engine generates text output based on the template a common tool for the preparation of the use of pure Java Template + data model = output FreeMarker is a very good template engine, the template engine ca
Examples of video playback
Mainly use the jquery.easywidgets.js straightforward plug-ins to achieve this effect Paste attachments, be preserved for future use. Learning can be found online about jquery.easywidgets There is also a more simple drag effect is also relatively simp
This article describes how to write a simple WSDL file , WSDL document prepared in accordance with the server side and client side code , And to publish Web Service service process . First of all, the point is clear there are two versions of the WSDL
The demo guide provides detailed instructions for setting up a multi-domain SSO demonstration for a quick start with CAS. If unreadable in IE (no line wrap), try Firefox or just use the PDF utility. Problem Statement You would like to show-off Single
A key term Project: anything you would like to build things, Maven can be considered that they were engineering. These projects are defined for the project object model (POM, Poject Object Model). A project can rely on other works; a project can also
In this case developed implements a P2P multi-user online chat program, C / S architecture, the client can send messages, and then other users receive the message and displays the interface, the server information on the handling to the appropriate u
Struts2 specific usage examples of a constant <? xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE struts PUBLIC "- / / Apache Software Foundation / / DTD Struts Configuration 2.0 / / EN" "
Struts2 specific usage examples of two constants "! - Settings for each request, are to re-load the resource file, the default value is false. -> <cosntant name="struts.i18n.reload" value="false" /> "! - Standard UI
From: Annotation and packaged using the DAO layer integrates with paging capabilities S2SH examples Li Shunli January 24, 2010 Directory Key words ... 2 Foreword ... 2 Development enviro
import java.awt.AlphaComposite; import java.awt.Component; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; i
Quartz comes with running a database to run examples of unusual persistence ERROR [main] 2010-03-19 15:25:06,312 - org.quartz.SchedulerException: JobStore class 'org.quartz.ompl.jdbcjobstore.JobStoreTX' could not be instantiated. [See nested exceptio
Done before a struts2 project, summarizes commonly used in several struts2 tag usage, and to respond to the sample code, each label summarizes the key attributes about the page code, background code, and the generated html code 1. Checkbox Checkbox t
At present, more and more customers are using IBM FileNet BPM products, in particular the process engine (Process Engine), has been widely used. While the other three products, process simulator, process analyzers and business activity monitoring dev
Because the use of the hibernate-annotation, I found just the liberation of many things, almost completely without worry about the database, and posted examples of note: the code is written by someone else, I just realized only under Ha Use of the ba
exp usage and examples of exp / imp as a database backup recovery tool can also transfer data between different databases as a tool for the operating system where the two databases can be different exp database data can be exported as binary files ca Some other examples of which GtkTreeView: With the GtkTreeView and GtkListStore basis GtkTreeStore in GtkTreeView with nothing to explain to, and following this example, only the GtkTreeV
Author: wasw100 Website: Test environment: MyElipse (with Flex Builder3 plug-ins) Can set, here are more complementary,
Original Address This article describes the xmerl_xpath a good thing in this very convenient, and in official documents, the sum over them, people did no
Guide layer is it? Guide layer is equivalent to an approach to the person, the guidelines related to the idea of dominion over the object to act. Guide layer in the exported SWF file is not visible, so it will not affect the beauty of the screen. Gui
Flash shape tween animation is very important to the performance of practices in one, use it, you can changes all sorts of wonderful magical morphing. This section of the shape tween animation from the basic concept, with a shape tween animation you
makefile and some examples of static libraries Purpose of simplification from complex work out. Some production Makfile online articles, just stop it in the Makefile. Tools to use autotools to be relatively more simple, some other articles there are
extjs 3.1 API Ext JS 3.1 RC download examples Extjs Introduction (Reprinted) Official Website: API: Chinese API: extjs 3.1 API examples download Annex in
SQL injection is a technique that exploits a security vulnerability occurring in the Database Layer of an Application . The vulnerability is present when User input is either incorrectly filtered for String literal Escape characters Embedded in SQL s
Part I: oracle pl / sql instance of practice (1) First, using the scott / tiger emp table under the user and the dept table to complete the following exercises, table structure described below Staff table emp (empno Staff No. / ename employee name /
vmware network configuration examples of two windows host + linux guest Author: tenry (Yunqing (2005-03-24) Note: many of my friends asked to host ping unreasonable situation, please check the host in the firewall settings, most of the windows xp sp2
Welcome to reprint, please indicate the source - Web Hosting Provider and on --- sxl001 --- QQ: 285510591 In this statement only to control of movement with the AS method. FLASH can move objects in the stage of the film is usually an instance (for br
I've just watched the next spring AOP, the next stop and organize knowledge. The following describes the use of AOP in spring are two examples: a way to implement the use of annotations, another way to implement the declaration adopted. These two exa
CodeWeblog.com 版权所有 闽ICP备15018612号
processed in 0.095 (s). 9 q(s) | http://www.codeweblog.com/stag/gxt-examples/ | CC-MAIN-2017-51 | refinedweb | 1,885 | 50.06 |
Created on 2008-10-12 13:41 by thsajid, last changed 2009-06-04 16:14 by mbloore.
Check the robots.txt file from mathworld.
-->
It contains 2 User-Agent: * lines.
From
."
But it seems that our robotparser is obeying the 2nd one. the problem
occures because robotparser assumes that no robots.txt will contain two
* user-agent. it should not have two two such line, but in reality many
site may have two.
So i have changed robotparser.py as follow:
def _add_entry(self, entry):
if "*" in entry.useragents:
# the default entry is considered last
if self.default_entry == None: # this check is added
self.default_entry = entry
else:
self.entries.append(entry)
And at the end of parse(self, lines) method
if state==2:
# self.entries.append(entry)
self._add_entry(entry) # necessary if there is no new line
at end and last User-Agent is *
this looks like a good fix. i've put it into my own copy. | http://bugs.python.org/issue4108 | crawl-002 | refinedweb | 159 | 71.51 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.