text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
Data
Context Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Represents the main entry point for the LINQ to SQL framework.
public ref class DataContext : IDisposable
public class DataContext : IDisposable
type DataContext = class interface IDisposable
Public Class DataContext Implements IDisposable
- Inheritance
-
- Implements
-
Remarks. | https://docs.microsoft.com/en-us/dotnet/api/system.data.linq.datacontext?view=netframework-4.8 | CC-MAIN-2022-27 | en | refinedweb |
.
-.
- SherlockHans
from __future__ import annotations
pretty sure that annotations are in 3.6, as is typing...
Bumping this… I’d love to be able to use dataclasses. Feel free to tell me why I should do it another way, but I think it’s a valid request. I’m still newish to python but I’ve been writing software for 20 years.
@ottoflux there is a backport of dataclasses, since this basically pure py.
@Strassboom or others missing the quite convenient asyncio.run feature: CPython repo has a backport of the runners module, which you can conditionally import with a try ... except. | https://forum.omz-software.com/topic/4966/python-3-7/9 | CC-MAIN-2022-27 | en | refinedweb |
Hi! Jan Nieuwenhuizen <address@hidden> skribis: > Ludovic Courtès writes: > > Hello! > >> Jan Nieuwenhuizen <address@hidden> skribis: >> >>>>> +#if !__GNU__ >>>>> int status = pid.wait(true); >>>>> if (status != 0) >>>>> throw Error(format("cannot kill processes for uid `%1%': %2%") % >>>>> uid % statusToString(status)); >>>>> +#endif >>>> >>>> Do you know what the rationale was? It looks like it could leave >>>> zombies behind us. >>> >>> No, maybe Manolis knows? What I do know is why I used the patch: before >>> applying this patch I could only build up to binutils-boot0. >>> binutils-boot0 would always fail like so >>> >>> ./pre-inst-env guix build -e '(@@ (gnu packages commencement) >>> binutils-boot0)' --no-offload >>> XXX fails: Workaround for nix daemon >>> phase `compress-documentation' succeeded after 0.4 seconds >>> error: cannot kill processes for uid `999': Operation not permitted >>> guix build: error: cannot kill processes for uid `999': failed with exit >>> code 1 >> >> But is the build process actually running as UID 999? If you pass >> ‘--disable-chroot’, then I think build users are not used at all, right? > > It seems that they are; I'm running Oh, OK. […] >> Other options: >> >> 1. Implement clone(2) with CLONE_NEW* in libc on GNU/Hurd. >> >> 2. Add a “sandbox” abstraction in the daemon, with OS-specific >> implementations of the abstraction (the Nix daemon did that at some >> point, with the goal of supporting proprietary macOS etc.) >> >> For GNU/Linux, it’d use chroot(2)+clone(NEWNS) etc. as root. >> >> On GNU/Hurd, it could spawn the process in a sub-Hurd, i.e., with >> its own proc server, root file system server, and without a pfinet >> server running. >> >> Option #2 can be fun to implement and probably easier and less >> controversial than Option #1. However, it does mean adding more code of >> the C++ code base, which is sad. > > I'm assuming that 1.is what Manolis wanted to support with his > libhurdutil? In fact, I forward ported (minimal effort) the patch > > > > > but haven't tried linking against this yet. That would be a nice first > step. 2. sounds fun, but it would need more getting familiar with the > Hurd for me :-) You never know.. I suppose the commit you link to could have been used by libc to implement #1? Oh, actually, IIRC, Manolis was working on implementing mount(2) and umount(2) in libc (which would also be needed), and probably the settrans utilities were part of that effort. Thanks, Ludo’. | https://lists.gnu.org/archive/html/bug-guix/2020-03/msg00154.html | CC-MAIN-2022-27 | en | refinedweb |
enable setting row height on rows without cell values
Created originally on Bitbucket by Former user
Was already merged in Bitbucket before import, marked as merged by the import user
If a row does not have any cells with values, openpyxl fails to set the row height.
In this example only row 1 gets height 50:
from openpyxl import Workbook wb = Workbook() ws = wb.get_active_sheet() ws.cell('A1').value = "test" ws.row_dimensions[ws.cell('A1').row].height = 50 ws.row_dimensions[ws.cell('B2').row].height = 50 wb.save("test.xlsx") | https://foss.heptapod.net/openpyxl/openpyxl/-/merge_requests/6 | CC-MAIN-2022-27 | en | refinedweb |
- 27 Apr, 2012 2 commits
- 26 Apr, 2012 8 commits
Extend name lookup for fixity declaration to the TcClsName namespace for all reader names, instead of only those in DataName.
See Note [Deriving inside TH brackets] in TcInstDcls Fixes Trac #6005 (again)
- gmainlan@microsoft.com authored
This change generalizes support for floating in case expressions. Previously, case expression with an unlifted scrutinee and a single DEFAULT alternative were floated in. In particular, this allowed array index operations to be floated in. We also want to float in SIMD unpack primops, which return an unboxed tuple of scalars, thus the generalization.
Fixes Trac #6020, #6044
- 25 Apr, 2012 14 commits
This has been causing bloat in the src dist for ages. Noticed while looking at #6009, but I don't think this is the bug (./configure always removes ghc-pwd/dist-boot before building ghc-pwd)
*)
See Note [Splicing Exact names] in RnEnv.
-
Fixes Trac #6039, where we have a bogus kind signature data T (a :: j k) = MkT
Fixes Trac #5867, and is generally nicer
- 24 Apr, 2012 7 commits
- 23 Apr, 2012 4 commits
Reduces wobble in error messages, and is better for the programmer
- 22 Apr, 2012 3 commits
Fixes Trac #6020
That in turn means that you can derive Show etc in other modules, fixing Trac #6031
- 21 Apr, 2012 2 commits
It allows you to do (high, low) `quotRem` d provided high < d. Currently only has an inefficient fallback implementation. | https://gitlab.haskell.org/nineonine/ghc/-/commits/18c2a2f71e38fad5e677b8f448f6135e5a691868 | CC-MAIN-2022-27 | en | refinedweb |
In a previous post, I showed you how to remove comments from a Word file. In today’s post, I am going to show you how to accomplish the same scenario, but this time with Excel and PowerPoint files. Excel and PowerPoint have a Document Inspector feature, which is able to remove multiple types of data/content, including comments. This feature works great for client side solutions, but how do you cleanse these files of comments on the server? The Open XML SDK can accomplish these scenarios in just a few lines of code.
Note: The code showed in this post is backwards compatible with version 1 of the SDK.
Solution for PowerPoint
Imagine I start off with a PowerPoint deck that has multiple slides and comments. Here is a screenshot of a comment within a PowerPoint slide:
To remove comments from a PowerPoint deck we need to take the following actions:
- Open up the PowerPoint deck via the Open XML SDK
- Access the main presentation part, which will give us access to all the slide parts within the package
- Delete the comment part associated with each slide part
- Save changes made to the deck
If you want to jump straight into the code, feel free to download this solution here.
The Code
The code is pretty easy and maps 1:1 to the steps I mentioned above:
End Result
Running this method, I end up with a presentation void of comments. Pretty easy!
Here is a screenshot of the final presentation:
Solution for Excel
This solution is very similar to the PowerPoint solution.
Imagine I start off with an Excel workbook that has multiple worksheets, where each worksheet contains multiple comments. Here is a screenshot of a comment within a worksheet cell:
To remove comments from an Excel workbook we need to take the following actions:
- Open up the Excel workbook via the Open XML SDK
- Access the main workbook part, which will give us access to all the worksheet parts within the package
- Delete all comment parts associated with each worksheet part
- Save changes made to the workbook
If you want to jump straight into the code, feel free to download this solution here.
The Code
This code is very similar to the code used to remove comments from a PowerPoint deck:
End Result
Running this method, I end up with a workbook void of comments.
Here is a screenshot of the final workbook:
Zeyad Rajabi
PingBack from
FYI, the comments in Excel don’t consist in only the Comments part. This kind of snippet is pretty bad given the actual work to do to delete comments properly. It’s bad since it’s wrong, and that developers tend to copy/paste someone else’s code without checking first.
Anon,
Are you talking about removing the legacy vml drawing parts as well?
Zeyad Rajabi
Sure. And the reference to it in the sheet footer. And any singleton child part referenced by the legacy drawings. That makes a lot of difference with what you have posted…
Catching up on links to blog posts I’ve found interesting this month … I was on vacation the first week
Sorry for absolute off-topic Open Packaging Conventions question. Can anyone explain me the purpose of defining content types, when content can be determined from relationships? Thanks in advance and once more, sorry for OT question.
Brian, I have a question somewhat unrelated to this post. But it’s a simple one. I have added some XML parts to an Excel spreadsheet via an Excel Application Add-in. When I do this I use a namespace uri to identify the part that I added.
But when I use the Open XML SDK this namespace uri that I used doesn’t appear to be available. How do I find this namespace uri, given this is what I used as the key to my content.
Anon – Is there any way you can share an example file? I want to make sure I fully understand your concerns.
Ferou – Take a look at the following post:
Kang – You can either iterate through all the parts related to a particular part and look for the uri yourself or you could use System.IO.Packaging to get access to the specific part you want. | https://blogs.msdn.microsoft.com/brian_jones/2009/04/20/removing-comments-from-excel-and-powerpoint-files/ | CC-MAIN-2017-13 | en | refinedweb |
/*
* StructureBuilder.Attribute;.Order;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.Version;
import org.simpleframework.xml.strategy.Type;
/**
* The <code>StructureBuilder</code> object is used to build the XML
* structure of an annotated class. Once all the information scanned
* from the class has been collected a <code>Structure</code> object
* can be built using this object. The structure instance will
* contain relevant information regarding the class schema.
* <p>
* This builder exposes several methods, which are invoked in a
* sequence by the <code>Scanner</code> object. In particular there
* is a <code>process</code> method which is used to consume the
* annotated fields and methods. With the annotations it then builds
* the underlying structure representing the class schema.
*
* @author Niall Gallagher
* @see org.simpleframework.xml.core.Scanner
class StructureBuilder {
/**
* This is used to build an instantiator for creating objects.
*/
private InstantiatorBuilder resolver;
* This is used to build XPath expressions from annotations.
private ExpressionBuilder builder;
* This is used to perform the initial ordered registrations.
private ModelAssembler assembler;
* This is the instantiator that is used to create instances.
private Instantiator factory;
* For validation all attributes must be stored in the builder.
private LabelMap attributes;
* For validation all elements must be stored in the builder.
private LabelMap elements;
* This is used to maintain the text labels for the class.
private LabelMap texts;
* This is the source scanner that is used to scan the class.
private Scanner scanner;
* This object contains various support functions for the class.
private Support support;
* This is the version annotation extracted from the class.
private Label version;
* This represents a text annotation extracted from the class.
private Label text;
* This the core model used to represent the XML structure.
private Model root;
* This is used to determine if the scanned class is primitive.
private boolean primitive;
* Constructor for the <code>StructureBuilder</code> object. This
* is used to process all the annotations for a class schema and
* build a hierarchical model representing the required structure.
* Once the structure has been built then it is validated to
* ensure that all elements and attributes exist.
*
* @param scanner this is the scanner used to scan annotations
* @param type this is the type that is being scanned
* @param format this is the format used to style the XML
public StructureBuilder(Scanner scanner, Detail detail, Support support) throws Exception {
this.builder = new ExpressionBuilder(detail, support);
this.assembler = new ModelAssembler(builder, detail, support);
this.resolver = new InstantiatorBuilder(scanner, detail);
this.root = new TreeModel(scanner, detail);
this.attributes = new LabelMap(scanner);
this.elements = new LabelMap(scanner);
this.texts = new LabelMap(scanner);
this.scanner = scanner;
this.support = support;
}
* This is used to acquire the optional order annotation to provide
* order to the elements and attributes for the generated XML. This
* acts as an override to the order provided by the declaration of
* the types within the object.
* @param type this is the type to be scanned for the order
public void assemble(Class type) throws Exception {
Order order = scanner.getOrder();
if(order != null) {
assembler.assemble(root, order);
}
}
* This reflectively checks the annotation to determine the type
* of annotation it represents. If it represents an XML schema
* annotation it is used to create a <code>Label</code> which can
* be used to represent the field within the context object.
* @param field the field that the annotation comes from
* @param label the annotation used to model the XML schema
* @throws Exception if there is more than one text annotation
*/
public void process(Contact field, Annotation label) throws Exception {
if(label instanceof Attribute) {
process(field, label, attributes);
if(label instanceof ElementUnion) {
union(field, label, elements);
if(label instanceof ElementListUnion) {
if(label instanceof ElementMapUnion) {
if(label instanceof ElementList) {
process(field, label, elements);
if(label instanceof ElementArray) {
if(label instanceof ElementMap) {
if(label instanceof Element) {
}
if(label instanceof Version) {
version(field, label);
if(label instanceof Text) {
text(field, label);
* This is used when all details from a field have been gathered
* and a <code>Label</code> implementation needs to be created.
* This will build a label instance based on the field annotation.
* If a label with the same name was already inserted then it is
* ignored and the value for that field will not be serialized.
* @param field the field the annotation was extracted from
* @param type the annotation extracted from the field
* @param map this is used to collect the label instance created
* @throws Exception thrown if the label can not be created
private void union(Contact field, Annotation type, LabelMap map) throws Exception {
List<Label> list = support.getLabels(field, type);
for(Label label : list) {
String path = label.getPath();
String name = label.getName();
if(map.get(path) != null) {
throw new PersistenceException("Duplicate annotation of name '%s' on %s", name, label);
}
process(field, label, map);
private void process(Contact field, Annotation type, LabelMap map) throws Exception {
Label label = support.getLabel(field, type);
String path = label.getPath();
String name = label.getName();
if(map.get(path) != null) {
throw new PersistenceException("Duplicate annotation of name '%s' on %s", name, field);
process(field, label, map);
* @param label this is the label representing a field or method
private void process(Contact field, Label label, LabelMap map) throws Exception {
Expression expression = label.getExpression();
Model model = root;
if(!expression.isEmpty()) {
model = register(expression);
resolver.register(label);
model.register(label);
map.put(path, label);
* This is used to process the <code>Text</code> annotations that
* are present in the scanned class. This will set the text label
* for the class and an ensure that if there is more than one
* text label within the class an exception is thrown.
private void text(Contact field, Annotation type) throws Exception {
if(texts.get(path) != null) {
throw new TextException("Multiple text annotations in %s", type);
model.register(label);
texts.put(path, label);
private void version(Contact field, Annotation type) throws Exception {
if(version != null) {
throw new AttributeException("Multiple version annotations in %s", type);
version = label;
* This is used to build the <code>Structure</code> that has been
* built. The structure will contain all the details required to
* serialize and deserialize the type. Once created the structure
* is immutable, and can be used to create <code>Section</code>
* objects, which contains the element and attribute details.
* @param type this is the type that represents the schema class
* @return this returns the structure that has been built
public Structure build(Class type) throws Exception {
return new Structure(factory, root, version, text, primitive);
* This is used to determine if the specified XPath expression
* represents an element within the root model. This will return
* true if the specified path exists as either an element or
* as a valid path to an existing model.
* <p>
* If the path references a <code>Model</code> then that is an
* element only if it is not empty. If the model is empty this
* means that it was used in the <code>Order</code> annotation
* only and this does not refer to a value XML element.
* @param path this is the path to search for the element
* @return this returns true if an element or model exists
private boolean isElement(String path)throws Exception {
Expression target = builder.build(path);
Model model = lookup(target);
if(model != null) {
String name = target.getLast();
int index = target.getIndex();
if(model.isElement(name)) {
return true;
if(model.isModel(name)) {
Model element = model.lookup(name, index);
if(element.isEmpty()) {
return false;
}
return false;
* represents an attribute within the root model. This returns
* true if the specified path exists as either an attribute.
* @param path this is the path to search for the attribute
* @return this returns true if the attribute exists
private boolean isAttribute(String path) throws Exception {
if(model != null) {
if(!target.isPath()) {
return model.isAttribute(path);
return model.isAttribute
private Model lookup(Expression path) throws Exception {
Expression target = path.getPath(0, 1);
if(path.isPath()) {
return root.lookup(target);
return root;
* This is used to register a <code>Model</code> for this builder.
* Registration of a model creates a tree of models that is used
* to represent an XML structure. Each model can contain elements
* and attributes associated with a type.
* @param path this is the path of the model to be resolved
* @return this returns the model that was registered
private Model register(Expression path) throws Exception {
Model model = root.lookup(path);
if (model != null) {
return model;
}
return create(path);
private Model create(Expression path) throws Exception {
while(model != null) {
String prefix = path.getPrefix();
String name = path.getFirst();
int index = path.getIndex();
if(name != null) {
model = model.register(name, prefix, index);
if(!path.isPath()) {
break;
path = path.getPath(1);
return model;
* This is used to commit the structure of the type. This will
* build an <code>Instantiator</code> that can be used to create
* instances using annotated constructors. If no constructors have
* be annotated then instances can use the default constructor.
* @param type this is the type that this builder creates
public void commit(Class type) throws Exception {
if(factory == null) {
factory = resolver.build();
* This is used to validate the configuration of the scanned class.
* If a <code>Text</code> annotation has been used with elements
* then validation will fail and an exception will be thrown.
* @param type this is the object type that is being scanned
public void validate(Class type) throws Exception {
validateUnions(type);
validateElements(type, order);
validateAttributes(type, order);
validateModel(type);
validateText(type);
validateTextList(type);
* This is used to validate the model to ensure all elements and
* attributes are valid. Validation also ensures that any order
* specified by an annotated class did not contain invalid XPath
* values, or redundant elements and attributes.
* @param type this is the object type representing the schema
private void validateModel(Class type) throws Exception {
if(!root.isEmpty()) {
root.validate(type);
private void validateText(Class type) throws Exception {
Label label = root.getText();
if(label != null) {
if(!label.isTextList()) {
if(!elements.isEmpty()) {
throw new TextException("Elements used with %s in %s", label, type);
if(root.isComposite()) {
throw new TextException("Paths used with %s in %s", label, type);
} else {
if(scanner.isEmpty()) {
primitive = isEmpty();
* If an <code>ElementListUnion</code> annotation has been used with
* a <code>Text</code> annotation this validates to ensure there are
* no other elements declared and no <code>Path</code> annotations
* have been used, which ensures free text can be processed.
private void validateTextList(Class type) throws Exception {
Label label = root.getText();
if(label.isTextList()) {
Object key = label.getKey();
for(Label element : elements) {
Object identity = element.getKey();
if(!identity.equals(key)) {
throw new TextException("Elements used with %s in %s", label, type);
}
Type dependent = element.getDependent();
Class actual = dependent.getType();
if(actual == String.class) {
throw new TextException("Illegal entry of %s with text annotations on %s in %s", actual, label, type);
}
* This is used to validate the unions that have been defined
* within the type. Union validation is done by determining if
* the union has consistent inline values. If one annotation in
* the union declaration is inline, then all must be inline.
* @param type this is the type to validate the unions for
private void validateUnions(Class type) throws Exception {
for(Label label : elements) {
String[] options = label.getPaths();
Contact contact = label.getContact();
for(String option : options) {
Annotation union = contact.getAnnotation();
Label other = elements.get(option);
if(label.isInline() != other.isInline()) {
throw new UnionException("Inline must be consistent in %s for %s", union, contact);
if(label.isRequired() != other.isRequired()) {
throw new UnionException("Required must be consistent in %s for %s", union, contact);
}
* If an ordered element is specified but does not refer to an
* existing element then this will throw an exception.
* @param order this is the order that is to be validated
private void validateElements(Class type, Order order) throws Exception {
for(String name : order.elements()) {
if(!isElement(name)) {
throw new ElementException("Ordered element '%s' missing for %s", name, type);
* If an ordered attribute is specified but does not refer to an
* existing attribute then this will throw an exception.
private void validateAttributes(Class type, Order order) throws Exception {
for(String name : order.attributes()) {
if(!isAttribute(name)) {
throw new AttributeException("Ordered attribute '%s' missing in %s", name, type);
* This is used to determine if the structure is empty. To check
* to see if the structure is empty all models within the tree
* must be examined. Also, if there is a text annotation then it
* is not considered to be empty.
* @return true if the structure represents an empty schema
private boolean isEmpty() {
if(text != null) {
return false;
return root.isEmpty();
} | http://simple.sourceforge.net/download/stream/report/cobertura/org.simpleframework.xml.core.StructureBuilder.html | CC-MAIN-2017-13 | en | refinedweb |
I have been searching for this a lot, but could not find an answer for Python.
Is it possible to simulate right click, or open up the context menu via selenium/chromedriver?
I have seen options for Java, and some other languages, but never in Python.
What would I have to do to simulate a right click on a link, or a picture?
It's called
context_click in selenium.webdriver.common.action_chains. Note that Selenium can't do anything about browser level context menu, so I assume your link will pop up HTML context menu.
from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome() actionChains = ActionChains(driver) actionChains.context_click(your_link).perform() | https://codedump.io/share/rYv5md7fffK8/1/how-to-perform-right-click-using-selenium-chromedriver | CC-MAIN-2017-13 | en | refinedweb |
Edward Moemeka
My new book, Real World Windows 8 App Development with JavaScript (apress), will be out July 10th. Pre-order now. You might also like my other titles: Professional C# (wrox) and C# for Java developers (sams) (all available on Amazon)
Inside Windows Platform | Going from Windows Phone Silverlight to Windows RT XAML
awesome video! Can you shed some light on when WinPRT will have ServiceModel and associated namespaces so we can *really* start porting. All these samples are great from a UI perspective but don't include the tremendous amount of backend redesigning that needs to happen for a port to happen (becuase of lack of WCF stack).
Most of us built our WP Silverlight apps using WCF web services. For some bizarre reason everyone keeps giving "LongListSelector" and "namespace change" examples; these are just about the least of anyone's concerns given the huge backend effort needed to commit to WinPRT.
For my part I spent a week converting one of my apps without even suspecting that such a thing would be ommitted and not clearly stated. Then i right-clicked on my project searching for the "Add Service Reference" menu item and cried myself to sleep...
Please give us some good news, every release of your UI SDKs lately seem to be missing some obscure critical piece that just delays innovation and development.
What's New In C# 6.0
@MadsTorgersen:Thanks for you feedback, this request might be too late but please consider making anonymous types like new{Name="john",Age=5}; serializable by generating a public parameterless constructor for them and also marking the type with the appropriate DataMember/Contract attributes. They are already public types and cannot be redefined at runtime so why not make them seriazable? This reduces code bloat astronomically.
What's New In C# 6.0
Um, what happened to the $ shortcut for dictionary initializers that have a string based key. I get the squiggles when I try to use it. This is a critical issue for data access types as you noted in a previous blog. I am tired of creating one-off data classes that are just extensions of some back end projection. The $ feature was a nice middle ground since anonymous types can still not be serialized properly.
Enterprise App Deployment for Windows and Windows Phone
...OR...you can just write your enterprise code in WPF (even web based) and not have to jump through 10000 hoops to get it installed. Why would you make it so difficult to simply install an app, effectively making every other UI technology you have canibalize the use of WInRT and apps in the enterprise ?!? What does one gain by using WinRT for LOB? There is absolutely NO value proposition based on these deployment rules. If you only use store compliant APIs then the store is best for deploying, if you dont then you are basically working three times as hard to make an application that will look (as of windows 10) and feel just like it's Native counterpart.
You are shackling software development to IT guys who are: conservative, slow, and certainly dont have a passion for the technology. Do you expect a VP on the Infrastructure team to approve such a process (maybe even have to train people!) just so I can build a cool reporting utility for my manager?
This type of approach is so strategic a choice, that it kills the ability for visionary technologists - who are *not* in senior leadership positions - to create enough of a ground-swell to make WInRT's merrits visible to people who *are* leadership positions. But there is no simple way to explain to leaders what the actual value proposition of WinRT in this scenario is because its value is something only a visionary technologists could divine. See the problem?
Please remove all these pointless restrictions because they really are idiotic. People can already install / run programs from anywhere and that is just not going to change.
I agree that there should be an API subset between store apps and normal apps, you can even put up a prompt or something every time a sideloaded app is run, but this madness has to stop. GET OUT OF YOUR OWN WAY!!! And let us make this happen.
The New Windows Phone Application Model.
Anders Hejlsberg: Introducing TypeScript !!!!!
Visual Studio Toolbox: Visual Studio 11 Beta with Jason Zander
Future directions for C# and Visual Basic
).
Windows 8 Running on ARM
!
Allen Wirfs-Brock and Chris Wilson: EcmaScript, JavaScript and the Web
I know javascript rules, but I just always feel like i'm stitching things together with it.
Allen Wirfs-Brock and Chris Wilson: EcmaScript, JavaScript and the Web
will there ever be a new compiled language for the web? One that all the browsers will understand? I really wish that something else existed beyond javascript.
Where the Multitouch Devices Are pt. 2. | https://channel9.msdn.com/Niners/Moemeka | CC-MAIN-2017-13 | en | refinedweb |
UPM has been around for nearly 4 years now, and seems to have been well adopted, to the point where we’re starting to see some support calls along the lines of “I’ve outgrown my original user store and I need to migrate my users to a more scalable store, without losing my data. How?”
There are some obvious solutions around using tools like robocopy and Profile Nurse (sepago.de), but they don’t fit all scenarios, as they tend to require some downtime, or high-bandwidth connections (or both).
So I’m going talk about a couple of other techniques that might help upgrade a live installation. One of those techniques is a bit “off-the-wall”, but maybe it’ll inspire you.
Technique #1 – DFS is your friend
Suppose in the early days of my UPM deployment I had defined my profile store (i.e. Path to user store) to be \\MyCorpLonSrv01\profile$\#cn#
Imagine now that we’ve kept adding users, plus we really need to add a couple more file servers in the new Tokyo and Seattle offices, which are planned to have their own farms. We can’t really afford any downtime, either. And we’d rather do it without adding any new OUs for the moment.
Scaling UPM to thousands of users really needs DFS Namespaces, and it’s this that we’ll use.
Step 1 is to set up the new file servers \\MyCorpTkoSrv01 and \\MyCorpSeaSrv01 and create profile shares on each of them.
Step 2 is to create a DFS Namespace called (say) \\MyCorp\Profiles. Beneath this namespace we can now create folders, and assign them to targets. This is very similar to the technique described in eDocs at . Typically we’ll use a department-based or a geo-based attribute from the AD user object to load balance. The eDocs page suggests #l# (the location attribute) as a suitable example.
So at this point we have the following folders defined in a DFS namespace, pointing to the targets shown
\\MyCorp\Profiles\London --> \\MyCorpLonSrv01\profile$ \\MyCorp\Profiles\Tokyo --> \\MyCorpTkoSrv01\profile$ \\MyCorp\Profiles\Seattle --> \\MyCorpSeaSrv01\profile$
Step 3 is to add or fix all the AD user objects so that every user has a location attribute set to one of London, Tokyo and Seattle. After that, you can simply change the path to user store policy to be \\MyCorp\Profiles\#l#\#cn#
Simple?
Maybe too simple…
But what if some early Tokyo users already have profiles on MyCorpLonSrv01, or if MyCorpLonSrv01 isn’t really powerful enough to handle all the users on it. Or maybe there’s a merger/acquisition and we’re integrating hundreds of new users from the NewCorp domain? This can be a real headache, as #cn# probably isn’t unique – consider that both MyCorp and NewCorp may have employees called “John Smith”, for example – we really need to switch the profiles to use %USERNAME%.%USERDOMAIN% rather than #cn#
We need a mechanism to migrate (some) users off MyCorpLonSrv01. Of course, if we don’t mind a bit of downtime, it’s easy. Use robocopy and/or Profile Nurse to migrate selected profiles to new servers, change the Path to user store and let everyone back on again. And we’ll need quite a bit of bandwidth if we want to get all profiles copied over a long weekend, which may not work over intercontinental links.
But is there a way to do it without downtime, and without huge bandwidth?
Maybe…
Technique #2 – UPM Profiles are just like MS Roaming Profiles – Really!
(Warning – This is the off-the-wall one!)
UPM has a feature to migrate MS Roaming Profiles to UPM Profiles. If UPM finds that a user doesn’t yet have a UPM Profile, it can be configured to migrate an existing Roaming Profile.
But what’s the difference between a UPM Profile and a Roaming Profile? It turns out there’s very little difference at all. This what you’d expect – if there were major differences between UPM Profiles and Roaming Profiles, then there would be application compatibility issues.
How little a difference? On the local machine there’s a registry value in HKLM that tells UPM that the local profile for a particular user SID is actually a UPM profile. And there are a couple of extra copies of the registry (NTUSER.DAT.START and NTUSER.DAT.NET) that UPM uses to merge registry changes – they’re temporary files that get deleted at logoff anyway.
On the profile store, there are a couple of extra files (PmCompatibility.ini and UPMSettings.ini) that record which machines have been sharing the profile, and how they’re configured. There’s also the Pending area, which is a temporary area used for managing profile updates made by concurrent sessions. If there are no sessions active, the Pending area will be empty.
So maybe we can convince UPM that our old UPM Profile is actually a Roaming Profile and get it to migrate it to a new UPM Profile in a new location.
Let’s see what we have to do…
First of all, we have to get rid of that registry value in HKLM. If that’s around, UPM will find a UPM profile on the local machine but no UPM profile in the User Store. UPM (rightly) regards this as an error condition.
To get rid of that registry value, we need to make sure UPM deletes the locally cached profile off the machine on logoff. So we set the policy “Delete locally cached profiles on logoff”. That gets rid of the profile and that troublesome registry value too. It doesn’t have much effect on performance, as you should be using “Profile streaming” anyway.
Now we have to convince (=trick) UPM to treat the old UPM Profile as if it were a Roaming Profile, and migrate it.
UPM looks for Roaming Profiles by querying Group Policy and the AD User Account (the user object) in the following order:
- Group policy TS profile directory (if in TS session)
- User account TS profile directory (if in TS session)
- Group policy “normal” profile directory (if on Vista/7/2008)
- User account “normal” profile directory
So we need to set up one of these sources to point to the old user store, and all will be well.
The Group policy works by putting the path into a registry key+value, which will be either:
TS Profile:
Normal Profile:
The equivalent attributes in the AD user account are:
TerminalServicesProfilePath
or
ProfilePath
respectively.
The two policies are machine policies, so may not be suitable in all cases. However, it should be straightforward to script an AD update that overwrites either TerminalServicesProfilePath or ProfilePath for each user to reference the “old” UPM Profile path. PowerShell, for example, provides Get-ADUser and Set-ADUser cmdlets that let a suitably-privileged administrator update the AD User Object.
So now we have a way to:
- Clear out the locally cached copy of the UPM profile
- Convince UPM that the old UPM profile is in fact a Roaming Profile, by setting the AD user attribute TerminalServicesProfilePath to the old UPM profile (for example, changing John Smith’s attribute to “\\MyCorpLonSrv01\profile$\John Smith”)
It just remains to point UPM at the new profile store (by changing the Path to user store policy to \\MyCorp\Profiles\#l#\%USERNAME%.%USERDOMAIN%) and UPM will migrate the old UPM profiles to the new user store, complete with name changes, and moving to new servers.
The best and the worst of this solution is that migrations happen when users log on. If the logons are staggered, that’s great – your profiles will get migrated without straining your intercontinental link. But if all your users log on at once – the classic “thundering herd” scenario – then this solution is no better than robocopy.
The mitigation is to move small batches of users at a time, moving them to a new farm with separate machines and the new user store, but still able to access the old user store. Sadly this involves setting up either a new OU or at least putting WMI filtering on, to give the new farm a different Path to user store policy.
Conclusion
The moral of this tale is to get your Path to user store right in the first place. If you don’t, it’ll be painful later. Some specific points:
- Don’t use #cn#. Use %USERNAME%.%USERDOMAIN%
- Do include a user attribute in the Path to user store that will help you load balance across file servers and across geos when your deployment grows. Make sure your user attributes are also valid as NTFS folder names!
- Plan from the start to use DFS Namespaces for scalable profile deployments
Hope that helps somebody…
PostScript
Some of you will be asking, has Bill actually tried any of this out?
No, but that’s not the point.
The point is to start some discussion on what issues UPM users have faced around this area, with a view of collecting some best practices and maybe setting UPM development direction.
- Is this a realistic migration scenario?
- How much control do UPM users typically have over their AD environment? Can you set up an OU at the drop of a hat? Or do you have to wait 6 weeks to get even the tiniest changes made?
- Have you tried something like this, and did it work?
- What other techniques have you found useful?
- What new features or tools would be useful to you, to help in such a scenario?
Disclaimer
WARNING! Modifying the Active Directory incorrectly, either manually or by a script, can cause serious problems that may require you to restore your Active Directory. Citrix cannot guarantee that problems resulting from the incorrect modification of the Active Directory can be solved. Modifications of Active Directory, either manually or by script, are undertaken at your own risk. | https://www.citrix.com/blogs/2012/06/27/migrating-upm-profiles-%E2%80%93-tips-and-tricks/ | CC-MAIN-2017-13 | en | refinedweb |
dpns_modifygrpmap - modify group entry corresponding to a given virtual gid
#include <sys/types.h> #include "dpns_api.h" int dpns_modifygrpmap (gid_t gid, char *newname)
dpns_modifygrpmap modifies the group entry corresponding to a given virtual gid. gid specifies the Virtual Group Id. newname specifies the new group. | http://huge-man-linux.net/man3/dpns_modifygrpmap.html | CC-MAIN-2017-13 | en | refinedweb |
gfs_glob - find path names matching a pattern
#include <gfarm/gfarm.h> char *gfs_glob (const char * pattern, gfarm_stringlist * paths, gfs_glob_t * types);
gfs_glob() searches for all the path names matching pattern that may include a wildcard, and returns paths. The returned path names are accessed by gfarm_stringlist_length(3) and gfarm_stringlist_elem(3). It is necessary to allocate memory space dynamically pointed to by types using gfs_glob_init(3) before calling gfs_glob(3). The allocated memory space needs to be free’ed by gfs_glob_free(3).
NULL The function terminated successfully. GFARM_ERR_NO_MEMORY Insufficient memory was available. GFARM_ERR_PATHNAME_TOO_LONG Too long pattern or path name to process. Others An error except the above occurred. The reason is shown by its pointed strings.
gfs_glob_init(3) gfs_glob_free(3) gfarm_stringlist_init(3) gfarm_stringlist_length(3) gfarm_stringlist_elem(3) gfarm_stringlist_free(3) gfarm_stringlist_free_deeply(3) | http://huge-man-linux.net/man3/gfs_glob.html | CC-MAIN-2017-13 | en | refinedweb |
application ID
The application ID can be found using the
appengine.AppID function.engine.DefaultVersionHostname function. ID, if present.
appengine.AccessToken function
returns an access token for a scope, or list of scopes. This token can then be
set in the HTTP headers of a call to identify the calling application.
import ( "net/http" "google.golang.org/appengine/urlfetch" "golang.org/x/net/context" "golang.org/x/oauth2" "golang.org/x/oauth2/google" urlshortener "google.golang.org/api/urlshortener/v1" ) // shortenURL returns a short URL which redirects to the provided url, // using Google's urlshortener API. func shortenURL(ctx context.Context, url string) (string, error) { transport := &oauth2.Transport{ Source: google.AppEngineTokenSource(ctx, urlshortener.UrlshortenerScope), Base: &urlfetch.Transport{Context: ctx}, } client := &http.Client{Transport: transport} svc, err := urlshortener.New(client) if err != nil { return "", err } resp, err := svc.Url.Insert(&urlshortener.Url{LongUrl: url}).Do() if err != nil { return "", err } return resp.Id, nil }
Note that the application's identity is represented by the service account name, which is typically applicationid@appspot.gserviceaccount.com. You can get the exact value by using the
appengine.ServiceAccount function.
For services which offer ACLs, you can grant the application access by granting this account access.
Asserting identity to third-party services
The token generated by
AccessToken
only works against Google services. However you can use the underlying signing technology to assert the identity of your application to other services. The
appengine.SignBytes function
will sign bytes using a private key unique to your application, and the
appengine.PublicCertificates function
will return certificates which can be used to validate the signature., call DefaultBucketName. | https://cloud.google.com/appengine/docs/standard/go/appidentity/ | CC-MAIN-2017-13 | en | refinedweb |
Swiftenv allows you to easily install, and switch between multiple versions of Swift. You can install swiftenv following official instructions.
⚠️ With homebrew use
brew install kylef/formulae/swiftenv --HEAD.
Once you have it, install the Swift 3.0 Release
swiftenv install 3.0), ] )
Open
main.swift and make it look like this:
import HTTPServer let router = BasicRouter { route in route.get("/hello") { request in return Response(body: "Hello, world!") } } let server = try Server(configuration: ["port": 8080], responder: router) try server.start()
This code:
HTTPServermodule
BasicRouter
Requestwith GET as the HTTP method and /hello as the path.
Responsewith
"Hello, world!"as the body for requests matching the route.
8080...
Check out our organization for more. You can also take a look at our documentation. If you have any doubts you can reach us at our slack. We're very active and always ready to help. | https://www.gitbook.com/book/zewo/docs/details | CC-MAIN-2017-13 | en | refinedweb |
Human resource management principles and standards
Published: Last Edited:
This essay has been submitted by a student. This is not an example of the work written by our professional essay writers.
The control and guidance of human activities have started with the gathering of human in communities but have become a necessity with the apparition of factories and work centres. The owner or person in charge of the business in order to achieve his smart objectives had to set rules and practices for the control and guiding of his employees.
The need to understand and control their workforce had fuelled the emergence of theories and concepts by companies' owners. HRM is therefore a resultant a long list of management models. As a human concept, human management is set and implemented with a variety of shades, depending of the type of industry, company and culture, but four approaches can always be distinguished on managing employee in an organisation (Haffner, 2010, page 9 handout 1) Appendix 1 is showing these four different approaches
HRM strategy
Haffner in his handout 1 (2010) cited a definition of HRM by Armstrong as "a strategic and coherent approach to the management of an organisation most valued assets, the people working there, who individually and collectively contribute to the achievements of objectives."
HRM is a hard concept to defined as it is differently interpreted by authors or practitioners (see Appendix 2 Table 1: Textbook definition of HRM) but one fact seems constant in all definitions; the implementation of HRM is part of the business strategy of an organisation (Price, 2004). The integration of HRM strategy in the overall business strategy of the organisation is a paramount requirement for achievement of its smart objectives.
Socio-economic
Technical
Political Legal
Competitive
OUTER CONTEXT (PEST)
INNER CONTEXT (SWOT)
Management Style
Culture
Structure
Finances
Task-Technology
Motivation of staff
BUSINESS STRATEGY CONTEXT
Feedback
BUSINESS UNITS' STRATEGIES -
SUCH AS HUMAN RESOURCE MANAGEMENT
HRM OPERATIONS 'EFFECTIVENESS AND EFFICIENCY
OUTCOME OF STRATEGIC OBJECTIVES AND CONSEQUENCES
Figure 1: An illustrated Typical HRM Strategy Model (source: Haffner handout 1, 2010, p.18)
The implementation of human management can also be described as hard and soft HRM. According to Armstrong (2006) citing Storey and Legge, the hard HRM regards employees as commodity similar to others resources used by the organisation to achieve its smart objectives. For them soft HRM sees people as valued assets that the commitment is required to achieve the smart objectives of an organisation. An analysis of the reality show that most organisations used a mixture of all the approaches except the worker' control one, in accordance with the environment, the nature of the organisation and the operational strategy (Haffners' handout1, 2010).
PEST AND SWOT ANALYSIS
A better understanding of the environment (External and internal), was need during the writing of this paper. The Dairy industry in UK with a value of $16.5 Billion in 2008, seem to be an appropriated choice for a PEST analyse for the external impact of the environment and Dairy Crest with a value of £1,629.7 million for a SWOT analysis for the internal impact (Datamonitor, 2010).
Appendix 3 shows how the PEST and SWOT analysis were conducted
The outcome of the PEST analysis shows that the Dairy industry stills in good condition despite the economic crisis and with status of its products in the UK population diet, it will remain a good investment for many years. The SWOT analysis of Dairy Crest seems to show that despite the positive state of the Dairy industry in UK, Dairy Crest seems to have some issues which threaten its position in the market. The management of Dairy Crest need to make some changes regarding its debt and lack of involvement in new products.
ACTIVITIES
TRAINING AND DEVELOPMENT
It is well recognised allowing employees to develop skills and attitude help most organisations to achieve their smart objectives and enhance their competitiveness (Bratton and Gold, 2007, p 307). In successful organisation the provision of training and development of the employees is set up, planned and monitored by the Human Resource Development (HRD) within the HRM department. See appendix 4 page 22 systematic training model and role of HRM and Line manager.
Regarding the importance of training and development the Chief executive Sir Terry Leahy of the successful supermarket Tesco was quote saying "We are not doing it at Tesco because it makes us feel good. Among apprentices we have higher employee satisfaction levels, which lead to higher retention levels and an increase in staff performance" (, 2010). The training and development approach in Tesco is flexible and structured in such way that it suited the individual needs of the employees (, 2010). See appendix 5 explained the models used by Tesco for training and Development for its employees.
Figure 2: Shows the different training paths available to Tesco's employees
For the Eresearch (2010), Human Resources Development is the framework that focuses on the organisations competencies at the first stage, training, and then developing the employee, through education, to satisfy the organisations long-term needs and the individuals' career goals and employee value to their present and future employers. The evolution of the HRM function and consequently the one of HRD, have seen the role of Line managers increased. They are encouraged to be mentor and coaches, integrated in the HRM strategy of Training and Development. Several reasons justified the involvement of the Line Manager:
Training and development occurred more and more at work place
Effectiveness of training and development at the working environment
The Line manager can intervene more rapidly when help is needed
Much cheaper for the organisation as the employee remains productive and applied immediately what he is learning
Training and development occurred also off job site, employees are sent to centres where they learn specific skills such as team building, leadership development, etc. The choice of the centre and the content of the learning are made by the HRD, after the employee and its line manager have identified gaps in skills and knowledge. The decision made is always in line with the overall strategy of the organisation (, 2010).
The development of ICT has been notice by the HRD managers and been taking upon as training and development tools.
RECRUITMENT AND SELECTION
The recruitment and selection process is part of the operational strategy of in any successful organisation. A well conducted recruitment and selection can provide many benefits for the employees and the employer but most importantly for customers. For an organisation such as Enterprise, the customer satisfaction is correlated to an effective and efficient recruitment which also lead to a low workforce turnover (thetimes100, 2010).
Various models of recruitment and selection existed but they are all subjected to the rules and regulations of the organisation geographical location. The organisations operating in the UK are under UK legislation, mostly on sex, race, disability and recently age discrimination which are depend on the EU directives. See appendix 6 Table 3.1: a list of Acts and they application in the UK.
In HRM oriented organisations, while the Line manager in case of vacancy decide the need for filling it, change part of it or shared among others role, the HRM department which over-see the operational and strategic smart objectives of the organisation, will insure that the recruitment is contributing to them (, 2010). The involvement of the Line manager in the job and person description is important as he is one receiving the selected person into his team, in charge of the induction and training. The role of the HRM manager regarding the recruitment and selection process should be limited to advising the Line manager or recruitment team on legal aspect of the process and to the respect of the overall smart objectives of the organisation. In reality, some organisations with a centralised HRM department, it is the responsibility of the HRM manager to conduct most aspect of the recruitment and selection process, while the Line manager has a passive role of involvement (, 2010).
The evolution and integration of the HRM role in the strategic operation of successful organisation have change the nature of the recruitment and selection approach. It is now understand that the recruitment and selection policy and process of an organisation will reflect on the way it managed its workforce (Bratton and Gold, 2007 pag. 269). It also a process which subject to external influences such as the state of the economy, the skill or competency of the national workforce like in the UK, a shortage of qualified IT professionals saw people from outside coming in with the consequence of a rise in the salary on that sector. See appendix 7 figure 3.2: an illustration of demand and supply of labour.
The adoption of HRM strategy in successful organisation have seen the workforce considered as the most important resource, therefore their recruitment and selection is seen by the HRM manager as part of the organisation's strategy. It can be used to strategically steer the culture and competency of the workforce toward the smart objectives set by the senior managements.
The recruitment and selection in an organisation can occur internally or externally. Depending on the operational and strategic aims of an organisation, the recruitment and selection is mostly base on three approaches (Price, 2004). See appendix 9 Table 3.4: Recruitment strategies).
The best candidate approach
The culture fit approach
Flexible person approach
The recruitment which is the first part of this process, consist of acknowledge a need for a new employee, draft a job and person description, advertising the vacancy (several methods existed) and reception of application forms. The second and final part consists making a choice of best candidate among a pool of applicants using different type of technics (interview, psychometric test, graphology, selection test, etc..) depending of the organisation strategy (thetime100, 2010, Haffner handout2, 2010, pag. 12). See appendix 9 figure 3.3: Model of recruitment and selection stages)
EMPLOYEE WELFARE
According to Priti Shah (2010), "Employee welfare is a comprehensive term including various services, benefits and facilities offered to employees by the employers. Through such generous fringe benefits the employer makes life worth living for employees." It is statement in line with the philosophy of HRM, which see the employees of an organisation as its most valued assets, therefore need protection (Haffner handout1 pag. 10, 2010).
The Employee welfare can be incited by the state, categorised as statutory and /or by the organisation which is non-statutory.
The statutory welfare such as the Health and Safety at Work etc Act 1974 (HASAW or HSW 1974), EU directives and the Social Charter, influence the management of employee welfare in most successful organisation, inciting the HRM managers to set up policies and rules for compliance (Bratton and Gold, 2007). They also trained and advised senior managers and line managers on the welfare of the employees not only on the legal aspect of the scheme but also on the beneficial aspect regarding the strategy of the organisation.
According to Armstrong (2006, pag 846 10th ed.) the implementation of an employee welfare scheme increases their loyalty and motivation. See appendix 10 figure show the relationship between management and employee wellness
The implementation of employee welfare by an organisation consist of making sure the work place is safe for worker (equipment, working environment, shift pattern, etc) and it also concern issues such stress, counselling, trust fund and many other schemes like the one set up by G4S for its employees in Kenya.
In early 2008 as a result of the post-election violence in Kenya, over 60 employees were left without homes when they were burnt down during the violence. The local (G4S) company quickly put in place a programme of support and assistance for those affected which included counselling for those suffering from post-traumatic stress. Financial assistance from the G4S Employees' Trust Fund helped these employees to rebuild their homes and bring some normality back into their lives. (, 2010)
When such scheme is put in place the Line manager are in charge of making sure the workforce is aware of it existence and monitor it impact on the employees.
PAYMENT AND REWARD OF EMPLOYEE
Among all the process analysed during this essay, payment and reward of the employee is the most strategic for the HRM as it is a contractual exchange where the workforce undertake a certain amount of activities and expect a fair level of payment or reward in return (Bratton and Gold, 2007). It is a strategic process as it has a direct and immediate impact on the behaviour and performance of the workforce affecting the public image or reputation and ability to achieve the operational and strategic smart objectives of an organisation. In the organisations that have adopted the HRM philosophy, a reward management system has been developed by the HRM management to use the payment and reward of the workforce to improve productivity, commitment, services and customers satisfaction without a negative effect on the organisations profit. See appendix 11 Model of reward management: elements and interrelationship
Most payment of employee can be of a fix pre-agree amount which a salary or wage or a performance related reward which can depend on the quality, quantity or profit (Price, 2004, pag 529). Others types of reward are used by organisations to motivate their employee's, rewards such as:
over-time paid double the habitual rate,
commission depending on success,
bonus for harder worker
item produce
profit related
pension scheme
Trust fund
Barclays Bank is an organisation that used bonus reward; they offer an annual discretionary bonus which depends on the performance of both individual employee and their team (, 2010).
The importance of the payment and reward of the employee has been valued as a strategic operation by the HR management which should be aligned or integrated to the organisation operational strategy (Bratton and Gold, 2007, pag 360). According to Price (2007) the reward system consists of integrated policies, process, practices and administrative procedures. This process has also been encouraged or influenced by government legislations such as in UK the Equal pay Act or National Minimum Wage Act.
Act
Date
Coverage
Equal Pay Act
Sex Discrimination
Social Security and Contribution and Benefit Act
Employment Right Act
National Minimum Wage Act
Employment Act
National Minimum Wage Act
1970
1986
1992
1996
1999
2002
2003
Male and female employees to receive equal pay for like work, equivalent work and work of equal value.
Removal from the employer's pay structure, wage regulations, collective agreement, and so on, of any tem that is discriminatory.
Enforcement of statutory maternity pay for a maximum of 18 weeks Employer responsible for sick pay for the first 28 weeks of absence through sickness
Restricts unauthorised deductions and payments from the wages of employees Guaranteed payment for a whole day Right to an itemised pay statement Notice pay if the employer become insolvent
Enforcement of a statutory minimum wage Written statement on wage calculation
Enforcement of a statutory paternity and maternity pay Details or rate of statutory pay
Enforcement notice requiring an employer to pay the minimum wage to an employee amended in relation to past periods and termination of employment
Table 3.4.1: Key UK legislation related to reward management (source: Bratton and Gold, 2007, p.391)
According to CIPD website (2010) the HRM management design the reward system but the practice is delivered by the Line manager. The involvement of the Line manager will depend on the type of reward applied by the organisation; as he would be one explaining the scheme to his team, make decision about who deserve a reward and why (CIPD, 2010).
The understanding of the diversity of what people as a reward regarding to the job satisfaction a lead to development of new concept such as "Total reward". The CIPD defined total reward as ". The table below illustrated the how the two types of reward (financial and non-financial) combined can maximise the motivation, commitment and performance of the workforce.
Financial rewards
Base pay
Total remuneration
Total reward
Contingency pay
Employee benefits
Non-financial rewards
Learning and development
Non-financial /intrinsic rewards
The work experience
Figure 3.6: The components of total reward (source Michael Armstrong, Handbook of HRM Practice 10th Ed. Pag,631, 2006)
It is a concept that has been adopted more and more by organisations as it is seen as powerful tool of looking after their valued asset which their human resource. According to the CIPD (2010) two in five organisations have adopted the total reward system and 22% are planning to do so in the next 12 months. See appendix -table of number of organisations that are implemented the total reward concept and appendix show an illustrated model of total reward pag 633 Armstrong. | https://www.ukessays.com/essays/business/human-resource-management-principles-and-standards-business-essay.php | CC-MAIN-2017-13 | en | refinedweb |
I think that your code does not print anything.
How do you type codes? I am new
please tell
I don't even know how to play. Or code
Have you read the tutorial?
Onboarding puzzleIn C languageHow to attack?everytime I write printf("Attack"); It shows errorhelp
To attack, you need to write the name of the enemy you want to attack. If you use printf("Attack");, it will try to attack an enemy called "Attack", however there are no enemies with this name
printf("Attack");
I'm working with C++, i think i've done my code correctly but the cannon doesn't shoot, could you help me please?
I was having this problem and it turns out there is a print statement at the bottom i was using python and that was holding up the loop once i took it out it started to work. I hope this helps
I just find some errors, you can not do this.like:1. dist is integer, and closet_enemy is a point. how can you use "dist < closet_enemy"?2. how can you use strcat function?
hello everyone,i m a ungraduate student and don t know hot to create a game like this,but more easier,how to start?
Hi, i try to make a struct to storage data from enemies but in main function cin does not get the name of enemies.Any help please?
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
struct Enemy
{
int dist;
string name;
};
int main()
{
list<Enemy> enemies;
// game loop
while (true) {
Enemy a;
cin >> a.name; cin.ignore();
cin >> a.dist; cin.ignore();
enemies.push_back(a);
cout << "Enemy: ";
cout << (*enemies.begin()).name << endl;
cout << "HotDroid" << endl;
// To debug: cerr << "Debug messages..." << endl;
}
}
Hi all,please look at this snippet: val enemy1 = readLine // name of enemy 1 val dist1 = readInt // distance to enemy 1 Console.err.println(enemy1+" "+dist1) val enemy2 = readLine // name of enemy 1 val dist2 = readInt // distance to enemy 1 Console.err.println(enemy2+" "+dist2)
the output is:Standard Error Stream: Nobody 9999 Rock 70WTF the Nobody with distance 9999 is?
"Nobody" is given when there's only one enemy on the screen. Since the input is hardcoded to have 2 enemies always provided, if there's only one, then a "dummy" enemy of "Nobody" is given for one of them. Since it is "very" far away, it should not have any adverse effect on the logic of your program.
@player_one thanks for your answer. The strange thing is that event if there are more then 2 enemies visible (sometimes are 5 at once) you cannot get the name and range of the 3rd, 4th etc. Bug or feature?
That's by design. The description clearly states:
On each start of turn (within the game loop), you obtain information on the two closest enemies
If it seems like the design is a bit strange it's because this puzzle has evolved. It actually used to give you information about all enemies on screen, but that seemed a bit hard for newbies, so now it always makes you choose between two options.
Hello Everyone,
This is Prasad. I am trying to complete first program in URL
This program is about destroying the enemy ships by shooting the closest enemy on each turn.
I am trying to figure out how to pass inputs to this program.
Would be very helpful if someone can answer.
Thanks!!
It depends on the language you are using but you have help in the puzzle (there is a link somewhere).
i know irs so cool i love coding
Hi I need help in how to code python3 | http://forum.codingame.com/t/onboarding-puzzle-discussion/119?page=13 | CC-MAIN-2018-30 | en | refinedweb |
Redux Saga is famous for being easy to test but what if it could be even more comfortable. redux-saga-test-plan by Jeremy Fairbank was designed precisely for this purpose.
Test Double. We believe that software is broken, and we're here to fix it. Our mission is to improve how the world builds software.I'm a software engineer and consultant with
I've been doing front-end development for almost ten years now and enjoy the paradigms that React and Redux helped introduce to the front-end world. I've created a few open source projects that work well with the React and Redux ecosystem such as revalidate, redux-saga-router, and, the topic of this interview, redux-saga-test-plan.
I'm a huge fan of functional programming and Elm. In fact, I'm currently writing a book on Elm with The Pragmatic Programmers called Programming Elm: Build Safe and Maintainable Front-End Applications. The book is over halfway complete and should be available sometime in Spring 2018.
redux-saga-test-plan is a library for easily testing redux-saga.
If you're unfamiliar with redux-saga, check out the redux-saga interview with creator Yassine Elouafi.
redux-saga-test-plan removes the headache of manually testing saga generator functions that couple your tests to their implementations. It offers a declarative, chainable API for testing that your saga yields certain effects without worrying about other effects or the order effects were yielded. It also runs your saga with redux-saga's runtime so that you can write integration tests, or you can use redux-saga-test-plan's built-in effect mocking to write unit tests too.
Let's look at some example sagas to see how redux-saga-test-plan makes it easy to test them.
Given this simple saga for fetching an array of users:
import { call, put } from "redux-saga/effects"; function* fetchUsersSaga(api) { const users = yield call(api.getUsers); yield put({ type: "FETCH_USERS_SUCCESS", payload: users }); }
You can test it with redux-saga-test-plan like this:
import { expectSaga } from "redux-saga-test-plan"; it("fetches users", () => { const users = ["Jeremy", "Tucker"]; const api = { getUsers: () => users, }; return expectSaga(fetchUsersSaga, api) .put({ type: "FETCH_USERS_SUCCESS", payload: users }) .run(); });
The
expectSaga function accepts a saga as an argument as well as any additional arguments for the saga itself. Here, we pass in the
fetchUsersSaga and inject a mock
api to fake the API response.
expectSaga returns a chainable API with lots of useful methods. The
put method is an assertion that the saga will eventually yield a
put effect with the given
FETCH_USERS_SUCCESS action.
The
run method starts the saga. redux-saga-test-plan uses redux-saga's
runSaga function to run the saga like it would be run in your application.
expectSaga tracks any effects your saga yields, so you can assert them like we do with
put here.
Sagas are inherently asynchronous, so redux-saga-test-plan returns a promise from the
run method. You need that promise to know when the test is complete. In this example, we're using Jest so that we can return the promise directly to it.
Because redux-saga-test-plan runs asynchronously, it times out your saga after a set amount of time. You can configure the timeout length.
If you don't inject dependencies like the
api object, you can use
expectSaga's built-in mocking mechanism called providers. Let's say you import
api from another file and use it like this instead:
import { call, put } from "redux-saga/effects"; import api from "./api"; function* fetchUsersSaga() { const users = yield call(api.getUsers); yield put({ type: "FETCH_USERS_SUCCESS", payload: users }); }
You can mock it with the
provide method like this:
import { expectSaga } from "redux-saga-test-plan"; import api from "./api"; it("fetches users", () => { const users = ["Jeremy", "Tucker"]; return expectSaga(fetchUsersSaga) .provide([[call(api.getUsers), users]]) .put({ type: "FETCH_USERS_SUCCESS", payload: users }) .run(); });
The
provide method takes an array of matcher-value pairs. Each matcher-value pair is an array with an effect to match and a fake value to return. redux-saga-test-plan will intercept effects that match and return the fake value instead of letting redux-saga handle the effect. In this example, we match any
call effects to
api.getUsers and return a fake array of users instead.
redux-saga-test-plan can handle more complex saga relationships like this:
import { call, put, takeLatest } from "redux-saga/effects"; import api from "./api"; function* fetchUserSaga(action) { const id = action.payload; const user = yield call(api.getUser, id); yield put({ type: "FETCH_USER_SUCCESS", payload: user }); } function* watchFetchUserSaga() { yield takeLatest("FETCH_USER_REQUEST", fetchUserSaga); }
In this example,
watchFetchUserSaga uses
takeLatest to handle the latest
FETCH_USER_REQUEST action. If something dispatches
FETCH_USER_REQUEST, then redux-saga forks
fetchUserSaga to handle the action and fetch a user by id from the action's
payload. You can test these sagas with redux-saga-test-plan like this:
import { expectSaga } from "redux-saga-test-plan"; import api from "./api"; it("fetches a user", () => { const id = 42; const user = { id, name: "Jeremy" }; return expectSaga(watchFetchUserSaga) .provide([[call(api.getUser, id), user]]) .put({ type: "FETCH_USER_SUCCESS", payload: user }) .dispatch({ type: "FETCH_USER_REQUEST", payload: id }) .silentRun(); });
redux-saga-test-plan captures effects from forked sagas too. Notice that we call
expectSaga with
watchFetchUserSaga but still test the behavior of
fetchUserSaga with the
put assertion.
We use the
dispatch method to dispatch a
FETCH_USER_REQUEST action with a
payload id of
42 to
watchFetchUserSaga. redux-saga then forks and runs
fetchUserSaga.
takeLatest runs in a loop so that redux-saga-test-plan will time out the saga with a warning message. You can safely silence the warning with the alternative
silentRun method since we expect a timeout here.
You can use providers to test your saga's error handling too. Take this new version of
fetchUsersSaga that uses a
try-catch block:
function* fetchUsersSaga() { try { const users = yield call(api.getUsers); yield put({ type: "FETCH_USERS_SUCCESS", payload: users }); } catch (e) { yield put({ type: "FETCH_USERS_FAIL", payload: e }); } }
You can import
throwError from
redux-saga-test-plan/providers to simulate an error in the
provide method:
import { expectSaga } from "redux-saga-test-plan"; import { throwError } from "redux-saga-test-plan/providers"; it("handles errors", () => { const error = new Error("Whoops"); return expectSaga(fetchUsersSaga) .provide([[call(api.getUsers), throwError(error)]]) .put({ type: "FETCH_USERS_FAIL", payload: error }) .run(); });
You can also test your Redux reducers alongside your sagas. Take this reducer for updating the array of users in the store state:
const INITIAL_STATE = { users: [] }; function reducer(state = INITIAL_STATE, action) { switch (action.type) { case "FETCH_USERS_SUCCESS": return { ...state, users: action.payload }; default: return state; } }
You can use the
withReducer method to hook up your reducer and then assert the final state with
hasFinalState:
import { expectSaga } from "redux-saga-test-plan"; it("fetches the users into the store state", () => { const users = ["Jeremy", "Tucker"]; return expectSaga(fetchUsersSaga) .withReducer(reducer) .provide([[call(api.getUsers), users]]) .hasFinalState({ users }) .run(); });
Here are the other effect assertions available for testing.
take(pattern)
take.maybe(pattern)
put(action)
put.resolve(action)
call(fn, ...args)
call([context, fn], ...args)
apply(context, fn, args)
cps(fn, ...args)
cps([context, fn], ...args)
fork(fn, ...args)
fork([context, fn], ...args)
spawn(fn, ...args)
spawn([context, fn], ...args)
join(task)
select(selector, ...args)
actionChannel(pattern, [buffer])
race(effects)
expectSaga. You don't have to manually iterate through your saga's yielded effects, which decouples your test from the implementation.
puta particular
typeof action without worrying about the action payload.
I grew tired of manually testing sagas by iterating through yielded effects like this:
function* fetchUsersSaga() { const users = yield call(api.getUsers); yield put({ type: "FETCH_USERS_SUCCESS", payload: users }); } it("fetches users", () => { const users = ["Jeremy", "Tucker"]; const iter = fetchUsersSaga(); expect(iter.next().value).toEqual(call(api.getUsers)); expect(iter.next(users).value).toEqual( put({ type: "FETCH_USERS_SUCCESS", payload: users }) ); });
These tests took long to write and coupled the test to the implementation. One small change in the order of effects would break a test even if the change didn't change the saga's overall behavior. Ironically, I created a testSaga API that took some of that boilerplate away but still coupled tests to their implementation.
I finally set out to create a more user-friendly API that removed most of the boilerplate and let you focus on testing the behavior you were most interested, and this is how
expectSaga was born.
Writing my Elm book is currently consuming a lot of my time, so I've had to take a short break from redux-saga-test-plan. However, the next big plan is to support redux-saga v1, which adds support for effect middlewares. Effect middlewares let you intercept effects to return a mock value. I hope to simplify
expectSaga's implementation of providers with effect middlewares.
There's a nice backlog of issues for other cool features like new helpful assertions and integrating with a full Redux store too.
Contributors are welcome!
I'm not entirely sure because it depends on the life of redux-saga. Mateusz Burzyński and all the contributors have been doing a great job maintaining it. It's a great sign that they're working toward v1. But front-end development can move and change so fast. For example, we've seen a massive rise in the popularity of RxJS and redux-observable.
As long as there is broad support for redux-saga in front-end applications, I think redux-saga-test-plan will stick around and fill a much-needed testing niche. Testing saga generators is hard, so redux-saga-test-plan will hopefully continue to make it easy. That being said, I don't always get to use redux-saga with my client projects, so I could use the support of other contributors to make redux-saga-test-plan the best it can be for testing.
As far as trends, I think front-end development is heading toward better maintainability and safety with static typing. Elm, TypeScript, and Flow are making it easier to build robust front-end applications. Static types can catch so many simple bugs and mistakes to help you refactor code more confidently.
You don't need to keep up with every new library and framework coming out. Focus on a stack that you like and build fantastic software. Don't let others make you feel like you're not a real developer because you're not up-to-date with the latest JavaScript framework. What's most important is understanding the language you're working with and how to stick to good software engineering practices. Find a mentor that's empathetic and eager to help you.
Also, ask to speak at a meetup or submit to a conference. You'd be surprised how many people sometimes aren't experts on the topics they share (I've been there for sure). You can share the pain points you experienced learning a technology and offer your unique perspective on what you love about it. Then, you can inspire and empower other newcomers.
I might be a little biased because I work for Test Double, but you should interview Justin Searls. He speaks a lot about testing, and his insight is something the JavaScript world would greatly benefit from. He maintains our awesome test double library testdouble.js, which has transformed how I think about mocking in tests.
Thanks for the interview Jeremy! redux-saga-test-plan seems to complement redux-saga well.
You can learn more from the redux-saga-test-plan site and redux-saga-test-plan GitHub page. | https://survivejs.com/blog/redux-saga-test-plan-interview/ | CC-MAIN-2018-30 | en | refinedweb |
BiDi Class
Defines the BiDi Class.When the object is serialized out as xml, its qualified name is w:bidi.
Inheritance Hierarchy
System.Object
DocumentFormat.OpenXml.OpenXmlElement
DocumentFormat.OpenXml.OpenXmlLeafElement
DocumentFormat.OpenXml.Wordprocessing.OnOffType
DocumentFormat.OpenXml.Wordprocessing.BiDi
Namespace: DocumentFormat.OpenXml.Wordprocessing
Assembly: DocumentFormat.OpenXml (in DocumentFormat.OpenXml.dll)
Syntax
'Declaration Public Class BiDi _ Inherits OnOffType 'Usage Dim instance As BiDi
public class BiDi : OnOffType
Remarks
[ISO/IEC 29500-1 1st Edition]
17.3.1.6 bidi (Right to Left Paragraph Layout)
This element specifies that this paragraph shall be displayed from right to left. This property only affects the following set of paragraph-level properties:
ind (§17.3.1.12)
jc (§17.3.1.13)
tab (§17.3.1.37)
textDirection (§17.3.1.41)
This setting alone does not affect the ordering of text within the paragraph – see the rtl element (§17.3.2.30) for a detailed description.
[Example: Consider a paragraph with the bidi property set as follows:
<w:p> <w:pPr> <w:bidi/> </w:pPr> … </w:p>
This paragraph direction is now right to left, which means that all paragraph properties are displayed right to left (e.g. the paragraph marker glyph (if any) is displayed on the right, and indentation for the first line of the paragraph occurs on the right side of the page). end example]
This element’s content model is defined by the common boolean property definition in §17.17.4.
[ISO/IEC 29500-1 1st Edition]
17.6.1 bidi (Right to Left Section Layout)
This element specifies that this section shall be presented using a right-to-left page direction. This property only affects section-level properties, and does not affect the layout of text within the contents of this section.
[Example: Consider a section with the bidi property set as follows:
<w:sectPr> … <w:bidi/> </w:sectPr>
This section direction is now right-to-left, which means that all section level properties are displayed right-to-left (e.g., page numbers are displayed on the right of text; columns are populated from right-to-left). However, the layout of text is determined by properties applied at the text level. end example]
This element’s content model is defined by the common boolean property definition in §17.17.4.
© ISO/IEC29500: 2008.
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also
Reference
DocumentFormat.OpenXml.Wordprocessing Namespace | https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/cc840881(v=office.14) | CC-MAIN-2018-30 | en | refinedweb |
// swap two numbers without using a temporary variable // the numbers can be either integers or floats #include <iostream> using namespace std; int main() { float a = 1.7; float b = -7.1; cout << "a = " << a << " b = " << b << endl; // swap a with b a = a + b; b = a - b; a = a - b; cout << "after swapping a with b:" << endl; cout << "a = " << a << " b = " << b << endl; cin.get(); // wait return EXIT_SUCCESS; }
Are you able to help answer this sponsored question?
Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies. | https://www.daniweb.com/programming/software-development/code/216614/swapping-two-numbers | CC-MAIN-2018-30 | en | refinedweb |
Hi James, you mentioned that this script would be available on ArcGIS Online as a toolbox, where would I find it.
Also would it be available on Portal? We put our Survey 123 on our Portal.
Finally, is it intended to update the script to work with ArcGIS Pro?
Thanks,
Ian Hamilton
We had been running this as a scheduled task on an 2012R windows box and is now failing. Here's the last print statement:
{"replicaName":"","replicaID":"","layerServerGens":[{"id":0,"serverGen":0}],"submissionTime":1588943947580,"lastUpdatedTime":1588944574083,"status":"Completed","resultUrl":"..."}
-Check 63: Completed
-Temporary Directory: c:\users\jcrandal\appdata\local\temp\22\tmpz2orp_
======================
FAIL: Downloading Survey
exception:
File is not a zip file
('File is not a zip file',)
<class 'zipfile.BadZipfile'>
595
----------------------
Hi James,
I am currently trying to troubleshoot this same issue as a python novice. I am scratching my head at the field name issue - isn't this script creating a brand new table? I am only defining a workspace using the tool in ArcMap so why would the creation date field be something I need to change and how do I do that? I do not have an existing table yet as this is only referencing a feature service in our portal.
Thank you!
Mitch
I figured out where to change "CreationDate" to "created_date" as i was doing it in the python script outside of the geoprocessing tool originally. Now I am stuck at a domain assignment error. I'll take another stab tomorrow - but i am wondering if I should try to find a different solution to link inspections back to a feature class automatically as we will eventually move to ArcGIS Pro.
Thanks,
Mitch
Hello,
I am also get the error The application is not licensed to create or modify schema for this type of data. The feature layer have sync enabled and i am exporting to a file gdb.
Any ideas how to resolve?
Thank you
Hello James, I am getting Error 000358: Invalid Expression (MakeFeatureLayer). I am running Desktop 10.7.1. Any suggestions would be appreciated. Thank you
Hi Mitch, did you get any resolution here? I am getting the same message and not sure why.
Hi Survey Admin,
Unfortunately, no I did not get a resolution with this. I decided to take a different approach and generate survey from an existing feature service. Using a relationship class, I am able to inspect a feature on Collector causing it to open up Survey123 and automatically generate our Manhole ID in the associated survey. This is in an enterprise geodatabase using portal for Collector/Survey123.
Best,
Mitch
Hi James Tedrick,
Thanks so much for the great tool. It was recommended as a solution for bringing down survey data on a regular basis. I've just started testing it and I'm getting an error that I think has been mentioned regarding attachments. Currently the service has three layers in it with attachments enabled on the one layer but currently there are no attachments. I'm not sure what the AttributeError: 563 is, but if you could offer any advice it would be much appreciated. Thanks in advance, Kathy
I was wondering if this issue was ever resolved? I am generating the same error on a survey that has a repeat table and attachments.
I also ran this today and got this error. Anyone has an idea what could have caused this?
Check 79: ExportingData
{"replicaName":"","replicaID":"","layerServerGens":[{"id":0,"serverGen":0},{"id":1,"serverGen":0}],"submissionTime":1598515975440,"lastUpdatedTime":1598516802167,"status":"Completed","resultUrl":"..."}
-Check 80: Completed
-Temporary Directory: c:\users\hsa191\appdata\local\temp\arcd2d4\tmpoxkxrq
======================
FAIL: Downloading Survey
exception:
File is not a zip file
['File is not a zip file']
<class 'zipfile.BadZipfile'>
558
----------------------
I am running the script using python 3x. The main things I ran into has to do with urllib2. In Py3 needs to be imported a little differently.
from urllib.request import urlopen
from urllib.parse import urlencode
Then of course remove anything using urllib2.
also where urlencode is being used it needs to be explicity encoded as bytes or 'utf-8' (at least the error I got was a 'TypeError' where the parameters for the url were being treated as string.)
urlencode(replicaParameters).encode("utf-8")
I did not really have any other issue that I can remember aside from those differences in using urllib....
Thanks again for all your work on this James this script has held up over the years!
Hi James Tedrick,
Thank you very much for this tool! I'm hoping to implement this as a scheduled task to send across data to an SQL database from the AGOL Survey 123. I'm test running it to connect to a local GDB and I'm getting this error message.
It has created a table in the destination workspace but fails to copy across the rows.
I have made changes to the code such as "returnAttachments" = False as I'll be only be needing the table to be copied across.
Hoping you or any one from the community can provide guidance with me on this. Thank you very much in advance!
Best regards,
Harmond
Hi, just want to ask if you were able to get around with this? I'm hoping to automate bringing the AGOL data to an SQL database without the attachments as well.
Thank you,
Harmond
Hi Harmond,
The error indicates that something did not allow the destination tables to made correctly. One possible workaround would be for you to create the tables in the enterprise geodatabase. Otherwise, you should troubleshoot with your DBA as to why the table creation is failing.
Thanks, James Tedrick! I was able to get around the issue. Your comments in the python code really helped me debug and configure to suit our needs. The code is running successfully when connecting to a local fgdb and an enterprise gdb. I'm getting 'DBMS table not found' when trying to connect to a non enterprise GDB (MS SQL db)
Will probably coordinate with the database administrator to debug this one.
Thanks, again!
Hi Harmond,
The script was designed to write into eGDB Feature Classes, writing into non-eGDB tables will likely not work at all.
Hi James,
Oh no. That's bad news. Would have any idea if there's a way to sync Survey 123 table to non-eGDB tables (if it's even possible)?
Any chance you can post your python 3 version somewhere? Thanks
Hello GRSM GIS and James Tedrick,
I am running into the same issue noted above with existing tables in an enterprise database and I was wondering what worked for getting it to update when prior tables exist. When I first run the tool, I specified a prefix of YukonPSS_long and that works great. I've never gotten the tool to run successfully again. In the prefix I've tried several options including sde_dcf.DBO.YukonPSS_long, DBO.YukonPSS_long, and YukonPSS_long. In the response above you mention ((i.e., GIS.GRSM_SASQUATCH_SRV_EVENT - this should be found by the search pattern) or capitalization (GRSM vs grsm). What do you mean by search pattern?
Since you said you had made it past this issue I was curious what worked hoping for some insight.
Thanks in advance,
Kathy
Not certain this will solve your issue but for a prefix be sure that your prefix itself does not include an underscore '_' since this is being added by the script after whatever prefix you choose. The fact that it is saying the tables already exist should not cause the tool to fail it should instead check the existing feature class and filter existing features.
Hi Robert!
Thanks for the reply! I didn't have an underscore at the end of the prefix BUT your reply prompted me to think about the prefix I was including with the underscore. Then I looked at the script and found this:
for t in allTables:
tableName = t.split('.')[-1]
nameParts = tableName.split('_')"
So I removed the underscore and renamed my tables in the enterprise geodatabase and reran the tool. It worked!!!!! I need to check it all but at first glance I've never gotten the tool to repeat and sync (I'm so excited!). I wouldn't have thought of the underscore in my naming but that was it. Thank-you!!
I was using this script without issue, but now I have some new surveys (created with 123 v3.11.123) and the script is no longer functioning correctly. It is changing the globalid of the point feature class that my repeat tables are linked to. Anyone have a work around for this since I am using the globalid/parentglobalid fields to link my repeaters to my non-repeater? | https://community.esri.com/t5/arcgis-survey123-blog/migrating-data-from-the-survey-feature-service-to-an-enterprise/bc-p/899936 | CC-MAIN-2021-10 | en | refinedweb |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Good day.
I want to make it possible to reconnect the camera which is bound to the Capture object during the program works. So, it's just a button on the screen and when you click it the camera should be changed. Actually, now there is no matter if it connects to a new or the previous one.
That's the truncated part of the code:
import processing.video.Capture; Capture wirelessCam; void setup() { fullScreen(); smooth(); frameRate(60); connect(); } void draw() { background(#000000); if (wirelessCam.available()) wirelessCam.read(); image(wirelessCam, 0, 0); } void connect() { wirelessCam = new Capture(this, Capture.list()[0]); wirelessCam.start(); } void mouseClicked() { connect(); }
Seems to be an easy block of code working correctly, but, in fact, it isn't. The first time when the program is launched it really shows the webcam video stream. But as only you click the mouse the whole program breaks down - instead of the expected video image you see a lonely useless rectangle the same color as the background.
I've done my best to solve the proplem, combining the functions sequences and adding/removing some parts of code. Unfortunately, I managed to do nothing. Literally, NOTHING.
I will be very grateful to your ideas and any kind of help. Thanks.
Answers
I have tried this before and when I tried to re-define my capture object, I could get even the blue death screen that nobody wants to ever see.
How many capture devices do you have? Or are you just switching resolution settings? One possible idea is to have an array of capture devices and stop and play accordingly.
Kf
There are 22 of them and they're all the same webcam device.
But, you see, that's not the sense. It doesn't change its behaviour while trying to re-connect a different device. You may even add a function like
connect(), but make it bing the
wirelessCamto a Capture object with another characteristics, thoung it still won't work.
Speaking about creating an array of Capture objects - yeah, I had such an idea. The only thing is that this will occupy to much memory, and I'm not sure such an array allows the program work as fast as it is currently.
If you are using the same device, I would suggest instantiating one object at high resolution and then display at lower resolution. This idea might not not suit your needs as I don't know all the details of your application. Can you ellaborate why you want to do this by the way?
Not sure if it is a good idea to have an array of objects manipulating the same device but at different resolutions. You could manipulate multiple cameras. You can instantiate a capture device to each of them and then only process the one you have the focus on.
Kf
Oh god... I've finally found the problem. Still cannot believe that the solution is so easy and, moreover, so evident. Just have a look at this and nothing more should be explained:
Kfrajer, thank you for you ideas.
By the way, the principal reason to have an ability to change the camera connected to a Capture object is that the program should connect to a certain camera with known name and resolution, though it isn't known if it's connected to PC (the camera supposed to be a video stream from video capture card). If it is not at the moment, the program chooses a default one, which stands for the number 0 in
Capture.list().
P.S. I tried to make an array of Capture objects, but it will give the same result if not to use the
cameraName.stop()function. Now I'm sure it has some special sense.
@daniil
Great you found a solution. Thxs for sharing your answer.
Kf
If you're instantiating a
newCapture after stop(), you're probably generating memory leakage! :-SS
In order to make sure all resources are freed up, use dispose() instead. L-) | https://forum.processing.org/two/discussion/22484/ | CC-MAIN-2021-10 | en | refinedweb |
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
tikhop/TPInAppReceipt
TPInAppReceipt
A lightweight library for reading and validating Apple In App Purchase Receipt locally.
Features
- ☑ Extract all In-App Receipt Attributes
- ☑ Hash Verification
- ☑ Verify Bundle Version and Identifiers
- ☑ Signature Verification
Installation
CocoaPods
To integrate TPInAppReceipt into your project using CocoaPods, specify it in your
Podfile:
platform :ios, '9.0' target 'YOUR_TARGET' do use_frameworks! pod 'TPInAppReceipt' end
Then, run the following command:
$ pod install
In any swift file you'd like to use TPInAppReceipt, import the framework with
import TPInAppReceipt.
Swift Package Manager
To integrate using Apple's Swift package manager, add the following as a dependency to your
Package.swift:
.package(url: "", .upToNextMajor(from: "3.0.0"))
Then, specify
"TPInAppReceipt" as a dependency of the Target in which you wish to use TPInAppReceipt.
Lastly, run the following command:
swift package update
Requirements
- iOS 9.0+ / OSX 10.11+
- Swift 5.3+
Usage
Working With a Receipt
InAppReceipt is an object to incapsulate all necessary getters from a receipt payload and provides a comprehensive API for reading and validating in app receipt and related purchases.
Initializing Receipt
do { /// Initialize receipt let receipt = try InAppReceipt.localReceipt() // let receiptData: Data = ... // let receipt = try InAppReceipt.receipt(from: receiptData) } catch { print(error) }
Refreshing/Requesting Receipt
Use this method to request a new receipt if the receipt is invalid or missing.
InAppReceipt.refresh { (error) in if let err = error { print(err) }else{ initializeReceipt() } }
Reading Receipt
/// Base64 Encoded Receipt let base64Receipt = receipt.base64 /// Initialize receipt let receipt = try! InAppReceipt.localReceipt() /// Check whether receipt contains any purchases let hasPurchases = receipt.hasPurchases /// All auto renewable `InAppPurchase`s, let purchases: [InAppPurchase] = receipt.autoRenewablePurchases /// all ACTIVE auto renewable `InAppPurchase`s, let activePurchases: [InAppPurchase] = receipt.activeAutoRenewableSubscriptionPurchases
Useful methods
// Retrieve Original TransactionIdentifier for Product Name receipt.originalTransactionIdentifier(ofProductIdentifier: subscriptionName) // Retrieve Active Auto Renewable Subscription's Purchases for Product Name and Specific Date receipt.activeAutoRenewableSubscriptionPurchases(ofProductIdentifier: subscriptionName, forDate: Date()) // Retrieve All Purchases for Product Name receipt.purchases(ofProductIdentifier: subscriptionName)
Validating Receipt
/// Verify all at once do { try r.verify() } catch IARError.validationFailed(reason: .hashValidation) { // Do smth } catch IARError.validationFailed(reason: .bundleIdentifierVerification) { // Do smth } catch IARError.validationFailed(reason: .signatureValidation) { // Do smth } catch { // Do smth } /// Verify hash try? r.verifyHash() /// Verify bundle identifier and version try? r.verifyBundleIdentifierAndVersion() /// Verify signature try? r.verifySignature()
Essential Reading
- Apple - About Receipt Validation
- Apple - Receipt Validation Programming Guide
- Apple - Validating Receipts Locally
- objc.io - Receipt Validation
License
TPInAppReceipt is released under an MIT license. See LICENSE for more information. | https://swiftpack.co/package/tikhop/TPInAppReceipt | CC-MAIN-2021-10 | en | refinedweb |
Product
Resources
Maxime Castres
January 8, 2020
If you are familiar with our blog you must have seen that we've released a series of tutorials on how to make blogs using Strapi with a lot of frontend frameworks: React, Next.js, Vue, Nuxt.js or Angular.
This one if for React developers who wants to build a simple blog with Strapi!
React is an open-source, front end, JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.
Strapi is the open source Headless CMS. It saves weeks of API development time, and allows easy long-term content management through a beautiful administration panel anyone can use.
Unlike other CMSs, Strapi is 100% open-source, which means:
You may want to directly try the result of this tutorial. Well, we made a starter out of it so give it a try!
The goal here is to be able to create a simple static blog website using Strapi as the backend and React for the frontend The source code is available on GitHub.
We will make this tutorial shorter and more efficient by using our new templates.
This tutorial will always use the latest version of Strapi. That is awesome right!? You'll understand why below. You need to have node v.12 installed and that's all.
take blog-strapi
That's the easiest part of this tutorial thanks to Rémi who developed a series of Strapi templates that you can use for your Blog, E-commerce, Portfolio or Corporate website project.
These templates are Strapi applications containing existing collection-types and single-types suited for the appropriate use case, and data. In this tutorial we'll use the Blog template and connect a React application to it.
Note: for this tutorial, we will use
yarn as your package manager.
yarn create strapi-app backend --quickstart --template
Don't forget that Strapi is running on. Create your admin user by signing up!
That's it! You're done with Strapi! I'm not kidding, we can start to create our Gatsby application now in order to fetch our content from Strapi. Ok ok wait, let's talk about this amazing template you just created.
You should know that before the starters and before the templates we only had tutorials. The idea of creating starters came to us when we realized that we could do something with the end result of our tutorials. Thus were born our starters.
However Strapi evolves quickly, very quickly and at the time the starters constituted a repository including the backend as well as the frontend. This means that updating the Strapi version on all our starters took time, too much time. We then decided to develop templates that are always created with the latest versions of Strapi. Quite simply by passing in parameter the repository of the desired template like you just did. Also, it gives you a good architecture for your Strapi project.
These templates provide a solid basis for your Strapi application.
Feel free to modify all this, however, we will be satisfied with that for the tutorial.
cd backend yarn strapi install graphql
It will allow you to request your content-types using graphql.
Nice! Now that Strapi is ready, you are going to create your React application.
The easiest part has been completed, let's get our hands dirty developing our blog!
React setup
frontendserver by running the following command:
yarn create react-app frontend
Once the installation is completed, you can start your front-end app to make sure everything went ok.
cd frontend yarn dev
You are going to give a better structure to your React application! But first, let's install
react-router-dom
react-router-domby running the following command:
yarn add react-router-dom
Remove everything inside your
src folder
Create an
index.js file containing the following code:
import React from "react"; import ReactDOM from "react-dom"; import App from "./containers/App"; import { BrowserRouter as Router } from "react-router-dom"; ReactDOM.render( <Router> <App /> </Router>, document.getElementById("root") );
What you are doing here is to wrap your
App inside
Router. But what/where is your
App ?
Well we're going to create a
containers folder that will contains your App.
UIkit setup
public/index.htmlin order to use UIkit from their CDN
... <title>React App</title> <link rel="stylesheet" href="" /> <link rel="stylesheet" href="" /> <script src=""></script> <script src=""></script> <script src=""></script> ...
.); }
Please don't force me to explain you some css!
Apollo setup
yarn add apollo-boost @apollo/react-hooks graphql react-apollo
.;
Oh oh! It looks like you don't have any
REACT_APP_BACKEND_URL environment variable yet !
.envfile in the root of your application containing the following line:
REACT_APP_BACKEND_URL=
You'll need to restart your server.
Note: You want Apollo to point to this address. That's the one where you'll be able to fetch your data from your Strapi server.
Appinside the
ApolloProviderand import your
index.cssfile in the
./src/index.js:
import React from "react"; import ReactDOM from "react-dom"; import { ApolloProvider } from "@apollo/react-hooks";! Your app should be ready now! You should have a blank page if everything went ok
You are going to use Apollo to fetch your data from different pages. We don't want you to rewrite the same code every time in your pages. This is why you are going to write a
Query component that will be reusable!
./src/components/Query/index.jsfile containing the following code:
import React from "react"; import { useQuery } from "@apollo/react-hooks"; const Query = ({ children, query, slug }) => { const { data, loading, error } = useQuery(query, { variables: { slug: slug } });
./src/queries/category/categories.jsfile containing the following code:
import gql from "graphql-tag"; const CATEGORIES_QUERY = gql` query Categories { categories { slug name } } `; export default CATEGORIES_QUERY;
Let's use this query to display your categories inside your navbar
..slug}> <Link to={`/category/${category.slug}`} {category.name} </Link> </li> ); })} </ul> </div> </nav> </div> ); }} </Query> </div> ); }; export default Nav;
Since we want our Nav to be in every pages of our application we are going to use it inside our App container
containers/App/index.js
import React from "react"; import Nav from "../../components/Nav"; function App() { return ( <div className="App"> <Nav /> </div> ); } export default App;
Great! You should now be able to see your brand new navbar containing your categories. But the links are not working right now. We'll work on this later in the tutorial, don't worry.
Note: The current code is not suited to display a lot of categories as you may encounter a UI issue. Since this blog post is supposed to be short, you could improve the code by adding a lazy load or something like that.
This container will wrap a component that will display all your articles
./src/queries/article/articles.jsfile containing the following code:
import gql from "graphql-tag"; const ARTICLES_QUERY = gql` query Articles { articles { slug title category { slug name } image { url } } } `; export default ARTICLES_QUERY;
Now we need to create an
Articles component that will display all of your articles and an Card component that will display each of your article:.slug}`} />; })} </div> <div> <div className="uk-child-width-1-2@m uk-grid-match" data-uk-grid> {rightArticles.map((article, i) => { return <Card article={article} key={`article__${article.slug}`} />; })} </div> </div> </div> </div> ); }; export default Articles;
components/Card/index.jsfile containing the following code:
import React from "react"; import { Link } from "react-router-dom"; const Card = ({ article }) => { const imageUrl = process.env.NODE_ENV !== "development" ? article.image.url : process.env.REACT_APP_BACKEND_URL + article.image.url; return ( <Link to={`/article/${article.slug}`}.
Articlescontainer inside your
containers/App/index.js:
import React from "react"; import Articles from "../Articles"; import Nav from "../../components/Nav"; function App() { return ( <div className="App"> <Nav /> <Articles /> </div> ); } export default App;
You can see that if you click on the article, there is nothing. Let's create the article container together! But first, you'll need two packages:} slug={id}> {({ data: { articles } }) => { if (articles.length) { const imageUrl = process.env.NODE_ENV !== "development" ? articles[0].image.url : process.env.REACT_APP_BACKEND_URL + articles[0].image.url; return ( <div> <div id="banner" className="uk-height-medium uk-flex uk-flex-center uk-flex-middle uk-background-cover uk-light uk-padding uk-margin" data-src={imageUrl} data-); } }} </Query> ); }; export default Article;
Let's write the query for just one article now!
./src/queries/article/article.jscontaining the following code:
import gql from "graphql-tag"; const ARTICLES_QUERY = gql` query Articles { articles { slug title category { slug name } image { url } } } `; export default ARTICLES_QUERY;
Article page is ready, we just need to add this new Article container inside the App container. You are going to use the Switch and Route components from
react-router-dom in order to establish a routing system for your article page;
Great! You should be able to get your article now!
You may want to separate your article depending on the categories! Let's create a page for each category then:
./containers/Category/index.jsfile containing the following:
import React from "react"; import { useParams } from "react-router"; import Articles from "../../components/Articles"; import Query from "../../components/Query"; import CATEGORY_ARTICLES_QUERY from "../../queries/category/articles"; const Category = () => { let { id } = useParams(); return ( <Query query={CATEGORY_ARTICLES_QUERY} slug={id}> {({ data: { categories } }) => { if (categories.length) { return ( <div> <div className="uk-section"> <div className="uk-container uk-container-large"> <h1>{categories[0].name}</h1> <Articles articles={categories[0].articles} /> </div> </div> </div> ); } }} </Query> ); }; export default Category;
./src/queries/category/articles.jsfile containing the following:
import gql from 'graphql-tag'; const CATEGORY_ARTICLES_QUERY = gql` query Category($slug: String!){ categories(where: {slug: $slug}) { name articles { slug title content image { url } category { slug name } } } } `; export default CATEGORY_ARTICLES_QUERY;
Category page is ready, we just need to add this new container inside the App container.;
Awesome! You can list articles depending on the selected category now.
Huge congrats, you successfully achieved this tutorial. I hope you enjoyed it!
Still hungry?
Feel free to add additional features, adapt this project to your own needs, and give your feedback in the comment section below.
If you want to deploy your application, check our documentation.
Contribute and collaborate on educational content for the Strapi Community
Can't wait to see your contribution!
One last thing, we are trying to make the best possible tutorials for you, help us in this mission by answering this short survey
Please note: Since we initially published this blog, we released new versions of Strapi and tutorials may be outdated. Sorry for the inconvenience if it's the case, and please help us by reporting it here.
This article was updated on February 15th 2021 | https://strapi.io/blog/build-a-blog-with-react-strapi-and-apollo | CC-MAIN-2021-10 | en | refinedweb |
#include <deal.II/numerics/rtree.h>
Helper structure that allows one to extract a level from an RTree as a vector of BoundingBox objects.
This structure implements a boost::geometry::index::detail::rtree::visitor object, allowing one to visit any existing RTree object, and return the vector of bounding boxes associated to a specific target level of the tree.
Although possible, direct usage of this structure is cumbersome. The suggested usage of this class is through the helper function extract_rtree_level().
Definition at line 300 of file rtree.h.
Construct a vector
boxes of BoundingBox objects corresponding to the
target_level of the tree.
Implements the visitor interface for InternalNode objects. If the node belongs to the
target_leve, then fill the bounding box vector.
Implements the visitor interface for Leaf objects.
A reference to the input vector of BoundingBox objects.
Definition at line 370 of file rtree.h. | https://dealii.org/developer/doxygen/deal.II/structExtractLevelVisitor.html | CC-MAIN-2021-10 | en | refinedweb |
I'm very new to programming, and I mostly know how to adapt from example. So, I'm pulling my hair out trying to get the HMC5883L to work with the Pi. Since it has 3 axis's and uses the first 6 byes from the output just like the ADXL345 accelerometer, I started out by cloning most of the code I was give which works very well for that sensor. However, while I am getting values from the compass, I don't think they're correct, or I'm mis-handling them in the code or calculations to arrive at a correct heading (0-360 in degress).
Has anyone got this sensor working correctly on the Pi yet? I'm hoping someone can help me work through the problem on here, and hopefully I can learn some things along the way. Here's the code I have working so far, but as I mentioned, as I rotate the module the values do change, but they are wrong, they keep going up and down, and don't seem to make it past 90 I'd say.
Of course, as is my style, I've scoured the web for code examples, not all of them include a heading calculation, but that's really what I want. There's a correction for magnetic declination to include as well, but I figured I better get this part working correctly first. Some of the links I've been using to derive commands and code, in addition to the datasheet, are:
Code: Select all
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <linux/i2c-dev.h> #define HMC5883L_I2C_ADDR 0x1e void selectDevice(int fd, int addr, char * name) { if (ioctl(fd, I2C_SLAVE, addr) < 0) { fprintf(stderr, "%s not present\n", name); //exit(1); } } void writeToDevice(int fd, int reg, int val) { char buf[2]; buf[0]=reg; buf[1]=val; if (write(fd, buf, 2) != 2) { fprintf(stderr, "Can't write to HMC5883L\n"); //exit(1); } } int main(int argc, char **argv) { int x, y, z; float head; int fd; int buf[16]; if ((fd = open("/dev/i2c-0", O_RDWR)) < 0) { // Open port for reading and writing fprintf(stderr, "Failed to open i2c bus\n"); exit(1); } /* initialise HMC5883L */ selectDevice(fd, HMC5883L_I2C_ADDR, "HMC5883L"); writeToDevice(fd, 0x3c, 0x70); writeToDevice(fd, 0x3c, 0xA0); writeToDevice(fd, 0x3c, 0x00); usleep(67000); writeToDevice(fd, 0x3c, 0x03); while (1) { /* select HMC5883L */ selectDevice(fd, HMC5883L_I2C_ADDR, "HMC5883L"); buf[0] = 0x06; if ((write(fd, buf, 1)) != 1) { // Send the register to read from fprintf(stderr, "Error writing to i2c slave\n"); //exit(1); } if (read(fd, buf, 6) != 6) { // X, Y, Z readings fprintf(stderr, "Unable to read from HMC5883L\n"); //exit(1); } else { x = buf[0]<<8| buf[1]; y = buf[2]<<8| buf[3]; z = buf[4]<<8| buf[5]; head = atan2 (y,x) * 180 / 3.14159265358979323846; printf("%4.0f\n", head); writeToDevice(fd, 0x3c, 0x03); } usleep(67000); } return 0; } ... no-library- ... pass_v1.0b ... C5883L.cpp
I know it's frowned upon to ask for help without trying enough first, so I've put in about two weeks of playing around with this module and C Code tweaks, and just can't figure it out myself.
Would anyone care to assist? Even if you don't have this module yourself, maybe you can spot obvious errors in the code? Help!
| https://www.raspberrypi.org/forums/viewtopic.php?p=344008 | CC-MAIN-2021-10 | en | refinedweb |
My new post for beginners and learners. So here We'll learn about Import and Export in a very very easy way. Let's go
Import and Export
- In JavaScript ES6, we can import and export functionalities from modules.
- These can be functions, classes, components, constants, essentially anything assign to a JavaScript variable.
- Modules can be single files or a whole folder with one index file as an entry point.
Why to use Import and Export
- The import and export statements in JavaScript help you to share code across multiple files to keep it reusable and maintainable.
- Encapsulation : Since not every function needs to be exported from a file. Some of these functionalities should only be used in files where they have been defined. File exports are a public API to a file, where only the exported functionalities are available to be reused elsewhere. This follows the best practice of encapsulation.
Export before declaration
export const name = Rahul; export function sayHi(user) { alert(`Hello, ${user}!`); } // no; at the end
And import them in another file with a relative path to the first file.
import { name } from './firstfile.js'; console.log(name); // Rahul sayHi(name); // Hello, Rahul! import * as person from './firstfile.js'; console.log(person.name); // Rahul
Imports can have aliases, which are necessary when we import functionalities from multiple files that have the same-named export.
import { name as firstName, sayHi } from './firstfile.js'; console.log(firstName); // Rahul
There is also default statement, which can be used for a few cases:
- To export and import a single functionality
- To highlight the main funuctionality of the exported API o a module To have a fallback import functionality
const person = { firstName: 'Rahul', lastName: 'Singh', }; export default person;
We can leave out the curly braces to import the default export.
import developer from './firstfile.js'; console.log(developer); // { firstName: 'Rahul', lastName: 'Singh' }
That was it explaining the
import and
export in JavaScript. Hope you have found it useful.
Need Help
Need help in raising funds to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.
😎Happy Coding | Thanks For Reading⚡
Discussion (1)
You need to enclose (name = "Rahul") or define Rahul as a variable. Otherwise it'll be misleading to beginners. | https://dev.to/rahxuls/what-is-export-and-import-in-javascript-3p6o | CC-MAIN-2021-10 | en | refinedweb |
Caching Regular Data Benefits Regular Programs, Too
We all know what a dramatic increase in speed we can give a Web application if we choose to use some kind of an output cache for a given Web-based application.
For those who are unfamiliar with the term 'Output Cache', what we generally mean is that any output generated by the application, from a source such as a database, is cached (typically in memory). Then, for further requests to the same page, the cached output is returned, rather than a new copy of the page being created each time.
If you have a lot of database queries that are used to create the page, you can often find doing this will give you a massive increase, but at the expense that the data you're working with could easily get stale.
From .NET 4 onwards, however, using output caching is now much easier to use, and also can be used in a traditional application.
Why Would I Want to Use Output Caching in a Regular Desktop App?
I can answer this using the scenario from a project, I'm currently working on...
"Rate Limits"
I'm currently working on an application that has to interface with various rate-limited API calls to Amazon Web services. The rate limit here is so ferocious that using output caching means that I don't hit my rate limit anywhere near as much as I do without it, simply because it reduces the number of live calls I need to make.
Create yourself a simple .NET console mode program. Then, to that project, add yourself a class called "FakeData.cs".
In this new class, add the following code:
using System; using System.Linq; using System.Threading; namespace datacache { public class FakeData {() { Thread.Sleep(5000); return GenerateRandomString(); } } }
The class is nothing special; it waits 5 seconds each time you call its GetData method, and then returns a random string. The idea here is that it simulates getting data from a Web call, or a database or something similar, and gives the impression of a delay in the process.
In your 'Main' method in Program.cs, make sure you have the following code:
using System; using System.Diagnostics; namespace datacache { class Program { static void Main() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); FakeData myData = new FakeData(); myData.GetData(); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}: {1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime: " + elapsedTime); } } }
If you compile and run this program, you should see something like the following:
Figure 1: Our un-cached program always takes about 5 seconds to get its data.
Just to give things a little bit more effect, let's wrap a loop around this, and execute our get data call 10 times.
Alter your main method so it looks like the following:
static void Main() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for(int count = 0; count < 10; count++) { FakeData myData = new FakeData(); string res = myData.GetData(); Console.WriteLine("Got data: {0}", res); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}: {1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime: " + elapsedTime); } stopWatch.Stop(); }
If you run it now, you should see the following:
Figure 2: Our program now gets 10 items of data with approximately 5 seconds between each run.
The data I'm returning is only randomly generated, and if you really did have data that absolutely had to be different on each call, caching is not a strategy you want to employ. However, if your data was fairly static, and changed little, then the case for caching, even in a desktop program, is a valid one.
Use your project's 'Add Reference' right-click menu, to add the
System.Runtime.Caching
namespace to your project.
Figure 3: Adding the Caching namespace
With this assembly referenced, update your FakeData class, so that it looks like the following:
using System; using System.Linq; using System.Runtime.Caching; using System.Threading; namespace datacache { public class FakeData { ObjectCache _cache = MemoryCache.Default;() { string data = (string) _cache.Get("FakeData"); if(data != null) { return data; } CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10); Thread.Sleep(5000); string result = GenerateRandomString(); _cache.Add("FakeData", result, policy); return result; } } }
The changes we've made to fake data now use the new .NET 4 runtime memory cache, and instead of always going off and taking 5 seconds to re-generate the data each time, every call is now cached for 10 seconds.
If you run your program now, you'll see that it waits only 5 seconds for the first invocation, but every call after that is returned instantaneously:
Figure 4: Our program doesn't hang around once Caching is added to it.
You'll notice straight away that it's the initial call that's cached, and subsequent calls will return that object. If you add an artificial delay inside the for loop by using something like a 'Thread.Sleep' call, you'll see that after 10 seconds, your 'GetData' call will once again generate a new string and then return that as the cached copy.
Found a new API, or just want to know if there's an "API for that?" Come hunt me down on Twitter as @shawty_ds or on Linked-in in the Lidnug .NET users group I help run and ask me about it. I'll quite likely do a future post on the subject.
There are no comments yet. Be the first to comment! | http://www.codeguru.com/columns/dotnet/caching-regular-data-benefits-regular-programs-too.html | CC-MAIN-2017-22 | en | refinedweb |
Beginners: please read this post and this post before posting to the forum.
0 Members and 1 Guest are viewing this topic.
#include "sys/axon.h"#include "servoPWM.h"#include "a2d.h"//user includes#include "kinematics.c" //SoR Biped Engine// Define sensors#define gyro_X ADC_NUMBER_TO_CHANNEL(0)#define gyro_Y ADC_NUMBER_TO_CHANNEL(1)//snip
//initialize variablesint16_t r1L;int16_t r2L;int16_t r4L;//snip
../kinematics.c:24: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'r1L'../kinematics.c:25: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'r2L'../kinematics.c:26: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'r4L'
//initialize variableslong signed int r1L;long signed int r2L;long signed int r4L;
uint16_t counter;
#include <stdint.h>
Try renaming kinematics.c to kinematics.h and then including this h file rather than the c file.Its not good practice to include another C file. The effects are probably undefined and in this case it 'forgets' all the includes from your main file and so 'int16_t' etc are no longer defined and hence the compile error. If its a 'h' file then all is okNb this is a compiler issue/feature not my lib | http://www.societyofrobots.com/robotforum/index.php?topic=8828.0 | CC-MAIN-2017-22 | en | refinedweb |
PMDADSO(3) Library Functions Manual PMDADSO(3)
pmdaDSO - initialize the PMDA to run as a DSO
#include <pcp/pmapi.h> #include <pcp/impl(3), pmdaInterfaceMoved(3) and pmdaTextDADSO(3)
Pages that refer to this page: pmda(3), pmdaattribute(3), pmdachildren(3), pmdadaemon(3), pmdadesc(3), pmdafetch(3), pmdagetoptions(3), pmdahelp(3), pmdainit(3), pmdainstance(3), pmdainterfacemoved(3), pmdaname(3), pmdaopenlog(3), pmdapmid(3), pmdaprofile(3), pmdastore(3), pmdatext(3) | http://man7.org/linux/man-pages/man3/pmdadso.3.html | CC-MAIN-2017-22 | en | refinedweb |
view raw
I've been looking for a way to return specific number of object in the json response when I use the 'GET' method.
class CursaEsport(generics.ListAPIView):
serializer_class = CursaSerializer
def get_queryset(self):
sport = self.kwargs['sport']
return Cursa.objects.filter(esport=sport, visible=True)
Since
Cursa.objects.filter returns a
list, simply limited the number of objects to at most 50 by:
Cursa.objects.filter[:50]
This is known as splicing | https://codedump.io/share/38d9rItwwcc8/1/return-x-number-of-objects-from-cursaobjectsfilter | CC-MAIN-2017-22 | en | refinedweb |
Hi,
I have kind of simple question, but can't find anything usefull on the internet.
In my web application i have a sqldatasource control:
<asp:SqlDataSource
<SelectParameters>
<asp:Parameter
</SelectParameters>
</asp:SqlDataSource>
protected void sourceTrainingDate_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
View Complete Post
I am trying to create following function which should return table but when I try to create it I get error message as "Select statements included within a function cannot return data to a client.". I am looking for
workaround for this issue.
create
function dbo.GetCategoryIdTillBase(@Category_Id
as
char
Insert
into ReportDetail( Partcipantid, Reportid)
distinct ParticipantID
, 9 from OpenCredit
except select ParticipantID, 9
from StoreCredit where Closed
= 0
Issue is that when above select statement returns no row, it seems like no record is
Hi Dude,
I am new to Sql server 2005. I have a table in which contains many data. I need to take particular data. For example, I want to take value of 110652.795813712 from FTEBASEPAY column . So i have wrote the sql statment like in below.
SELECT * From tblEmployees where FTEBASEPAY='53842.7782655718'
SELECT * From tblEmployees where FTEBASEPAY='53842.7782655718'
But i am not able to get the particular value. Manually i have seen the tblEmployees table, in which contains the particular data ('53842.7782655718').
When i execute the above select statement, there is no result for it. Please let me know anyone face the same problem? Please give a solution for it. What i have to for overcome this issue?I have to give one more information, the FTEBASEPAY dataType is float in tblEmployees table.
Thanks in Advance.Ad
Hello,
I am adding table rows dynamically, after I return from a post back, these rows disappear.
Is there a way to preserve these rows and add them back on page load???????????"
Hello SQL CLR experts,
We're using SQL Server 2008 R2 (French) and Visual Studio 2008. I'm trying to get a "simple" SQL CLR to work, which calls DriveInfo.GetDrive() and returns drive name, space available and total size into a SQL Table from the UDF GetDriveInfo() defined
below. I need help getting the code to work.
I realize that there is already an xp_fixeddrives extended stored procedure that returns only the available space. I want to return the Total Size of each drive, the volume name, etc.
I based my code on the article but I want to use DriveInfo.GetDrive() instead of DirectoryInfo.GetFileSystemInfos(). I was successfully able to get the DirectoryInfo assembly from the article to work, but I am having trouble
getting my DriveInfo.GetDrive() adaptation to work.
In Visual Studio, I created a new C# SQL Server project and am using the following code:
using System;
using System.IO;
using System.Collections;
using System.Data;
using System.Data.SqlClient; | http://www.dotnetspark.com/links/35301-if-value-is-not-mssql-table-return-something.aspx | CC-MAIN-2017-22 | en | refinedweb |
This new version is compatible with Maya 2011, 2012 and 2013.
IMPORTANT: Please read carefully the documentation before using poseLib!!!
Documentation and installation instructions can be found on my website. Also that's where you'll find regularly updated versions.
PoseLib is based on a donation system. It means that if it is useful to you or your studio then you can make a donation to reflect your satisfaction. Thanks for using poseLib!
Updated: 26 July 2012
- Fixed right-click menu not displaying properly in Maya 2013.
-.
- Now only shows poses whose file actually exists (no more empty red icons).
Description:
PoseLib is being used in production throughout the world by feature animation studios and video-game companies.
It allows you to record a pose for any object in Maya (more precisely anything that has keyable channel attributes). Whether it is the hyper complex character rig you just created or a simple Nurbs sphere or a basic Lambert shader: You just have to select the object(s), hit the "Create New Pose" button, and a pose file is created in the relevant directory, along with the corresponding icon (a .bmp file).
Features:
- Works on anything at anytime (no "character map" or specific rig layout or particular naming required).
- You can blend between the current pose and the clicked one by holding down the ALT or CTRL key and clicking on a pose.
- Lets you choose the icon size you like (from 32x32 to any custom size/ratio up to 512x512).
- Works with referenced/unreferenced characters (you can even edit the namespace).
- Lets you organize your poses by characters (e.g.: Babar, Tintin...) and categories (e.g.: Face, Body...).
- You can rename, delete, replace or move any pose from any character or category.
- You can quickly select the objects/controls that are part of a specific pose.
- You can also remove, add or replace specific objects/controls in a pose.
- You can apply a pose specifically to the channels selected in the channel box.
Enjoy!
Please use the Feature Requests to give me ideas.
Please use the Support Forum if you have any questions or problems.
Please rate and review in the Review section. | https://www.highend3d.com/maya/script/poselib-for-maya | CC-MAIN-2017-22 | en | refinedweb |
JUnit 5 State Of The UnionBy Nicolai Parlog
JUnit 5 has been under development for about 14 months now and the prototype is almost a year old. Time to summarize what happened so far, where the project stands, and where it’s going.
All technical details are based on the current JUnit version, milestone 2. You will find more information in the official user guide, with separate versions for milestone 2 and the most recent build, or on my blog, where I wrote a series about JUnit 5, that I update whenever a new milestone is released.
Previously On Battlestar JUnit
Why JUnit 5? Why not 4.13, which has been in the making since, err, forever? Two and a half reasons…
Goodbye, JUnit 4
Part of JUnit’s success comes from its great tool support, for which tool creators went as far as using reflection (down to private fields) to access information that the API would not hand out. This bound tools to implementation details, which in turn made it hard for JUnit’s maintainers to evolve it – nobody likes breaking downstream projects. This is an important reason for why JUnit’s progress has basically come to a halt.
Then there are the runners and the rules. They were created to extend JUnit and did a good job at that – good but not superb. Runners are a heavyweight concept where one has to manage the whole test lifecycle. But worse, you can only use a single runner at a time – a very strict limitation. That’s why rules were introduced in 4.7. While much simpler and mostly composable, they have other drawbacks – namely that they are limited to certain kinds of behavior, which can best be summarized as before/after.
Last and least was the Java version. Everybody wants to play with lambdas nowadays and having JUnit 4 require Java 8 would have been a hard sell.
Hello, JUnit 5
So in 2015 a team formed around the idea of a complete rewrite. At first dubbed JUnit Lambda, the project did a successful crowdfunding campaign and came up with enough money and employer sponsorship to work on it full time for six months. Workshops, a prototype, an alpha version, and two milestones followed and since earlier this year the project is called JUnit 5. By now, the funds are used up and it is developed like so many other great open source projects: by dedicated people in their free time during the day’s first and last hours.
The team is currently completing the third milestone and has plan for a least two more before a release candidate is even considered. But we’ll come back to that. Let’s first look at what we’ve got in our hands at the moment.
More from this author
What Does It Look Like?
Instead of going into details about the new API I ask you to imagine a full blown JUnit 4 tests with all the shenanigans the API offers. Here’s how JUnit 5 is different in comparison to that:
- Test classes and methods can be package visible.
- Interface default methods can be test methods.
@Testno longer takes parameters. Expected exceptions and timeouts are realized via assertions.
- You can create tests dynamically at run time with
@TestFactoryannotated methods (more on that later).
- The lifecycle annotations got new names:
@Beforebecame
@BeforeEachand
@BeforeClassis now
@BeforeAll; likewise for
@After....
@Ignorechanged to
@Disabled.
- In assertions, failure messages come last and can be created lazily.
- A new assertion
assertAllexecutes the given checks and always reports all results, even if some assertions failed.
@Nestedcan be used to run tests in inner classes.
@DisplayNameassigns human readable names to tests.
- Runners and rules are gone and replaced by a new extension mechanism that integrates seamlessly with the native API (more on that later).
- Tests can have parameters, where instances are created by extensions (again, later).
All in all, this is what a test class might look like:
@DisplayName("Some example test cases") class ExampleTests { @BeforeAll static void initAll() { } @BeforeEach void init() { } @Test @DisplayName("Custom test name containing spaces") void succeedingTest() { } @Test void groupedAssertions() { // In a grouped assertion all assertions are executed, and any // failures will be reported together. assertAll("address", () -> assertEquals("John", address.getFirstName()), () -> assertEquals("User", address.getLastName()) ); } @Test @DisplayName("😱") @Disabled("for demonstration purposes") void skippedTest() { // not executed } @Test @CoolInstanceProvider void testWithParameters(MyCoolClass coolInstance) { // do something with 'coolInstance' } @TestFactory Collection<DynamicTest> dynamicTestsFromCollection() { return Arrays.asList( dynamicTest("1st dynamic test", () -> assertTrue(true)), dynamicTest("2nd dynamic test", () -> assertEquals(4, 2 * 2)) ); } @AfterEach void tearDown() { } @AfterAll static void tearDownAll() { } @DisplayName("Some nested test cases") class NestedTest { @Test @DisplayName("╯°□°)╯") void failingTest() { fail("a failing test"); } } }
As for
@Nested and
@DisplayName, this is what it looks like to run an example written by the JUnit team in IntelliJ 2016.2:
Not bad, right? For more have a look at the user guide or my post covering the basics.
How Can I Use It?
To start writing tests all you have to do is include the API artifact
org.junit.jupiter:junit-jupiter-api:5.0.0-M2 in your project. Unfortunately, running tests is a little more complicated…
IDEs
Native IDE support is a must-have for any serious testing framework. JUnit 5 is not there yet but that’s understandable considering that it is not even officially released.
- IntelliJ, since 2016.2, has built-in support that works reasonably well.
- The Eclipse team started working on it – see the corresponding issues in JUnit’s and in Eclipse’s bug tracker.
- NetBeans has no support and I could not even find an issue.
Build Tools
What about native build tool support? The JUnit team implemented a Maven Surefire provider and a Gradle plugin but these are just proofs of concept. To fully integrate and battle-test them, the team would like the respective projects to take over these code bases.
- For Maven that process just started by relicensing the source code under the Apache License. An issue in Apache’s JIRA tracks the progress.
- I saw no Gradle-related activity on the JUnit project and could not find an issue related to JUnit 5.
Fallbacks
This situation is a little unsatisfactory but luckily there are alternatives. One is to simply wrap all JUnit 5 tests in a JUnit 4 test suite and rely on JUnit 4 support:
@RunWith(JUnitPlatform.class) @SelectPackages({ "my.test.package" }) public class JUnit5TestSuite { }
See the user guide for setup details.
The other alternative is the console launcher. Again, see the user guide to get started and check out my JUnit setup post if you run into problems. When you’re done, you can run tests as follows:
junit-platform-console -p -p target/classes/:target/test-classes -a
Outer Space
Now that you know how to write and run JUnit 5 tests, let’s go beyond the basics and take a peek into more advances topics.
Dynamic Tests
Dynamic tests are a new concept in JUnit 5. They allow the easy creation of tests at run time that tools will recognize as full test cases.
An example explains this best. Assume you have a method
testPoint(Point p) that asserts something on the given point and you want to run that test for a host of points. You could write a simple loop around it:
@Test void testPoints() { getTestPoints().forEach(this::testPoint); }
This has the substantial drawback that while, conceptually, these are many tests, to JUnit it’s just one. First among the undesired consequences is that as soon as the first test fails all others aren’t even executed. Another is that tools, IDEs in particular, will report this as a single test, which is not ideal either.
JUnit 5 gives us an out. Test code can be wrapped into a
DynamicTest instance that is created at run time. Methods that return them can be annotated with the new
@TestFactory annotation and JUnit will call them, insert the created tests into the test plan, and execute them.
@TestFactory Stream<DynamicText> testingPoints() { return getTestPoints() .stream() .map(p -> dynamicTest("Testing " + p, () -> pointTest(p))); }
Neat. And if you really want to, you can use dynamic tests to write tests with lambda expressions
Extension Model
I already alluded to JUnit 4’s runners and rules. They are gone, replaced by extension points, which third party code can interact with. Here’s how that works.
Extension Points
For most steps in a test’s lifecycle an extension point exists:
- Test Instance Post Processor
- BeforeAll Callback
- Test and Container Execution Condition
- BeforeEach Callback
- Parameter Resolution
- Before Test Execution
- After Test Execution
- Exception Handling
- AfterEach Callback
- AfterAll Callback
For each of these extension points exists an interface and since the points are very focused the interfaces are quite simple. Here’s the one for the Before Each callback:
public interface BeforeEachCallback extends Extension { void beforeEach(TestExtensionContext context) throws Exception; }
I already bullet-pointed out that tests can have parameters. Since JUnit has no idea how to create an instance of
MyCoolClass, extensions have to provide them. Here’s that extension point:
public interface ParameterResolver extends Extension { boolean supports( ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException; Object resolve( ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException; }
For each parameter, JUnit will call
support on every registered extension, throw an exception if not exactly one of them returns
true, and otherwise request the one extension to resolve the parameter.
As a proof of concept, the team wrote a Mockito extension, which mocks parameters marked with
@Mock. It can be used as follows:
void myCoolClassTest(@Mock MyCoolClass instance) { // ... }
Writing Extensions
To create an extension you simply implement the interfaces corresponding to the extension points you want to interact with and register your class with JUnit. During test execution JUnit will pause at each extension point, gather all relevant information into an
ExtensionContext instance, and call all extensions that registered with that point.
The extension context gives access to many interesting things, for example the test class or method as
AnnotatedElements, so an extension can reflect over them. Then there is the
ExtensionStore. Because JUnit has no interest in tracking extension instances, it makes no guarantees about their lifecycle. Extension classes should hence be stateless and can use the store to persist information. Another interesting aspect is the
TestReporter, which allows extensions (and tests for that matter) to publish messages in a way that can easily be picked up by external tools.
Put together, a benchmark extension that simply reports a test’s run time looks as follows:
class SimpleBenchmarkExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback { // we need a namespace to access the store and a key to persist information private static final Namespace NAMESPACE = Namespace .create("com", "sitepoint", "SimpleBenchmarkExtension"); private static final String LAUNCH_TIME_KEY = "LaunchTime"; @Override public void beforeTestExecution(TestExtensionContext context) { storeNowAsLaunchTime(context); } @Override public void afterTestExecution(TestExtensionContext context) { long launchTime = loadLaunchTime(context); long elapsedTime = currentTimeMillis() - launchTime; report(context, elapsedTime); } private static void storeNowAsLaunchTime(ExtensionContext context) { context.getStore(NAMESPACE).put(LAUNCH_TIME_KEY, currentTimeMillis()); } private static long loadLaunchTime(ExtensionContext context) { return context.getStore(NAMESPACE).get(LAUNCH_TIME_KEY, long.class); } private static void report(ExtensionContext context, long elapsedTime) { String message = String .format("Test '%s' took %d ms.", context.getDisplayName(), elapsedTime); // 'publishReportEntry' pipes key-value pairs into the test reporter context.publishReportEntry(singletonMap("Benchmark", message)); } }
Registering Extensions
I glossed over how extensions can be registered. But a very cool feature is hiding here! Read my post on extensions to find out how you can get your extension to look as follows:
@Benchmark @Test void test() { // ... }
Architecture
Quick dive into the architecture, which is really interesting. To separate concerns of testers, extension developers, and tools as well as to allow other testing frameworks to benefit from JUnit’s great tool support (well, it’s not quite there yet but it will be) JUnit 5 is split into three subprojects:
- JUnit Jupiter provides the API that we have talked about so far and an engine that discovers and runs tests.
- JUnit Vintage adapts JUnit 3/4 to run within JUnit 5’s new architecture, which means it also provides an engine.
- JUnit Platform is where the magic happens. It provides an API for tools to instruct test execution and when that gets called, it locates test engines (like the two above), forwards the instruction to them, and lets them do their thing.
For one this makes it easy to run JUnit 3, 4, and 5 tests within the same mechanism. But the separation between the platform, which contains the engine API, and the engine implementations also allows the integration of all kinds of testing frameworks into the JUnit mechanism. Assuming a TestNG engine would exist, this is how that would turn out:
This is a big deal! Creating a new testing framework is an uphill battle because adoption depends on tool support and tool support depends on adoption. Now frameworks can break out of that vicious cycle! They can implement a JUnit engine and get full support in many tools from day 1.
This might give rise to a new generation of testing frameworks!
The Road From Here
JUnit is in very good shape and can already be used to replace vanilla JUnit 4. But, in accordance with the Pareto Principle, there is still some work to be done before it is ready to fulfill all use cases.
Ongoing Discussions
A lot of very interesting topics are being discussed!
JUnit 4 Compatibility
Wouldn’t it be great to create adapters for existing JUnit 4 rules? That would make migrating tests to JUnit Jupiter’s API (as opposed to just running them within JUnit 5) a lot easier. Issue #433 is exploring exactly that. But code is not the only good thing a project can produce. Issues #169 and #292 aim at providing a good migration guide from 4 to 5.
Extension Model
Personally, I think something’s missing from dynamic tests. It would be great for extensions to interact with this feature! One way to do that would be an extension point into which third party libraries could hook to inject dynamically created tests. They could then come up with interesting APIs to parameterize tests, for example. Talk is cheap. though, so I created an issue and a prototypical implementation for that feature. I hope it will be looked into during development of milestone 4.
Another detail is that while test factory methods are part of the full lifecycle, the dynamic tests they create are not. Meaning before and after callbacks or parameter resolution do not work for dynamic tests. This is tracked by an issue and I am sure a solution will be found before the release.
It is also currently not possible to interact with Jupiter’s threading model. This is a problem for extensions that want to push tests onto other threads, for example to make sure that Swing or JavaFX tests run on the Event Dispatch Thread or the Application Thread, respectively. There are several issues addressing this: #16, #20, #157
Other interesting topics:
- extension points…
- a global extensions registry, #448
- extensions on fields, #497
- an API for programmatic extension management, #506
Scenario Tests
A big topic are scenario tests, which is JUnit’s nomenclature for tests that are ordered and operate on common state (tracked by #48). TestNG offers this already and is an important reason for people to move away from JUnit. Well was a reason.
Let’s say we have a class encapsulating a REST API. With scenario tests we could have a first test that creates an instance, a second test could initialize it, a third logs in a user, and so forth. The state remains from test to test and those are mutating it in a fashion that prepares it for the next.
Others
Here are a couple of other interesting ideas:
- a mechanism for the launcher to detect engine capabilities, #90
- sanity checks for test code written by developers, #121
- lots of improvements on the console launcher, search filter
- a more flexible threading model, e.g. to parallelize tests, search filter
More Milestones
So what’s the plan for the following months? Sometime during the next couple of weeks milestone 3 will be released, which focuses on interoperability with JUnit 4 and an improved API for tools. After that, two more milestones are scheduled, number 4 focusing on parameterized tests, enhanced dynamic tests, and documentation, and number 5 on scenario tests, repeated tests, and test execution in user-defined thread.
Summary
We took a quick tour through the API we’re going to write tests against and saw that it was similar to JUnit 4’s but contains a lot of thoughtful additions. Most notably are built-in support for nested tests, human-readable display name and dynamically created tests. The extension model is very promising and the architecture, splitting JUnit 5 into Jupiter, Vintage and Platform, is just gorgeous, endowing other test frameworks with full tool support as soon as they’re implementing an engine.
On the soft side, we’ve gone through the history behind JUnit 5 and spent some time discussing the current state of tool support, which – with the exception of IntelliJ – is still lacking. We finally looked at some of the ongoing discussion and future developments, which I think are as thrilling as they are promising. I can’t wait to see the JUnit 5 GA release – hopefully some time in 2017. | https://www.sitepoint.com/junit-5-state-of-the-union/?utm_source=sitepoint&utm_medium=articletile&utm_campaign=comments&utm_term=java/ | CC-MAIN-2017-22 | en | refinedweb |
Ticket #11998 (closed Bugs: fixed)
Static const variables cannot be logged
Description
Static const variables cannot be logged for me any more. I am using RHEL 7.1 and the Intel icpc for my programms (boost compiled with gcc 4.8.3)
The following code does not work in 1.60.0 but does in 1.59.0 Maybe it has to do with the changes regarding formatting_ostream #11549 or #11545
Code:
/* * File: main.cpp * Author: hschall * * Created on February 18, 2016, 6:53 AM */ #include <cstdlib> #define BOOST_LOG_DYN_LINK #include <boost/log/trivial.hpp> class TestStaticError{ public: static void doLog(){ BOOST_LOG_TRIVIAL(debug) << myVar; } private: static const unsigned int myVar = 1337; }; class TestStaticWorking{ public: static void doLog(){ BOOST_LOG_TRIVIAL(debug) << (unsigned int)myVar; } private: static const unsigned int myVar = 1337; }; using namespace std; /* * */ int main(int argc, char** argv){ TestStaticWorking::doLog(); // Works // Works in 1.59.0 //TestStaticError::doLog(); // main.cpp:21: undefined reference to `TestStaticError::myVar' return 0; }
Attachments
Change History
comment:2 Changed 15 months ago by Hendrik Schall <torres@…>
The workaround is just to show that this behaviour relates to the static variable.
I compile with C++11 (but tested it also with C++98 and C++14). I did test it with the GCC (4.8.3) now aswell, same behaviour.
Wether it is a bug or not, it depends on the boost library version, which is strange.
comment:3 Changed 8 months ago by o.z
I see similar problem using bitfields:
I took the example from and added a bitfield print:
#include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> namespace logging = boost::log; //[ example_tutorial_trivial_with_filtering void init() { logging::core::get()->set_filter ( logging::trivial::severity >= logging::trivial::info ); } struct BF { unsigned int b : 8; BF() : b(0) {} }; int main(int, char*[]) { init(); BF bf; BOOST_LOG_TRIVIAL(info) << "An informational severity message " << bf.b; return 0; } //]
With boost 1.60 I got a compilation error:
cannot bind bitfield 'bf.BF::b' to 'unsigned int&'
With boost 1.57 the code is compiled and run (prints: [2016-09-19 20:21:33.018112] [0x000007fd1d5be672] [info] An informational severity message 0)
comment:4 Changed 8 months ago by andysem
- Status changed from new to closed
- Resolution set to fixed
Should be fixed in. Thanks for the report.
I don't think this is a bug in the library.
The static constant members have to be defined in some (one) translation unit, which gives them storage. In C++11 and later this is required if a reference to the variable is taken, which happens when you call the operator<<. In pre-C++11 versions of the language, IIRC, the definition is required unconditionally.
The type conversion that you use as a workaround makes the operator<< bind the reference to a temporary, that's why it works. I'm not sure how it works differently in 1.59 since I don't see any changes that could lead to that but there were such changes since 1.58 - the operator<< overloads could have been chosen differently before, which would result in not taking the reference.
However, I can see that your use case could be useful, and I'll see if I can support it in the future. | https://svn.boost.org/trac/boost/ticket/11998 | CC-MAIN-2017-22 | en | refinedweb |
> #include <stdlib.h> #include <stdio.h> #include <vector> #include <string> #include <time.h> using namespace std; int main() { string query_string; query_string = getenv("CONTENT_LENGTH"); cout << "content-type: text/html" << endl << endl; cout << "<html><body>test</body></html>" << endl; int nLen = atoi(query_string.c_str()); char* pBuf = new char[nLen + 1]; cin.read(pBuf,nLen); delete[] pBuf; return 0; }
If you are experiencing a similar issue, please ask a related question
Join the community of 500,000 technology professionals and ask your questions. | https://www.experts-exchange.com/questions/26471122/Trying-to-run-a-c-cgi-post.html | CC-MAIN-2017-22 | en | refinedweb |
Linus, Al,I'd like to ask for overlayfs to be merged into 3.1. git://git.kernel.org/pub/scm/linux/kernel/git/mszeredi/vfs.git overlayfs.v10AFAICS the only barrier now is the upcoming changes to the VFS/openinterface. Is there anything I can help to get those changes done?Thanks,Miklos---Andy Whitcroft (1): overlayfs: add statfs supportErez Zadok (1): overlayfs: implement show_optionsMiklos Szeredi (4): vfs: add i_op->open() vfs: export do_splice_direct() to modules vfs: introduce clone_private_mount() overlay filesystemNeil Brown (1): overlay: overlay filesystem documentation--- Documentation/filesystems/overlayfs.txt | 167 ++++++++ MAINTAINERS | 7 + fs/Kconfig | 1 + fs/Makefile | 1 + fs/namespace.c | 17 + fs/open.c | 76 +++-- fs/overlayfs/Kconfig | 4 + fs/overlayfs/Makefile | 7 + fs/overlayfs/copy_up.c | 383 +++++++++++++++++++ fs/overlayfs/dir.c | 607 ++++++++++++++++++++++++++++++ fs/overlayfs/inode.c | 375 ++++++++++++++++++ fs/overlayfs/overlayfs.h | 62 +++ fs/overlayfs/readdir.c | 558 +++++++++++++++++++++++++++ fs/overlayfs/super.c | 625 +++++++++++++++++++++++++++++++ fs/splice.c | 1 + include/linux/fs.h | 2 + include/linux/mount.h | 3 + 17 files changed, 2870 insertions(+), 26 deletions(-) create mode 100644 Documentation/filesystems/overlayfs.txt create mode 100644 fs/overlayfs/Kconfig create mode 100644 fs/overlayfs/Makefile create mode 100644 fs/overlayfs/copy_up.c create mode 100644 fs/overlayfs/dir.c create mode 100644 fs/overlayfs/inode.c create mode 100644 fs/overlayfs/overlayfs.h create mode 100644 fs/overlayfs/readdir.c create mode 100644 fs/overlayfs/super.c------------------------------------------------------------------------------Changes from v9 to v10- prevent d_delete() from turning upperdentry negative (reported by Erez Zadok)- show mount options in /proc/mounts and friends (patch by Erez Zadok)- fix off-by-one error in readdir (reported by Jordi Pujol)------------------------------------------------------------------------------Changes from v8 to v9- support xattr on tmpfs- fix build after split-up- fix remove after rename (reported by Jordi Pujol)- fix rename failure case------------------------------------------------------------------------------Changes from v7 to v8:- split overlayfs.c into smaller files- fix locking for copy up (reported by Al Viro)- locking analysis of copy up vs. directory rename added as a comment- tested with lockdep, fixed one lock annotation- other bug fixes------------------------------------------------------------------------------Changes from v6 to v7- added patches from Felix Fietkau to fix deadlocks on jffs2- optimized directory removal- properly clean up after copy-up and other failures------------------------------------------------------------------------------Changes from v5 to v6- optimize directory merging o use rbtree for weeding out duplicates o use a cursor for current position within the stream- instead of f_op->open_other(), implement i_op->open()- don't share inodes for non-directory dentries - for now. I hope this can come back once RCU lookup code has settled.- misc bug fixes------------------------------------------------------------------------------Changes from v4 to v5- fix copying up if fs doesn't support xattrs (Andy Whitcroft)- clone mounts to be used internally to access the underlying filesystems------------------------------------------------------------------------------Changes from v3 to v4- export security_inode_permission to allow overlayfs to be modular (Andy Whitcroft)- add statfs support (Andy Whitcroft)- change BUG_ON to WARN_ON- Revert "vfs: add flag to allow rename to same inode", instead introduce s_op->is_same_inode()- overlayfs: fix rename to self- fix whiteout after rename------------------------------------------------------------------------------Changes from v2 to v3 - Minimal remount support. As overlayfs reflects the 'readonly' mount status in write-access to the upper filesystem, we must handle remount and either drop or take write access when the ro status changes. (NeilBrown) - Use correct seek function for directories. It is incorrect to call generic_llseek_file on a file from a different filesystem. For that we must use the seek function that the filesystem defines, which is called by vfs_llseek. Also, we only want to seek the realfile when is_real is true. Otherwise we just want to update our own f_pos pointer, so use generic_llseek_file for that. (NeilBrown) - Initialise is_real before use. The previous patch can use od->is_real before it is properly initialised is llseek is called before readdir. So factor out the initialisation of is_real and call it from both readdir and llseek when f_pos is 0. (NeilBrown) - Rename ovl_fill_cache to ovl_dir_read (NeilBrown) - Tiny optimisation in open_other handling (NeilBrown) - Assorted updates to Documentation/filesystems/overlayfs.txt (NeilBrown) - Make copy-up work for >=4G files, make it killable during copy-up. Need to fix recovery after a failed/interrupted copy-up. - Store and reference upper/lower dentries in overlay dentries. Store and reference upper/lower vfsmounts in overlay superblock. - Add necessary barriers for setting upper dentry in copyup and for retrieving upper dentry locklessly. - Make sure the right file is used for directory fsync() after copy-up. - Add locking to ovl_dir_llseek() to prevent concurrent call of ovl_dir_reset() with ovl_dir_read(). - Get rid of ovl_dentry_iput(). The VFS doesn't provide enough locking for this function that the contents of ->d_fsdata could be safely updated. - After copying up a non-directory unhash the dentry. This way the lower dentry ref, which is no longer necessary, can go away. This revealed a use-after-free bug in truncate handling in fs/namei.c:finish_open(). - Fix if a copy-up happens between the follow_linka the put_link calls. - Replace some WARN_ONs with BUG_ON. Some things just _really_ shouldn't happen. - Extract common code from ovl_unlink and ovl_rmdir to a helper function. - After unlink and rmdir unhash the dentry. This will get rid of the lower and upper dentry references after there are no more users of the deleted dentry. This is a safe replacement for the removed ->d_iput() functionality. - Added checks to unlink, rmdir and rename to verify that the parent-child relationship in the upper filesystem matches that of the overlay. This is necessary to prevent crash and/or corruption if the upper filesystem topology is being modified while part of the overlay. - Optimize checking whiteout and opaque attributes. - Optimize copy-up on truncate: don't copy up whole file before truncating - Misc bug fixes------------------------------------------------------------------------------Changes from v1 to v2 - rename "hybrid union filesystem" to "overlay filesystem" or overlayfs - added documentation written by Neil - correct st_dev for directories (reported by Neil) - use getattr() to get attributes from the underlying filesystems, this means that now an overlay filesystem itself can be the lower, read-only layer of another overlay - listxattr filters out private extended attributes - get write ref on the upper layer on mount unless the overlay itself is mounted read-only - raise capabilities for copy up, dealing with whiteouts and opaque directories. Now the overlay works for non-root users as well - "rm -rf" didn't work correctly in all cases if the directory was copied up between opendir and the first readdir, this is now fixed (and the directory operations consolidated) - simplified copy up, this broke optimization for truncate and open(O_TRUNC) (now file is copied up to be immediately truncated, will fix) - st_nlink for merged directories set to 1, this is an "illegal" value that normal filesystems never have but some use it to indicate that the number of subdirectories is unknown. Utilities (find, ...) seem to tolerate this well. - misc fixes I forgot about | http://lkml.org/lkml/2011/6/1/456 | CC-MAIN-2017-22 | en | refinedweb |
What Future Java Might Look LikeBy Nicolai Parlog.
Table of Contents:
public class LinkedList<any T> { private Optional<Node<T>> head; // [constructors] // [list mutation by replacing nodes with new ones] public T reduce(T seed, BinaryOperator<T> operator) { var currentValue = seed; var currentNode = head; while (currentNode.isPresent()) { currentValue = operator.apply(currentValue, currentNode.get().getValue()); currentNode = switch (currentNode.get()) { case InnerNode(_, var nextNode) -> Optional.of(nextNode); case EndNode(_) -> Optional.empty(); default: throw new IllegalArgumentException(); } } return currentValue; } private interface Node<any T> { T getValue(); } private static class InnerNode<any T>(T value, Node<T> next) implements Node<T> { } private static class EndNode<any T>(T value) implements Node<T> { } }and
currentNodein
reduce?
- That
switchis almost unrecognizable.
- The classes
InnerNodeand
EndNodelook, err, empty.
Let’s look at all the ideas that went into this example.
More from this!
Here’s what a user might look like:!:
value class ComplexNumber { double real; double imaginary; // constructors, getters, setters, equals, hashCode, toString }.:
value class ComplexNumber(double real, double imaginary) { }:
//. In general, type inference can reduce boilerplate but also hide essential information. If you consider variable names to be more important than their types, you’ll like this as it aligns the names perfectly while throwing out redundant information..:
// matching types String formatted; switch (constant) { case Integer i: formatted = String.format("int %d", i); break; case Byte b: //... case Long l: // ... // ... default: formatted = "unknown" } // used as an expression String formatted = switch (constant) { case Integer i -> String.format("int %d", i); case Byte b: //... case Long l: // ... // ... default: formatted = "unknown" } // deconstructing objects int eval(ExprNode node) { return switch (node) { case ConstantNode(var i) -> i; case NegNode(var node) -> -eval(node); case PlusNode(var left, var right) -> eval(left) + eval(right); case MulNode(var left, var right) -> eval(left) * eval(right); // ... } }
For the linked list I also used it as an expression and to deconstruct the nodes:
currentNode = switch (currentNode.get()) { case InnerNode(_, var nextNode) -> Optional.of(nextNode); case EndNode(_) -> Optional.empty(); default: throw new IllegalArgumentException(); }
Much nicer than what it would have to look like now:
if (currentNode.get() instanceof InnerNode) { currentNode = Optional.of(((InnerNode) currentNode.get()).getNext()); } else if (currentNode.get() instanceof EndNode) { currentNode = Optional.empty(); } else { throw new IllegalArgumentException(); }
?
Liked this post? Want to read more about Java’s present and future? Subscribe to our feed or newsletter. | https://www.sitepoint.com/what-java-might-one-day-look-like/?utm_source=sitepoint&utm_medium=articletile&utm_campaign=likes&utm_term=java | CC-MAIN-2017-22 | en | refinedweb |
In Python, how would I go about grabbing all the titles, and plane text from a wikipedia article such as:. My current code is this:
from bs4 import BeautifulSoup
# ---- Definitions ----#
#Amount of documents
amount_of_documents = 1
#Directory of raw HTML documents
directory_of_raw_documents = "raw_documents/"
#Directory of parsed documents
directory_of_parsed_documents = "parsed_documents/"
# ---- Code ----#
def open_document():
for i in range (1, 1+1):
with open(directory_of_raw_documents + str(i), "r") as document:
html = document.read()
soup = BeautifulSoup(html, "html.parser")
body = soup.find('div', id='bodyContent')
for elements in body.find_all('p'):
print(elements.text)
open_document()
I am loading a downloaded HTML file, then using BeautifulSoup to grab all the content between the
<p> tags. My goal is to grab all titles and plain text content of this article. How would I go about doing this?
In the example posted above, my desired output would be contains:
<p>tags)
You might be interested in using specialized wikipedia page parsers like
wikipedia package. This way you may get the contents easily:
In [1]: import wikipedia In [2]: page = wikipedia.page("Amadeus (film)") In [3]: page.summary Out[3]: u"Amadeus is a 1984 American period drama film directed by Milo\u0161 Forman, written by Peter Shaffer, and adapted from Shaffer's stage play Amadeus (1979)..\nThe." In [4]: page.content Out[4]: u'Amadeus is a 1984 American period drama film directed by Milo\u0161 Forman, written by Peter Shaffer, and adapted from Shaffer\'s s ... Amadeus Filming locations at Movieloci.com'
As far as getting the titles, here is a sample code to get them via
BeautifulSoup:
In [1]: import requests In [2]: from bs4 import BeautifulSoup In [3]: url = "" In [4]: response = requests.get(url) In [5]: soup = BeautifulSoup(response.content, "html.parser") In [6]: [item.get_text() for item in soup.select("h2 .mw-headline")] Out[6]: [u'Plot', u'Cast', u'Production', u'Reception', u'Alternative versions', u'Music', u'Awards and nominations', u'References', u'External links']
The
h2 .mw-headline is a CSS selector that would match elements with
mw-headline class under the
h2 parent elements. | http://www.dlxedu.com/askdetail/3/4e9b9f46f51052891b40fd87a63e83ed.html | CC-MAIN-2018-47 | en | refinedweb |
This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of Resolved status.
Section: 29.7 [atomics.types.generic] Status: Resolved Submitter: BSI Opened: 2010-08-25 Last modified: 2017-02-03
Priority: Not Prioritized
View all other issues in [atomics.types.generic].
View all issues with Resolved status.
Discussion:
Addresses GB-133
The free functions that operate on atomic_address can be used to store a pointer to an unrelated type in an atomic<T*> without a cast. e.g.
int i; atomic<int*> ai(&i); string s; atomic_store(&ai,&s);
Overload the atomic_store, atomic_exchange and atomic_compare_exchange_[weak/strong] operations for atomic<T*> to allow storing only pointers to T.
[ 2010-10-27 Daniel adds: ]
Resolving this issue will also solve 1467Accepting n3164 would solve this issue by removing atomic_address.
[Resolved in Batavia by accepting n3193. ]
Proposed resolution:
Add the following overloads to 29.7 [atomics.types.generic], the synopsis around the specialization atomic<T*>, as indicated:
namespace std { [..] template <class T> struct atomic<T*> : atomic_address { [..] }; } | https://cplusplus.github.io/LWG/issue1469 | CC-MAIN-2018-47 | en | refinedweb |
Two questions about using libsvm in python:
I use a simple example considering 4 training points (depicted by *) in a 2D space:
*----*
| |
| |
*----*
I train the SVM with the C_SVC formulation and a linear kernel, I classify the 4 points in two labels [-1, +1].
For example, when I set the training points like this, it should find a separating hyperplane.
{-1}----{+1}
| |
| |
{-1}----{+1}
But with this nonlinear problem, it should not been able to find a separating hyperplane (because of the linear kernel).
{+1}----{-1}
| |
| |
{-1}----{+1}
And I would like to be able to detect this case.
Sample code for the 2nd example:
from svmutil import *
import numpy as np
y = [1, -1, 1, -1]
x = [{1:-1, 2 :1}, {1:-1, 2:-1}, {1:1, 2:-1}, {1:1, 2:1}]
prob = svm_problem(y, x)
param = svm_parameter()
param.kernel_type = LINEAR
param.C = 10
m = svm_train(prob, param)
Sample output:
optimization finished, #iter = 21
nu = 1.000000
obj = -40.000000, rho = 0.000000
nSV = 4, nBSV = 4
Total nSV = 4
Run cross validation for a exponential grid of C as explained in the libsvm guide on a linear kernel SVM. If the training set accuracy can never get close to 100% that means that the linear model is too biased for the data which in turn means that the linear assumption is false (the data is not linearly separable).
BTW. the testing set accuracy is the real evaluation of the generalization ability of the model but it measures the sum of the bias and variance hence cannot be used directly to measure the bias only. The difference between the training and testing sets accuracies measures the variance or overfitting of the model. More information on error analysis can be found in this blog post summarizing practical tips and tricks from the ml-class online class. | http://m.dlxedu.com/m/askdetail/3/8c4f335058d4105d39dcd0106eb3d4c2.html | CC-MAIN-2018-47 | en | refinedweb |
Question:
I'm trying to export a control library in a .dll for other developers in the office to consume.
The solution I original created looks like this:
Solution 1:
- Mri.Controls (Class Library)
- Mri.FmTool (Web Application)
Mri.FmTool references Mri.Controls.
Inside Mri.Controls, I have some javascript WebResources. Mri.FmTool seems to read the WebResources just fine, all my javascript web resouces appear as they should when Mri.FmTool web app is running.
So, now I was trying to create a simple solution to consume Mri.FmTool
Solution 2:
- Mri.ConsumerTest (Web Application)
I took the latest Mri.Controls.dll and added it as a reference to Mri.ConsumerTest application. All the controls from Mri.Controls seem to be working inside Mri.ConsumerTest. Intellisense is working, it compiles, no issues.
However, when running it, most of the WebResource.axd files are empty, just blank. One WebResource.axd file isn't blank, it simply says "This resource cannot be found."
Here are the properties of the javascript files inside the Properties window:
Build Action: "Embedded Resource"
Copy to Output Directory: "Copy always"
What step am I missing?
Solution:1
You are probably missing the [assembly:WebResource("YourNameSpace.YourFile.js", "text/javascript")] attribute. WebResource.axd needs that attribute. You can check this KB article for additional info on the matter.
Solution:2
Are the resources set to be part of the DLL?
Open the solution Mri.Controls & view the properties of your javascript resource files.
I think that is where the problem could be.
Solution:3
I noticed that my WebResource CSS files were loading properly, but Javascript was not loading in WebResource in the new solution.
So, instead of using the System.Web.UI.ClientScriptManager used to register the WebResources, I switched over to using System.Web.UI.ScriptManager. Now the files are coming out of ScriptManager.axd (instead of WebResource.axd). This seemed to fix the problem.
Old Code before Fix:
public class ScriptManagerExtension : System.Web.UI.ScriptManager { protected override void OnInit(EventArgs e) { base.OnInit(e); Page.ClientScript.RegisterClientScriptResource(this, typeof(ScriptManagerExtension), "Mri.Controls.Resources.Scripts.Libraries.jQuery.js"); } }
The code snippet above uses System.Web.UI.ClientScriptManager
New Code after Fix:
public class ScriptManagerExtension : System.Web.UI.ScriptManager { protected override void OnInit(EventArgs e) { base.OnInit(e); RegisterClientScriptResource(this, typeof(ScriptManagerExtension), "Mri.Controls.Resources.Scripts.Libraries.jQuery.js"); } }
The code snippet above uses System.Web.UI.ScriptManager
From my understanding, ClientScriptManager was introduced in 2.0. I believe ScriptManager is the new improved 3.5 way of managing scripts that has a lot more functionality.
/shrug
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon | http://www.toontricks.com/2018/05/tutorial-webresourceaxd-blank-or-not.html | CC-MAIN-2018-47 | en | refinedweb |
Suspicious connections of Signal and to ubuntu
Hello,
when I start the software and use the Signal client, there are connections open to amazon servers and the application has a strange name. There is also a permanent connection to ubuntu or ubports open. Can anyone check this please. This seems suspicious to me.
Best regards.
- Flohack Infrastructure last edited by
Probably Signal uses Amazon cloud. Nothing to worry about.
@humungus,
here is an article, why signal uses amazon aws
The connection to ubports or ubuntu could be the push-notifications-server.
What do you mean by "strange name"? The used namespace is
textsecure.nanuc. The textsecure is the historical name of signal and nanuc us the name of the maintainer.
Best
Thank you for your reply. I was just curious, because the initial key exchange with a friend was not flawless, it needed to be restarted a second time, and also some acknowledgements of delivered messages failed. Anyway thanks again. | https://forums.ubports.com/topic/1414/suspicious-connections-of-signal-and-to-ubuntu | CC-MAIN-2018-47 | en | refinedweb |
This blog posts discusses the design and performance implications of using
bitmaps to mark null values instead of sentinel values (or special values like
NaN).
How Apache Arrow's columnar format handles null values
Depending on who you talk to, one controversial aspect of the Apache Arrow columnar format is the fact that it uses a validity bitmap to mark value as null or not null. Here's the basic idea:
- The number of nulls is a property of an array, generally computed once then stored
- If an array has any null values at all, then a bitmap must be allocated
- If the value at bit i is 0, then the value is null, otherwise it is not null
There's some nice benefits of the bitmap approach:
- If an array has no nulls, then the bitmap can be ignored or simply not allocated at all
- Nulls can be propagated in algorithms by using word-wise AND or OR operations, processing 32 or 64 values at a time
Still, for systems like R which use special values to mark nulls, bitmaps can
be controversial. The argument sometimes centers on the performance
implications of having to check bits rather than comparing a value with
INT32_MIN or checking if it is
NaN. It is also noted that
NaN values are
propagated automatically by the CPU in arithmetic operations, so propagating
nulls in the bitmap case will be necessarily slower.
The database perspective
From the perspective of databases and data warehousing, reserving certain
values to mark a null (or NA) is widely considered unacceptable.
NaN is valid
data, as is
INT32_MIN and other common values used as sentinels.
Most SQL systems store the null-ness of value using an extra bit or byte. File formats like Apache Avro and Parquet have a separate null/not-null encoding.
Are sentinel values faster than bitmaps (for analytics)?
To show that the performance argument against bitmaps is not persuasive, I
wrote some in-memory performance benchmarks (I would like to do some
experiments with large memory-mapped datasets). To keep things simple, let's
consider the
sum operation which must aggregate all of the non-null values in
an array. We also will track the non-null count.
We are interested in a few typical cases:
- Data with no nulls
- Data with a small percentage of nulls, say 10%
- Data with a high percentage of nulls, say 50%
To keep track of the results of a sum, I use a simple struct, templated on the type of the values:
template <typename T> struct SumState { SumState() : total(0), valid_count(0) {} T total; int64_t valid_count; };
The naive sum looks like this
template <typename T> struct SumNoNulls { static void Sum(const T* values, int64_t length, SumState<T>* state) { for (int64_t i = 0; i < length; ++i) { state->total += *values++; } state->valid_count += length; } };
Let's consider double precision floating point values, where
NaN is a common
sentinel value. So a sum function for
double is:
template <typename T> struct SumWithNaN { static void Sum(const T* values, int64_t length, SumState<T>* state) { for (int64_t i = 0; i < length; ++i) { if (*values == *values) { // NaN is not equal to itself state->total += *values; ++state->valid_count; } ++values; } } };
If we represent nulls with bits, we could write the sum naively like so:
#include "arrow/util/bit-util.h" template <typename T> struct SumBitmapNaive { static void Sum(const T* values, const uint8_t* valid_bitmap, int64_t length, SumState<T>* state) { for (int64_t i = 0; i < length; ++i) { if (BitUtil::GetBit(valid_bitmap, i)) { state->total += *values; ++state->valid_count; } ++values; } } };
Summing much faster: eliminate branching, unroll loops, pre-compute popcounts
It's possible to go much faster using bitmaps with a few optimization techniques:
- Eliminate the "if" statements by using floating point operations to conditionally add the non-null values
- "Unroll" part of the for loop to sum 8 values at a time
- Skip null checking for groups of 8 values with no nulls. This is made faster still by generating a pre-populated table of bit popcounts for
uint8_tvalues.
Here's the meat of this new vectorized sum algorithm:
const int64_t whole_bytes = length / 8; for (int64_t i = 0; i < whole_bytes; ++i) { const uint8_t valid_byte = valid_bitmap[i]; if (valid_byte < 0xFF) { // Some nulls state->total += (values[0] * (valid_byte & 1)) + (values[1] * ((valid_byte >> 1) & 1)) + (values[2] * ((valid_byte >> 2) & 1)) + (values[3] * ((valid_byte >> 3) & 1)) + (values[4] * ((valid_byte >> 4) & 1)) + (values[5] * ((valid_byte >> 5) & 1)) + (values[6] * ((valid_byte >> 6) & 1)) + (values[7] * ((valid_byte >> 7) & 1)); state->valid_count += kBytePopcount[valid_byte]; } else { // No nulls state->total += values[0] + values[1] + values[2] + values[3] + values[4] + values[5] + values[6] + values[7]; state->valid_count += 8; } values += 8; }
To give a fair comparison with a sum without nulls, I also wrote similar
versions of this that sums 8 values at a time in the non-nullable case and
NaN sentinel value case. I also added the same benchmark with
int64 values
using
INT64_MIN as the sentinel value in case integer operations perform
differently from floating point operations.
Complete benchmarking code is here. Here are the performance results for the 3 cases there there are 0%, 10%, and 50% nulls, respectively. The size of the array being summed is 10 million values. The machine is my Xeon E3-1505M Linux laptop.
It's definitely possible that I'm doing something suboptimal in my implementations. I would love to hear from algorithms experts!
Some observations on these benchmark results:
- The "no nulls" sum functions, both vectorized and not, perform the same for all 3 cases, since it does no null checking at all
- When there are no nulls, there is no performance penality with the optimized bitmap sum
- When there are 10% nulls, the bitmap sum is about 30% faster than the sentinel-based sum. The performance gap widens when the percentage of nulls is higher.
- The vectorized bitmap sum is faster when there are 50% nulls than when there are 10% nulls. I am not sure why this is; I would speculate that because on average many of the terms in the sum are 0 that the processor is able to avoid some floating point operations. It might be possible to further optimize by reducing the number of possible FP operations using a "binary tree" sum.
- Vectorization / batching brings little benefit to the sentinel-based algorithm
Conclusions
Using a bit- or byte-based masked null representation is a requirement for a common memory format to be accepted by database systems as well as data science libraries, so using sentinel values at all is not really an option in a project like Apache Arrow. But, in many cases, using bitmaps allows faster algorithms to be developed that are not possible with the sentinel value-based null representation used in pandas and R.
I'm not a perfect programmer, so I'll be interested to see what other kinds of optimizations others can cook up. Take a look at the benchmark code! | http://wesmckinney.com/blog/bitmaps-vs-sentinel-values/ | CC-MAIN-2018-47 | en | refinedweb |
As previously discussed, the term used for deriving a subclass from a super class is extending because of the Java keyword extends. The formal syntax for the extends keyword is as follows:
[public] [qualifiers] class subclass extends superclass
public this can have the value public or no value, which identifies package access and is discussed later
qualifiers valid qualifiers are final, abstract, static, or nothing at all
Defining a class to be final means that it cannot be subclassed you cannot extend it. Use the keyword final to declare a class to be final, for example:
public final class MyClass { }
Typically, you'll want to define classes to be final when you do not want anyone else extending them. This can be either when they encapsulate all the functionality they will ever need, or if they contain core pieces of functionality that you do not want to expose for use by anyone else in any other capacity than how you intend.
Defining a class to be abstract means that it must be subclassed it cannot be instantiated on its own. An abstract class is defined using the abstract keyword, for example:
public abstract class Car { }
Abstract classes typically contain at least one abstract method. Abstract methods are identified by the abstract keyword in their declaration, and they do not contain a method body. Instead, a semicolon terminates the declaration, for example:
public abstract void accelerate();
The Car class might be declared to be abstract because you cannot create a generic car. You must have a specialization of a car, and some methods do not have any good default implementation. The Car class, for example, should not provide a default implementation for the accelerate() and decelerate() methods because they are too specific to the subclasses that implement them. Listing 7.6 defines a new version of the car class that is abstract: Car2.
public abstract class Car2 { // Car(() { running = true; } public void stop() { running = false; } public boolean isRunning() { return running; } public abstract void accelerate(); public abstract void decelerate(); public int getCurrentSpeed() { return currentSpeed; } public String toString() { return typeOfCar; } }
Car2 cannot be instantiated itself and all classes that subclass it must either provide an implementation of both the accelerate and decelerate methods or be declared to be abstract. If you declare a class that extends the Car2 class and do not implement both accelerate and decelerate, a compilation error will result. Consider Listing 7.7, it defines a new class: BadCar, that extends Car2 and does not implement its abstract methods.
public class BadCar extends Car2 { }
Upon compilation you should receive the following error:
BadCar.java:1: BadCar should be declared abstract; it does not define decelerate () in Car2 public class BadCar extends Car2 ^ 1 error
In previous chapters you have been exposed to two access modifiers: public and private. This chapter has presented a new hybrid access modifier: protected. public methods and variables are available both from within the class and outside the class. private methods and variables are only available from within the class and not from the outside protected methods and variables are available within the class and within any subclass, but not outside the class.
The end result of this is that if you declare your methods and variables to be public, they will be available to anyone who wants to use them, including your subclasses. If you define them to be private, they will not be available to anyone outside your class, including your subclasses. So, Java defined an access modifier specifically to support data that you want available in subclasses, but nowhere else: protected. | https://flylib.com/books/en/1.89.1.74/1/ | CC-MAIN-2021-17 | en | refinedweb |
Extending Our Functional Test Using the unittest Module
Let’s adapt our test, which currently checks for the default Django "it worked" page, and check instead for some of the things we want to see on the real front page of our site.
Time to reveal what kind of web app we’re building: a to-do lists site! In doing so we’re very much following fashion: a few years ago all web tutorials were about building a blog. Then it was forums and polls; nowadays it’s all to-do lists.
The reason is that a to-do list is a really nice example. At its most basic it is very simple indeed—just a list of text strings—so it’s easy to get a "minimum viable" list app up and running. But it can be extended in all sorts of ways—different persistence models, adding deadlines, reminders, sharing with other users, and improving the client-side UI. There’s no reason to be limited to just “to-do” lists either; they could be any kind of lists. But the point is that it should allow me to demonstrate all of the main aspects of web programming, and how you apply TDD to them.
Using a Functional Test to Scope Out a Minimum Viable App
Tests that use Selenium let us drive a real web browser, so they really let us see how the application functions from the user’s point of view. That’s why they’re called functional tests.
This means that an FT can be a sort of specification for your application. It tends to track what you might call a User Story, and follows how the user might work with a particular feature and how the app should respond to them.
FTs should have a human-readable story that we can follow. We make it explicit using comments that accompany the test code. When creating a new FT, we can write the comments first, to capture the key points of the User Story. Being human-readable, you could even share them with nonprogrammers, as a way of discussing the requirements and features of your app.
TDD and agile software development methodologies often go together, and one of the things we often talk about is the minimum viable app; what is the simplest thing we can build that is still useful? Let’s start by building that, so that we can test the water as quickly as possible.
A minimum viable to-do list really only needs to let the user enter some to-do items, and remember them for their next visit.
Open up functional_tests.py and write a story a bit like this one:
from selenium import webdriver browser = webdriver.Firefox() # Edith has heard about a cool new online to-do app. She goes # to check out its homepage browser.get('') # She notices the page title and header mention to-do lists assert 'To-Do' in browser.title # She is invited to enter a to-do item straight away # She types "Buy peacock feathers" into a text box (Edith's hobby # is tying fly-fishing lures) # When she hits enter, the page updates, and now the page lists # "1: Buy peacock feathers" as an item in a to-do list # There is still a text box inviting her to add another item. She # enters "Use peacock feathers to make a fly" (Edith is very methodical) # The page updates again, and now shows both items on her list # Edith wonders whether the site will remember her list. Then she sees # that the site has generated a unique URL for her -- there is some # explanatory text to that effect. # She visits that URL - her to-do list is still there. # Satisfied, she goes back to sleep browser.quit()
You’ll notice that, apart from writing the test out as comments, I’ve
updated the
assert to look for the word “To-Do” instead of “Django”.
That means we expect the test to fail now. Let’s try running it.
First, start up the server:
$ python manage.py runserver
And then, in another shell, run the tests:
$ python functional_tests.py Traceback (most recent call last): File "functional_tests.py", line 10, in <module> assert 'To-Do' in browser.title AssertionError
That’s what we call an expected fail, which is actually good news—not quite as good as a test that passes, but at least it’s failing for the right reason; we can have some confidence we’ve written the test correctly.
The Python Standard Library’s unittest Module
There are a couple of little annoyances we should probably deal with. Firstly, the message "AssertionError" isn’t very helpful—it would be nice if the test told us what it actually found as the browser title. Also, it’s left a Firefox window hanging around the desktop, so it would be nice if that got cleared up for us automatically.
One option would be to use the second parameter to the
assert keyword,
something like:
assert 'To-Do' in browser.title, "Browser title was " + browser.title
And we could also use a
try/finally to clean up the old Firefox window. But
these sorts of problems are quite common in testing, and there are some
ready-made solutions for us in the standard library’s
unittest module. Let’s
use that! In functional_tests.py:
from selenium import webdriver import unittest class NewVisitorTest(unittest.TestCase): (1) def setUp(self): (3) self.browser = webdriver.Firefox() def tearDown(self): (3) self.browser.quit() def test_can_start_a_list_and_retrieve_it_later(self): (2) # Edith has heard about a cool new online to-do app. She goes # to check out its homepage self.browser.get('') # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) (4) self.fail('Finish the test!') (5) # She is invited to enter a to-do item straight away [...rest of comments as before] if __name__ == '__main__': (6) unittest.main()
You’ll probably notice a few things here:
Let’s try it!
$ python functional_tests.py F ====================================================================== FAIL: test_can_start_a_list_and_retrieve_it_later (__main__.NewVisitorTest) --------------------------------------------------------------------- Traceback (most recent call last): File "functional_tests.py", line 18, in test_can_start_a_list_and_retrieve_it_later self.assertIn('To-Do', self.browser.title) AssertionError: 'To-Do' not found in 'Welcome to Django' --------------------------------------------------------------------- Ran 1 test in 1.747s FAILED (failures=1)
That’s a bit nicer, isn’t it? It tidied up our Firefox window, it gives us a
nicely formatted report of how many tests were run and how many failed, and
the
assertIn has given us a helpful error message with useful debugging info.
Bonzer!
Commit
This
is a good point to do a commit; it’s a nicely self-contained change. We’ve
expanded our functional test to include comments that describe the task we’re
setting ourselves, our minimum viable to-do list. We’ve also rewritten it to
use the Python
unittest module and its various testing helper functions.
Do a
git status—that should assure you that the only file that has
changed is functional_tests.py. Then do a
git diff, which shows you the
difference between the last commit and what’s currently on disk. That should
tell you that functional_tests.py has changed quite substantially:
$ git diff diff --git a/functional_tests.py b/functional_tests.py index d333591..b0f22dc 100644 --- a/functional_tests.py +++ b/functional_tests.py @@ -1,6 +1,45 @@ from selenium import webdriver +import unittest -browser = webdriver.Firefox() -browser.get('') +class NewVisitorTest(unittest.TestCase): -assert 'Django' in browser.title + def setUp(self): + self.browser = webdriver.Firefox() + + def tearDown(self): + self.browser.quit() [...]
Now let’s do a:
$ git commit -a
The
-a means “automatically add any changes to tracked files” (i.e., any
files that we’ve committed before). It won’t add any brand new files (you have
to explicitly
git add them yourself), but often, as in this case, there aren’t
any new files, so it’s a useful shortcut.
When the editor pops up, add a descriptive commit message, like “First FT specced out in comments, and now uses unittest.”
Now we’re in an excellent position to start writing some real code for our lists app. Read on! | https://www.obeythetestinggoat.com/book/chapter_02_unittest.html | CC-MAIN-2021-17 | en | refinedweb |
TensorRT is a platform for high-performance deep learning inference that can be used to optimize trained models. This is done by replacing TensorRT-compatible subgraphs with a single TRTEngineOp that is used to build a TensorRT engine. These engines are a network of layers and have well defined input shapes. They run inference using the TensorRT libraries (see Conversion Parameters for more details). After a model is optimized with TensorRT, the traditional Tensorflow workflow is still used for inferencing, including TensorFlow Serving.
TensorRT-compatible subgraphs consist of TensorFlow with TensorRT (TF-TRT) supported ops (see Supported Ops for more details) and are directed acyclic graphs (DAGs). Tensorflow ops that are not compatible with TF-TRT, including custom ops, are run using Tensorflow.
TensorRT can also calibrate for lower precision (FP16 and INT8) with a minimal loss of accuracy. Using a lower precision mode reduces the requirements on bandwidth and allows for faster computation speed. It also allows for the use of Tensor Cores, which perform matrix multiplication on 4×4 FP16 matrices and adds a 4×4 FP16 or FP32 matrix.
This tutorial explains how to convert a model to a TensorRT-optimized model, some of the parameters that can be used for the conversion, how to run an upstream example in the WLM CE environment, and compares statistics between native and TensorRT-optimized runs.
Note: TensorRT engines are optimized for the currently available GPUs. So, conversions should take place on the system that will be running inference.
Optimizing pre-trained models
In this section, we used the ResNet-50 v2 (fp32) model from the official TensorFlow models repository saved into the
/tmp/resnet directory.
# curl -s | tar --strip-components=2 -C /tmp/resnet -xvz
Saved models can be optimized by using the
saved_model_cliscript included with the TensorFlow conda package:
# saved_model_cli convert --dir /tmp/resnet/1538687457/ --output_dir /home/user/example/4/ --tag_set serve tensorrt --is_dynamic=True
Saved models and frozen graphs can also be optimized by using the TensorFlow Python
TrtGraphConverterclass.
For saved models, you need to pass in
input_saved_model_dir=dir, where
dir/saved_model.pbexists.
from tensorflow.python.compiler.tensorrt import trt_convert as trt # Convert a saved model converter = trt.TrtGraphConverter(input_saved_model_dir='/tmp/resnet/1538687457/') graph_def = converter.convert() converter.save('/home/user/example/1/')
For frozen graphs, you need to pass in
input_graph_defand
nodes_blacklistparameters.
nodes_blacklistis a list of output nodes.
Because this example model is in the saved model format, we need to create a frozen graph:
freeze_graph --input_saved_model_dir=/tmp/resnet/1538687457/ --output_graph=/tmp/resnet/frozen_graph.pb --saved_model_tags serve --output_node_names=softmax_tensor
Next, we load the frozen graph into a TensorFlow GraphDef:
import tensorflow as tf # Load and convert a frozen graph graph_def = tf.GraphDef() with tf.gfile.GFile("/tmp/resnet/frozen_graph.pb", 'rb') as f: graph_def.ParseFromString(f.read())
Finally, we optimize the frozen graph using TensorRT:
from tensorflow.python.compiler.tensorrt import trt_convert as trt converter = trt.TrtGraphConverter(input_graph_def=graph_def, nodes_blacklist=['softmax_tensor']) graph_def = converter.convert() converter.save('/home/user/example/2/')
When using INT8 precision mode, an additional calibration step is required to finish the optimization. The calibration data set should be representative of the problem data set. For information about INT8 calibration see NVIDIA’s 8-bit Inference with TensorRT
# Get calibration data import requests IMAGE_URL = '' data = requests.get(IMAGE_URL, stream=True).content # Convert and calibrate model from tensorflow.python.compiler.tensorrt import trt_convert as trt import numpy as np converter = trt.TrtGraphConverter(input_saved_model_dir='/tmp/resnet/1538687457/', precision_mode='INT8') converted_graph_def = converter.convert() calibrated_graph_def = converter.calibrate( fetch_names=['softmax_tensor'], num_runs=1, feed_dict_fn=lambda: {'input_tensor:0': np.array([data])} ) converter.save('/home/user/example/3/')
The calibrate function accepts either
feed_dict_fnor
input_map_fnfor mapping input tensors to data.
Conversion parameters
There are additional parameters that can be passed to
saved_model_cli and
TrtGraphConverter:
precision_mode: The precision mode to use (
FP32,
FP16, or
INT8)
minimum_segment_size: The minimum number of TensorFlow nodes required for a TensorRT subgraph to be valid.
is_dynamic_op: TensorRT engines are converted and built at model run time instead of during the
converter.convert()call. This is required if there are tensors with unknown or dynamic shapes.
use_calibration: Only used if
precision_mode='INT8'. If
True, a calibration graph will be created, and
converter.calibrate()should be called. This is the recommended option. If
False, all tensors that will not be fused must have quantization nodes. See NVIDIA’s INT8 Quantization for details.
max_batch_size:Used when
is_dynamic_op=False. This is the maximum batch size for TensorRT engines. At run time, smaller batch sizes can be used, but a larger batch size will result in an error.
maximum_cached_engines: Used when
is_dynamic_op=True. This limits the number of TensorRT engines that are cached, per TRTEngineOp.
Running the object detection example
Image classification and object detection examples can be found at github.com/tensorflow/tensorrt. The object detection example provides performance output for various models and configurations with and without TensorRT.
Get the example source code (this was verified with commit
3ddfab).
# git clone --recursive
Set up the environment:
# conda create -n tf-trt tensorflow-gpu requests pillow cython -y # conda activate tf-trt # cd tensorrt # pushd tftrt/examples/object_detection # ./install_dependencies.sh # popd
Download the coco validation data set:
# python >>> from tftrt.examples.object_detection import download_dataset >>> download_dataset('val2017', output_dir='coco')
Create a test.json file. See the verified models for additional options.
{ "model_config": { "model_name": "ssd_inception_v2_coco", "output_dir": "models" }, "optimization_config": { "use_trt": true, "precision_mode": "FP16" }, "benchmark_config": { "images_dir": "coco/val2017", "annotation_path": "coco/annotations/instances_val2017.json", "batch_size": 1, "image_shape": [600, 600], "num_images": 2048, "output_path": "stats/ssd_inception_v2_coco_trt_fp16.json" } }
For additional test configuration options, run:
# python >>> import tftrt.examples.object_detection as object_detection >>> help(object_detection.test) >>> help(object_detection.optimize_model) >>> help(object_detection.benchmark_model)
Run the test:
python -m tftrt.examples.object_detection.test test.json
Below are results from three different runs of the object_detection example: native (no TensorRT), FP32 (TensorRT optimized), and FP16 (TensorRT optimized). The TensorRT optimized models show an increase in performance with minimal to no loss of precision. These results were gathered on an IBM Power® System AC922 server with 16 GB NVIDIA Tesla V100 GPUs:
Summary
Converting a model to a TensorRT optimized model is a straightforward process and can enhance performance with little to no loss of accuracy. The image classification and object detection examples can be easily run to compare the performance of different models, with or without TensorRT. | https://developer.ibm.com/tutorials/introducing-tensorflow-with-tensorrt/ | CC-MAIN-2021-17 | en | refinedweb |
The practices outlined in this section focus on client performance. That is, we assume there is a client application, probably being used by an end user , which talks to a server using RMI. The goal of these practices is to improve both the performance and the perceived performance of the client application.
Perceived performance is a strange thing. The goal in improving perceived performance is improving application responsiveness. That is, when the user clicks a button, the application does the right thing, and it does the right thing quickly . Most practices that improve performance also improve perceived performance. But the converse is not true ”improving application responsiveness can actually degrade overall performance, or at least cause the server to work harder. But that's often a price worth paying if it means the end user is happier .
This section isn't as RMI-specific as the previous two sections because, when you get right down to it, all enterprise applications have a fairly similar structure, and a lot of optimization practices are fairly general.
One of the practices in Section 6.2 was entitled "Always Use a Naming Service." This is sound advice ”it does make the application more robust. When followed na vely, it also makes the application much slower. If you simply replace a remote method call (to a server) with two remote method calls (one to the naming service and then one to the server), you deserve whatever criticism comes your way.
A much better solution is to implement a centralized cache for stubs for remote servers. This cache should meet the following requirements:
It takes logical arguments, such as server names , and returns a stub. As much as possible, the rest of the code should not know about the structure of the application or the location of individual servers. Code is much more robust, and much easier to read, when knowledge about the application topology is encapsulated.
If the cache doesn't have a stub already, it fetches the stub (and does so in a way that's transparent to the rest of the application).
The cache expires stubs that haven't been used in a while. Otherwise , the cache will keep remote server stubs until the client application shuts down. Because having a live stub counts as a reference to the distributed garbage collector, holding on to stubs for long periods of time effectively prevents the server JVM from cleaning up unused resources.
It has a way for you to flush bad stubs (e.g., stubs to servers that no longer exist). When you discover that a stub is bad (e.g., attempting to make a remote call on the associated server consistently throws an instance of RemoteException ), you should remove the stub from the cache right away, instead of waiting for it to expire.
If you implement a stub cache that meets these four criteria, remote method call invocations will look like the following code snippet ( assuming that your implementation of a cache has get and remove methods ):
try { MyServer stubToRemoteServer = (MyServer) cache.get(LOGICAL_NAME_FOR_SERVER); stubToRemoteServer.performMethod( . . . ); } catch {RemoteException remoteException) { cache.remove(LOGICAL_NAME_FOR_SERVER); }
This has many benefits. For one, it's clear code. If the cache has the stub (e.g., if any part of the application has already talked to the server in question), the naming service is bypassed. And if the stub points to a server that is no longer running, the stub is immediately removed.
The next step in using a stub cache is to integrate it with the retry loop discussed earlier. Here's a very simple integration to illustrate the idea:
public void wrapRemoteCallInRetryLoop( ) { int numberOfTries = 0; while (numberOfTries < MAXIMUM_NUMBER_OF_TRIES) { numberOfTries++; try { MyServer stubToRemoteServer = (MyServer) cache.get(LOGICAL_NAME_FOR_SERVER); doActualWork(stubToRemoteServer); break; } catch (RemoteException exceptionThrownByRMIInfrastructure) { cache.remove(LOGICAL_NAME_FOR_SERVER); reportRemoteException(exceptionThrownByRMIInfrastructure); try { Thread.sleep(REMOTE_CALL_RETRY_DELAY); } catch (InterruptedException ignored) {} } } }
This attempts to get the stub and then makes the remote call. If the call fails, the stub is flushed and, on the second try, a new stub is fetched from the naming service. This is good. In most cases, the cache has the stub, and the overhead of the cache is strictly local. In return for the overhead of maintaining a local cache, you've eliminated most of the calls to the naming service.
Using a stub cache inside the retry loop also lets you gracefully handle the cases when a server is restarted or migrated . In these cases, the stubs in the cache won't work, and attempting to use them will cause instances of RemoteException to be thrown. Logically, the client performs the following sequence of operations:
The client fetches the stub from the cache and attempts to make a remote method call.
The call fails because the server the stub references is no longer running.
The client removes the stub from the cache.
The retry loop kicks in, and the client tries again.
Because the cache is empty, the cache fetches a new stub from the naming service.
Because the new stub points to the new server, everything succeeds.
Combining a stub cache with a retry loop is both efficient and robust!
At one company for which I worked, my first task was described in the following way: "This call is too slow. See if you can make it faster."
I looked at the call. It was slow. It involved 18 separate modules on the server and implicitly depended on about 40,000 lines of code, and all I could think was, "Oh yeah. I'll optimize this in my first week on the job."
Because the task was impossible , I decided to cheat. I thought, "Hmmm. If I can't make the call faster, I can at least use a cache to try and make the call less often." This turned out to be good enough for the application in question, and is often good enough in distributed applications.
The benefits of caching return values on the client side are:
Instead of making a call to the server, which involves network and marshalling overhead, you retrieve the value from an in-process cache. Unless you're doing something truly stupid, this should be faster.
In addition to the performance benefit, looking in a local data structure is more reliable than calling a remote server, and it has a predictable level of overhead (unlike a remote method call, which can take more time if the network is busy).
Bandwidth is the scarcest resource for distributed applications because it is shared by all distributed applications, and because upgrading a network is a lot harder than upgrading a single server. If you don't make a remote call, you aren't using the bandwidth necessary to make the remote call.
If you don't call the server, the server doesn't have to handle the call, which means you've lowered the effective load on the server.
On the other hand, caching does have some major drawbacks. The two most significant are:
Whenever you cache data, you run the risk of the cached values being incorrect. Sometimes this isn't very important. Sometimes it is. Generally speaking, the more important a piece of information is, or the more time-sensitive it is, the less likely you are to cache it.
Within a given sequence of operations (for example, responding when a user clicks a button), a cache improves performance. But caches have to be maintained : data has to be checked for consistency and occasionally thrown out.
Cache maintenance is usually done in a background thread so that a main thread doesn't take the hit of maintaining the cache (otherwise, perceived performance would suffer, and the "more predictable" item listed as an advantage would be false ). But nonetheless, if you're not accessing data that's been cached very often, the client-side cache might very well be a net loss in performance.
This last item is somewhat paradoxical in that, even if the cache winds up costing you more processing time than it saves, it still might be viewed as a performance improvement. This is because the cost occurs in a background thread, but the performance improvements occur in a main thread (where performance improvements are likely to be noticed).
Caching is a subtle and tricky subject. One reference worth looking at is the series of data expiration articles I wrote for onjava.com. In addition, if you're interested in the subject, you might want to keep an eye on JSR-107, the "Java Temporary Caching API," at.
I once had lunch with a group of programmers who were visiting my company from Germany. They were from a company that was partnering with the company I was working for. We were supposed to use CORBA to handle the method calls from their system to ours. But there was a problem.
"CORBA," they confided to me, "doesn't work. It's much too expensive. It doesn't scale very well at all." I was a little surprised by this. I'd been using CORBA for a couple of years at that point, and I'd never run into scalability problems (at least, not at the scale we were talking about).
It turned out that their idea of "building a distributed application" was to "build a single-process application using standard object-oriented techniques and then stick the network in." Their testing had revealed that if an instance of Person is on one machine, and the user interface displaying information about the person is on another machine, a sequence of fine-grained calls such as getFirstName( ) , getLastName( ) , and getSSN ( ) to get the values to display on the screen has performance problems.
Once I figured out what they were complaining about, I had a solution: "Don't do that." The object decompositions that make sense in a single-process application often don't make as much sense in a distributed application. Instead, you need to carefully look at the intent behind sequences of calls and see if you can encapsulate a sequence of calls in one bigger method call (which I refer to as a batch method).
In the previous example, the sequence getFirstName( ) , getLastName ( ), getSSN ( ), . . . should really have been a call to a new method called getDisplayData( ) . Of course, getDisplayData( ) shouldn't exist for a single-process implementation of the Person class (it completely breaks encapsulation). But it has to be there for the distributed application to perform well, and that's the point of this practice.
How do you spot a potential batch method? There's no cut-and- dried way to do so (that I know of). But here are four rules of thumb for when batch methods are appropriate:
The methods you want to include in a batch method must be called in a sequence fairly often. Batch methods are an optimization and they shouldn't be created for uncommon cases.
If the methods are all for data access (with no side effects), a batch method is more likely to be appropriate.
The methods should all block the same task (and not distinct tasks). If all the method calls are associated with the same set of client-side conceptual tasks, and none of the tasks can continue until the client gets all the return values, a batch method is almost certainly appropriate.
The methods have a predetermined outcome. That is, the client will make a sequence of calls. If the client doesn't know all the arguments (for all the calls) at the time the first call is made, or if the return values for all the calls can't be computed at the time when the first call is made, the methods can't be grouped into a batch method.
Sometimes a client will make a series of calls to a server, and these calls, while conceptually a transaction, aren't easily batched, or don't feel like a batch method. A classic example of this is transferring money between two bank accounts.
If you have two distinct servers (one for each account), this involves the following four steps:
Opening a transaction (presumably using a transaction management server)
Withdrawing money from one server
Depositing the money in another server
Committing the transaction
This sequence of calls should not be executed from a client application for two reasons. The first is that client applications are often deployed across a WAN, which is slow ( especially compared to a datacenter managed by IT personnel). Making four concurrent remote method calls under those conditions could lead to significant performance problems.
The second reason is that logic about transactions will most likely change. Even something as simple as "We've decided to log all money transfers from now on" would force you to redeploy a new version of the client that would call a logging method on a server somewhere, which is very bizarre in and of itself.
The solution is to use a server-side proxy for the client. A server-side proxy is a server, running "near" the other servers, which is client-specific and whose sole role is to manage complex transactions for the client. If you're using a server-side proxy, the previous calling sequence turns into a single call to the proxy's transferMoney method. The proxy still has to perform the four remote method calls, but it does so on a LAN inside a well-managed environment. Figure 6-1 illustrates the trade-off.
Most remote method calls are synchronous: the calling thread stops and waits for a response from the server. An asynchronous method call is one in which the caller doesn't wait for a response, or even wait to know if the call succeeded. Instead, the calling thread continues processing.
RMI doesn't directly support asynchronous calls. Instead, you have to use a background thread to make the call. In Example 6-2, the calling thread creates a command object and drops it off in a background queue for execution. This leaves the calling thread free to immediately resume processing, instead of waiting for a response, as in the following code snippet:
BackgroundCallQueue_backgroundQueue = new BackgroundCallQueueImpl( ); // . . . _backgroundQueue.addCall(new SpecificCallToServer( . . . ));
Example 6-2 is a sample implementation of BackgroundCallQueue and BackgroundCallQueueImpl .
public interface BackgroundCallQueue { public void addCall(RemoteMethodCall callToAdd); } public class BackgroundCallQueueImpl implements BackgroundCallQueue { private LinkedList _pendingCalls; private thread _dispatchThread; public BackgroundCallQueueImpl ( ) { _stopAcceptingRequests = false; _pendingCalls = new LinkedList( ); _dispatchThread = new Thread(this, "Background Call Queue Dispatch Thread"); _dispatchThread;.start( ); } public synchronized void addCall(RemoteMethodCall callToAdd) { _pendingCalls.addCall( ); notify( ); } public void run( ) { while (true) { RemoteMethodCall call = waitForCall( ); if (null!=call ) { executeCall(call); } } } private synchronized RemoteMethodCall waitForCall( ) { while (0== _pendingCalls.size( )) { wait( ); } return (RemoteMethodCall) _pendingCalls.removeFirst( ); } private void executeCall(RemoteMethodCall call) { // . . . } }
This isn't very complicated code, but it does offer two very significant advantages over synchronous method calls. The first is that it decreases the time a main thread spends sending remote messages. Imagine, for example, that a user clicks on a button, and, as a result of that click, the server needs to be told something. If you use a synchronous method call, the button processing time (and, hence, the perceived performance of the application) will include the time spent sending the remote method call (and the time the server spends processing the call). If you can make the call asynchronously, in a background thread, the application isn't any faster or more efficient, but the user thinks it is.
The second reason is that, once you've moved to a model where requests are dropped off into a queue, you can tweak the queue and make performance improvements without altering most of the client code. For example, if you are making a lot of calls to a single method on a server, you can group these calls and make them in a single call. For example, instead of 100 calls to:
server.patientGivenMedication(Patient patient, Medication medication, long time, HealthCareProvider medicationSource);
you might have 1 call to:
server.patientsGivenMedication(ArrayList medicationEvents);
Because each remote method call contains information about all the relevant classes involved, this will dramatically reduce both marshalling time and bandwidth. Instead of marshalling and sending information about the Patient class 100 times, you will send it only once.
There are two major downsides to putting messages in a background queue. The first is that your code will be harder to debug. Decoupling the source of the remote method call from the time the remote call is made makes it harder to trace the source of logical errors. For example, if a command object has the wrong value for an argument, it's harder to track down the source of the error.
The second problem with putting messages in a background queue is that it's harder to report failures (and harder to respond to them). If a user clicks a button and therefore thinks of an operation as "done," it can be disconcerting for him to find out later on that the operation failed.
Given all this, the question is: when should you use asynchronous messaging? Here are three indicators that a method can be put safely into a background queue:
If the method returns void and throws no exceptions (other than RemoteException ). Methods with this sort of signature tend to be information-sending methods rather than information-retrieval methods or methods that are requesting an action. And, hence, they can be safely postponed and performed in the background.
If there is an associated method to find out the status of an operation at a later time. For example, consider a method to submit a print request to a print server. It might have a boolean return value, and it might throw all sorts of interesting exceptions. But having clicked on the Print button, the user really wants to be able to continue with his work, not wait until the method call transfers the entire file to the print server, and he wants a status view so that he can see where his document is in the print queue.
If the server can call the client back with a return value (or an exceptional condition). Certain requests aren't particularly urgent and can be performed in the background. But the user would like to know if he succeeded. Consider email, for example. When he clicks on the Send button, the user is really saying, "This can go off into the email cloud now." Whether it is sent now or three minutes from now is not really an issue. But he is assuming that if it can't be sent, he will be told.
Printing documents is also a case when callbacks can improve the user interface. A callback to let a user know that his document has been printed is a nice feature.
Using callbacks to let the user know the outcome of an event could incur some additional overhead. It replaces one bidirectional socket connection (the method call and then the return value) with two unidirectional connections (the method call is sent and then, in a later connection, the response is sent). Breaking apart messages like this is a useful technique for optimizing perceived performance, but it almost always incurs some extra overhead. | https://flylib.com/books/en/3.299.1.38/1/ | CC-MAIN-2021-17 | en | refinedweb |
Python Altair is a unique data visualization library that allows you to create interactive models for visualizing data.
To become a good data scientist, being able to build easily understandable but complex plots is important.
A perfect way to tell the underlying story of your data is to make visualisations.
It illustrates the relationships within the data and exposes information that can not be communicated with only numbers and digits apparent to the human eye.
But you know what’s even better for data processing than visualizations? Visualizations that are interactive!
As a beginner, sadly, it can seem like a daunting mission.
To support you with the mission, Python and R both have a wide range of tools and tricks.
We will introduce you to Altair in this tutorial.
With Altair, with only a few lines of code and in a very short time, you’ll be able to construct meaningful, beautiful, and efficient visualizations. So let’s start now!
Table of Contents
- 1 What is Python Altair?
- 2 Working with the Python Altair Library
- 3 Ending Note
What is Python Altair?
Altair is a library of Python intended for statistical visualization. In nature, it is declarative (we shall come to this definition later on).
It is based on Vega and Vega-Lite, both of which are visualization grammar that enables you to explain a visualization’s visual appearance and interactive actions in a JSON format.
As a data scientist, Altair will allow you to concentrate your time on your data and make more effort to understand, analyze, and visualize it rather than on the required code.
Working with the Python Altair Library
Let’s move to work with the Altair library now. We’ll work on the vega dataset here. I’ve shared the link in the datasets section.
1. Installing the Altair module
To install the Python Altair library, we can use pip package manager:
pip install altair pip install vega_datasets
I’m using Google Colab, where it’s already present, so we can directly import:
import pandas as pd import altair as alt from vega_datasets import data as vega_data
2. Preparing the dataset
Today we’ll be using the flights_2k dataset from the vega-datasets library. I chose this because it is small, and doesn’t take much time to load, unlike the flights_3m library.
3. Fetching data with Pandas
We can fetch data from the library using the Python Pandas library and add the “url” tag as mentioned on the first line below:
flights_data = pd.read_json(vega_data.flights_2k.url) flights_data.head(10)
This gives us our data:
4. Plotting a dataset using Python Altair
Data is designed around the Pandas Dataframe in Altair, which means you can manipulate information in Altair the same way you can interact with Pandas DataFrame.
And while Altair internally stores data in a Pandas DataFrame format, there are several ways to enter information.
We use the alt.Chart function to plot :
alt.Chart(flights_data).mark_point().encode( alt.X('delay'), alt.Y('distance') )
5. Making plots interactive with Altair
Now we’ll take it to the next level. Let’s add the ability to interact with the plot, including:
- zooming into the plot
- clicking on data points
- viewing information while hovering
Add the tooltip option and then call the interactive function:
alt.Chart(flights_data).mark_point().encode( alt.X('delay'), alt.Y('distance'), tooltip = [ alt.Tooltip('delay'), alt.Tooltip('distance'), ] ).interactive()
This will give us:
As you can see, we can zoom in as we want into the dataset to get inferences.
Complete implementation of an interactive plot in Python
And that’s all. I’ve made a bunch of more interactive plots on my colab notebook using these codes, so try them out:
import pandas as pd import altair as alt from vega_datasets import data as vega_data flights_data = pd.read_json(vega_data.flights_2k.url) flights_data.head(10) alt.Chart(flights_data).mark_point().encode( alt.X('delay'), alt.Y('distance'), tooltip = [ alt.Tooltip('delay'), alt.Tooltip('distance'), ] ).interactive() alt.Chart(flights_data).mark_point(filled=True).encode( alt.X('origin'), alt.Y('delay'), alt.Size('distance') ) median_delay = flights_data.groupby('origin').median() alt.Chart(flights_data).mark_point(filled=True).encode( alt.X('origin'), alt.Y('destination'), alt.Size('distance') ).configure_mark( opacity=0.2, color='red' )! | https://www.journaldev.com/47555/python-altair-tutorial | CC-MAIN-2021-17 | en | refinedweb |
Introduction Scenario
To demonstrate this approach, we are going to use the Customer -> Preference -> Recommendation microservices application that is being used in the Red Hat Istio tutorial. Within the tutorial, encryption is handled by Istio. In our case, encryption will be configured and handled by the application pods.
We assume that in our environment implements two pieces of Public Key Infrastructure (PKI):
- External PKI
- Internal PKI
For external PKI, certificates must be created to facilitate trust from all browsers and operating system to the external facing services. Companies usually use Certificate Authorities (CA’s) such as Digicert, Verisign etc. for this type of certificates. These companies bill by the number of certificates requested, so we need to keep the external certificate number limited. In our example we are going to use Let’s Encrypt as the external PKI. Let’s Encrypt is a trusted CA maintained by a consortium of companies that provides certificates free of charge with the goal of creating a secure Internet; the catch is that the certificates provisioned via Let’s Encrypt are very short lived, so the only way to use this service effectively is if you automate your certificate provisioning process (this is not an issue as it is the primary goal of this scenario).
The internal PKI is used to establish a trust between internal services (services that do not need to be visible for external consumers and or systems). There are many products that can be installed on premise to act as CAs. One solution that we encounter frequently is Venafi. Red Hat also offers its own CAs product called FreeIPA. Unlike Let’s Encrypt, we can request as many certificates as we want to with this CA because the cost here is not tied to the number of certificate requests, so it is ideal for development and other fast-changing environments. In our solution, we are going to use a RootCA owned by our certificate operator for the internal PKI.
The target architecture is as follows:
The Customer service is exposed to the external clients and it calls the Preference service. The Preference service is also exposed outside of the cluster, but only to internal systems. It calls the Recommendation service. The recommendation service is an internal to the cluster service and not exposed externally.
For automating the certificate provisioning process, we are going to use three operators:
- Cert-manager: this operator is responsible for provisioning certificates. It interfaces with the various CAs and brokers certificate provisioning or renewal requests. Provisioned certificates are placed into Kubernetes secrets.
- Cert-util-operator: this operator provides utility functions around certificates. In particular, it will be used to inject certificates into OpenShift routes and turn PEM-formatted certificates into java-readable keystores.
- Reloader: this operator is used to trigger a deployment when a configmap or secret changes. We are going to use it to restart our applications when certificates get renewed.
Step by Step Instructions
The following describe the steps necessary for deploying the solution.. These steps align to the assets found within this repository.
These steps are presented in a sequential way to allow for better understanding of all the components needed for a successful implementation. In a real world scenario, a developer would configure their CI/CD pipeline to deploy the resources that have been properly set up with the correct annotations/configurations.
This example has been tested on OpenShift Container Platform (OCP) 4.1.x running on Amazon Web Services (AWS). You will need to make some adjustments to the Let’s Encrypt certificate issuer if you change environment (more specifically, if you change the target DNS provider).
To begin, clone the project repository from a directory of your choosing and then enter the project directory:
git clone
cd end-to-end encryption demo
Installing the operators
These steps may vary as more and more operators are added to the OperatorHub. To support OCP 3.x in which OperatorHub is not available, Helm-based steps are being used.
Helm is being used in a tiller-less fashion, so you will need only the helm CLI.
Cert-manager
oc new-project cert-manager
oc label namespace cert-manager certmanager.k8s.io/disable-validation=true
oc apply --validate=false -f
oc patch deployment cert-manager -n cert-manager -p '{"spec":{"template":{"spec":{"containers":[{"name":"cert-manager","args":["--v=2","--cluster-resource-namespace=$(POD_NAMESPACE)","--leader-election-namespace=$(POD_NAMESPACE)","--dns01-recursive-nameservers=8.8.8.8:53"]}]}}}}'
Cert-utils operator
oc new-project cert-utils-operator
helm repo add cert-utils-operator
helm repo update
export cert_utils_chart_version=$(helm search cert-utils-operator/cert-utils-operator | grep cert-utils-operator/cert-utils-operator | awk '{print $2}')
helm fetch cert-utils-operator/cert-utils-operator --version ${cert_utils_chart_version}
helm template cert-utils-operator-${cert_utils_chart_version}.tgz --namespace cert-utils-operator | oc apply -f - -n cert-utils-operator
rm cert-utils-operator-${cert_utils_chart_version}.tgz
Reloader
oc new-project reloader
helm repo add stakater
helm repo update
export reloader_chart_version=$(helm search stakater/reloader | grep stakater/reloader | awk '{print $2}')
helm fetch stakater/reloader --version ${reloader_chart_version}
helm template reloader-${reloader_chart_version}.tgz --namespace reloader --set isOpenshift=true | oc apply -f - -n reloader
rm reloader-${reloader_chart_version}.tgz
Configuring the certificate issuers
Next, configure the two issuers for cert-manager; one for Let’s Encrypt and the other for the internal PKI:
Let’s Encrypt issuer
export EMAIL=
oc apply -f issuers/aws-credentials.yaml
sleep 5
export AWS_ACCESS_KEY_ID=$(oc get secret cert-manager-dns-credentials -n cert-manager -o jsonpath='{.data.aws_access_key_id}' | base64 -d)
export REGION=$(oc get nodes --template='')
export zoneid=$(oc get dns cluster -o jsonpath='{.spec.publicZone.id}')
envsubst < issuers/lets-encrypt-issuer.yaml | oc apply -f - -n cert-manager
Internal PKI issuer
oc apply -f issuers/internal-issuer.yaml -n cert-manager
Deploying the application
oc new-project demo
oc apply -f customer/kubernetes/Deployment.yml -n demo
oc apply -f customer/kubernetes/Service.yml -n demo
oc apply -f preference/kubernetes/Deployment.yml -n demo
oc apply -f preference/kubernetes/Service.yml -n demo
oc apply -f recommendation/kubernetes/Deployment.yml -n demo
oc apply -f recommendation/kubernetes/Service.yml -n demo
If you check the status of the application at this point (for example with oc get pods), you will notice that all the pods are failing. This is due to the fact that these java microservices expect to be able to open a keystore configured in the application properties, but this keystore is not available yet. It will be injected as a secret in the following steps.
Securing the Customer Service
We are going to secure the customer service with a re-encrypt route. The certificate exposed by the route is going to be signed by the Let’s Encrypt CA, the certificate used by the pod is going to be signed by the internal CA.
## create the route
oc create route reencrypt customer --service=customer --port=https -n demo
## create the external certificate
namespace=demo route=customer host=$(oc get route $route -n $namespace -o jsonpath='{.spec.host}') envsubst < certificates/ACME-certificate.yaml | oc apply -f - -n demo
## create internal certificate
service=customer namespace=demo envsubst < certificates/internal-certificate.yaml | oc apply -f - -n demo;
## annotate the secret to create keystores
oc annotate secret service-customer -n demo cert-utils-operator.redhat-cop.io/generate-java-keystores=true;
## mount the secret to the pod
oc set volume deployment customer -n demo --add=true --type=secret --secret-name=service-customer --name=keystores --mount-path=/keystores --read-only=true
## annotate the route to use the certificate
oc annotate route customer -n demo cert-utils-operator.redhat-cop.io/certs-from-secret=route-customer
## make the route trust the internal certificate
oc annotate route customer -n demo cert-utils-operator.redhat-cop.io/destinationCA-from-secret=service-customer
At this point, if you open a browser and navigate to the route, you should see an error (because the preference service is still not working). However, you should observe that the certificate is trusted by the browser.
To find the customer route hostname type the following:
oc get route customer -n demo -o jsonpath='{.spec.host}'
Securing the Preference Service
The preference service needs to be accessible from outside of the cluster by internal systems and not by external consumers. Due to this, we can use a certificate signed by the internal PKI. This certificate will need to have two Subject Alternate Names (SAN’s): one for the route and one for the internal service name (the latter is used by the customer service). We can mount this certificate on the pod and create a passthrough route to access the pod.
## create the passthrough route
oc create route passthrough preference --service=preference --port=https -n demo
## create the two-SANs certificate
namespace=demo route=preference host=$(oc get route $route -n $namespace -o jsonpath='{.spec.host}') service=preference envsubst < certificates/multiSAN-internal-certificate.yaml | oc apply -f - -n demo
## annotate the secret to create keystores
oc annotate secret route-service-preference -n demo cert-utils-operator.redhat-cop.io/generate-java-keystores=true;
## mount the secret to the pod
oc set volume deployment preference-v1 -n demo --add=true --type=secret --secret-name=route-service-preference --name=keystores --mount-path=/keystores --read-only=true
If you navigate using your browser to the preference route, you should see an untrusted certificate.
To find the preference route hostname type the following:
oc get route preference -n demo -o jsonpath='{.spec.host}'
Notice that the customer service trusts calling the preference service because we have configured it’s truststore based on a certificate created with the internal PKI. Since the preference service certificate has also been created with the internal PKI, then trust can be established. The same is true with the Preference to Recommendation connection.
Securing the Recommendation service
In our example, the Recommendation service is an internal service and not exposed outside of the cluster. Given that fact, we can secure it with a certificate signed by the internal PKI.
service=recommendation namespace=demo envsubst < certificates/internal-certificate.yaml | oc apply -f - -n demo;
## annotate the secret to create keystores
oc annotate secret service-recommendation -n demo cert-utils-operator.redhat-cop.io/generate-java-keystores=true;
## mount the secret to the pod
oc set volume deployment recommendation-v1 -n demo --add=true --type=secret --secret-name=service-recommendation --name=keystores --mount-path=/keystores --read-only=true
Now, if we navigate our browser to the customer service, everything should be working correctly.
To find the customer route hostname type the following:
oc get route customer -n demo -o jsonpath='{.spec.host}'
Certificate Renewal
So far so good. Consider what happens when a certificate needs to be renewed. Cert-manager monitors the certificates it has issued and will renew them when it’s they are about to expire (this functionality can be customized to trigger the certificate renewal by changing the renewBefore field). At renewal time, the following occurs:
- Cert-manager contacts the configured CA to get a new certificate.
- Cert-manager replaces the secret content with the new certificate files.
- If a route is configured to use the specified certificate, the cert-utils operator updates the route TLS configuration.
- If a certificate secret is annotated to expose the certificate in keystore format, the cert-utils operator refreshes the keystore and truststore fields.
- If a certificate secret is mounted by a pod, then Kubernetes updates the content of the secret in the pod’s file system.
At this point, if an application is able to reconfigure itself based on the secret content being refreshed, then the certificate is successfully renewed. However, many applications still read their configuration at start-up and don’t monitor for subsequent changes. For those situations we can use the Reloader operator to have an application redeployed when the certificate secret is changed.
Let’s apply this configuration to enable this functionality to all of our deployments:
oc annotate deployment customer -n demo secret.reloader.stakater.com/reload=service-customer;
oc annotate deployment preference-v1 -n demo secret.reloader.stakater.com/reload=route-service-preference;
oc annotate deployment recommendation-v1 -n demo secret.reloader.stakater.com/reload=service-recommendation;
To demonstrate that this is working as anticipated, we can configure cert-manager to renew the preference certificate every minute:
oc patch certificate preference -n demo -p '{"spec":{"duration":"1h1m","renewBefore":"1h"}}' --type=merge
oc delete secret route-service-preference -n demo
sleep 5
oc annotate secret route-service-preference -n demo cert-utils-operator.redhat-cop.io/generate-java-keystores=true;
At this point, one should be able to observe that the preference pods are redeployed every minute or so.
Conclusions
In this article, we explored an example of how one can automate the entire certificate lifecycle (provisioning, renewal, retirement) for applications while at the same time integrating with existing CAs (external and or on premise). By being able to combine features from several operators, we were able to complete this task in a reliable and repeatable fashion.
Categories
Security, OpenStack Platform | https://www.openshift.com/blog/self-serviced-end-to-end-encryption-for-kubernetes-applications-part-2-a-practical-example | CC-MAIN-2021-17 | en | refinedweb |
__tfork_thread,
__tfork—
#include <unistd.h>
struct __tfork { void *tf_tcb; /* TCB address for new thread */ pid_t *tf_tid; /* where to write child's thread ID */ void *tf_stack; /* stack address for new thread */ };
__tfork_thread(const struct __tfork *params, size_t psize, void (*startfunc)(void *), void *startarg); pid_t
__tfork(const struct __tfork *params, size_t psize);
__tfork_thread() function creates a new kernel thread in the current process. The new thread starts by calling startfunc, passing startarg as the only argument. If startfunc returns, the thread will exit. The params argument provides parameters used by the kernel during thread creation. The new thread's thread control block (TCB) address is set to tf_tcb. If tf_tid is not NULL, the new thread's thread ID is returned to the user at that address, with the guarantee that this is done before returning to userspace in either the calling thread or the new thread. If tf_stack is not NULL, the new thread's stack is initialized to start at that address. On hppa that is the lowest address used; on other architectures that is the address after the highest address used. The psize argument provides the size of the struct __tfork passed via the params argument. The underlying system call used to create the thread is
__tfork(). Because the new thread returns without a stack frame, the syscall cannot be directly used from C and is therefore not provided as a function. However, the syscall may show up in the output of kdump(1).
__tfork_thread() returns in the calling thread the thread ID of new thread. The
__tfork() syscall itself, on success, returns a value of 0 in the new thread and returns the thread ID of the new thread to the calling thread. Otherwise, a value of -1 is returned, no thread is created, and the global variable errno is set to indicate an error.
__tfork_thread() and
__tfork() will fail and no thread will be created if:
ENOMEM]
EINVAL]
EAGAIN]
EAGAIN]
MAXUPRCon the total number of threads under execution by a single user would be exceeded.
MAXUPRCis currently defined in
<sys/param.h>as
CHILD_MAX, which is currently defined as 80 in
<sys/syslimits.h>.
__tfork_thread() function and
__tfork() syscall are specific to OpenBSD and should not be used in portable applications.
__tfork_thread() function and
__tfork() syscall appeared in OpenBSD 5.1. | https://man.openbsd.org/__tfork.3 | CC-MAIN-2018-34 | en | refinedweb |
I just announced the newSpring Security 5 modules (primarily focused on OAuth2) in the course:
1. Overview
Activiti is an open-source BPM (Business Process Management) system. For an introduction, check our Guide to Activiti with Java.
Both Activiti and the Spring framework provide their own identity management. However, in an application that integrates both projects, we may want to combine the two into a single user management process.
In the following, we’ll explore two possibilities to achieve this: one is by providing an Activiti-backed user service for Spring Security and the other by plugging a Spring Security user source into the Activiti identity management.
2. Maven Dependencies
To set up Activiti in a Spring Boot project, check out our previous article. In addition to activiti-spring-boot-starter-basic, we’ll also need the activiti-spring-boot-starter-security dependency:
<dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring-boot-starter-security</artifactId> <version>6.0.0</version> </dependency>
3. Identity Management Using Activiti
For this scenario, the Activiti starters provide a Spring Boot auto-configuration class which secures all REST endpoints with HTTP Basic authentication.
The auto-configuration also creates a UserDetailsService bean of class IdentityServiceUserDetailsService.
The class implements the Spring interface UserDetailsService and overrides the loadUserByUsername() method. This method retrieves an Activiti User object with the given id and uses it to create a Spring UserDetails object.
Also, the Activiti Group object corresponds to a Spring user role.
What this means is that when we login to the Spring Security application, we’ll use Activiti credentials.
3.1. Setting Up Activiti Users
First, let’s create a user in an InitializingBean defined in the main @SpringBootApplication class, using the IdentityService:
@Bean InitializingBean usersAndGroupsInitializer(IdentityService identityService) { return new InitializingBean() { public void afterPropertiesSet() throws Exception { User user = identityService.newUser("activiti_user"); user.setPassword("pass"); identityService.saveUser(user); Group group = identityService.newGroup("user"); group.setName("ROLE_USER"); group.setType("USER"); identityService.saveGroup(group); identityService.createMembership(user.getId(), group.getId()); } }; }
You’ll notice that since this will be used by Spring Security, the Group object name has to be of the form “ROLE_X”.
3.2. Spring Security Configuration
If we want to use a different security configuration instead of the HTTP Basic authentication, first we have to exclude the auto-configuration:
@SpringBootApplication( exclude = org.activiti.spring.boot.SecurityAutoConfiguration.class) public class ActivitiSpringSecurityApplication { // ... }
Then, we can provide our own Spring Security configuration class that uses the IdentityServiceUserDetailsService to retrieve users from the Activiti data source:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private IdentityService identityService; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()); } @Bean public UserDetailsService userDetailsService() { return new IdentityServiceUserDetailsService( this.identityService); } // spring security configuration }
4. Identity Management Using Spring Security
If we already have user management set up with Spring Security and we want to add Activiti to our application, then we need to customize Activiti’s identity management.
For this purpose, there’re two main classes we have to extend: UserEntityManagerImpl and GroupEntityManagerImpl which handle users and groups.
Let’s take a look at each of these in more detail.
4.1. Extending UserEntityManagerImpl
Let’s create our own class which extends the UserEntityManagerImpl class:
public class SpringSecurityUserManager extends UserEntityManagerImpl { private JdbcUserDetailsManager userManager; public SpringSecurityUserManager( ProcessEngineConfigurationImpl processEngineConfiguration, UserDataManager userDataManager, JdbcUserDetailsManager userManager) { super(processEngineConfiguration, userDataManager); this.userManager = userManager; } // ... }
This class needs a constructor of the form above, as well as the Spring Security user manager. In our case, we’ve used a database-backed UserDetailsManager.
The main methods we want to override are those that handle user retrieval: findById(), findUserByQueryCriteria() and findGroupsByUser().
The findById() method uses the JdbcUserDetailsManager to find a UserDetails object and transform it into a User object:
@Override public UserEntity findById(String userId) { UserDetails userDetails = userManager.loadUserByUsername(userId); if (userDetails != null) { UserEntityImpl user = new UserEntityImpl(); user.setId(userId); return user; } return null; }
Next, the findGroupsByUser() method finds all the Spring Security authorities of a user and returns a List of Group objects: findUserByQueryCriteria() method is based on a UserQueryImpl object with multiple properties, from which we’ll extract the group id and user id, as they have correspondents in Spring Security:
@Override public List<User> findUserByQueryCriteria( UserQueryImpl query, Page page) { // ... }
This method follows a similar principle to the ones above, by creating User objects from UserDetails objects. See the GitHub link at the end for the full implementation.
Similarly, we’ve got the findUserCountByQueryCriteria() method:
public long findUserCountByQueryCriteria( UserQueryImpl query) { return findUserByQueryCriteria(query, null).size(); }
The checkPassword() method should always return true as the password verification is not done by Activiti:
@Override public Boolean checkPassword(String userId, String password) { return true; }
For other methods, such as those dealing with updating users, we’ll just throw an exception since this is handled by Spring Security:
public User createNewUser(String userId) { throw new UnsupportedOperationException("This operation is not supported!"); }
4.2. Extend the GroupEntityManagerImpl
The SpringSecurityGroupManager is similar to the user manager class, except the fact it deals with user groups:
public class SpringSecurityGroupManager extends GroupEntityManagerImpl { private JdbcUserDetailsManager userManager; public SpringSecurityGroupManager(ProcessEngineConfigurationImpl processEngineConfiguration, GroupDataManager groupDataManager) { super(processEngineConfiguration, groupDataManager); } // ... }
Here the main method to override is the findGroupsByUser() method:
@Override method retrieves a Spring Security user’s authorities and transforms them to a list of Group objects.
Based on this, we can also override the findGroupByQueryCriteria() and findGroupByQueryCriteriaCount() methods:
@Override public List<Group> findGroupByQueryCriteria(GroupQueryImpl query, Page page) { if (query.getUserId() != null) { return findGroupsByUser(query.getUserId()); } return null; } @Override public long findGroupCountByQueryCriteria(GroupQueryImpl query) { return findGroupByQueryCriteria(query, null).size(); }
Other methods that update groups can be overridden to throw an exception:
public Group createNewGroup(String groupId) { throw new UnsupportedOperationException("This operation is not supported!"); }
4.3. Process Engine Configuration
After defining the two identity manager classes, we need to wire them into the configuration.
The spring starters auto-configure a SpringProcessEngineConfiguration for us. To modify this, we can use an InitializingBean:
@Autowired private SpringProcessEngineConfiguration processEngineConfiguration; @Autowired private JdbcUserDetailsManager userManager; @Bean InitializingBean processEngineInitializer() { return new InitializingBean() { public void afterPropertiesSet() throws Exception { processEngineConfiguration.setUserEntityManager( new SpringSecurityUserManager(processEngineConfiguration, new MybatisUserDataManager(processEngineConfiguration), userManager)); processEngineConfiguration.setGroupEntityManager( new SpringSecurityGroupManager(processEngineConfiguration, new MybatisGroupDataManager(processEngineConfiguration))); } }; }
Here, the existing processEngineConfiguration is modified to use our custom identity managers.
If we want to set the current user in Activiti, we can use the method:
identityService.setAuthenticatedUserId(userId);
Keep in mind that this sets a ThreadLocal property, so the value is different for every thread.
5. Conclusion
In this article, we’ve seen the two ways we can integrate Activiti with Spring Security.
The full source code can be found over on GitHub.
I just announced the new Spring Security 5 modules (primarily focused on OAuth2) in the course: | https://www.baeldung.com/activiti-spring-security | CC-MAIN-2018-34 | en | refinedweb |
Will do; this is on my list of things to look at very soon. Right now
I'm focusing on making some general performance improvements.
- James
Woody Anderson wrote:
> so this is my current solution:
>
> Reader reader = response.getReader();
> String docStr = StreamUtils.getString( reader );
>
> docStr = docStr.replace( "",
>
> "" );
> Parser parser = ABDERA.getParser();
> Document<Entry> doc = parser.parse( new StringReader( docStr ) );
>
> which works but is clearly a complete hack.
> if it becomes easier to alias this namespace or handle this with an
> extension factory, please let me know.
> -w
>
> On 10/31/07, Woody Anderson <woody@xoopit.com> wrote:
>> ok. i tried to do this, but it seems i'm not understanding something
>> with regard to the getElementWrapper method.. and now the mimetype
>> (per Element?)
>>
>> public class AliasNamespacesFactory implements ExtensionFactory {
>> HashSet<String> _namespaces = new HashSet<String>();
>> public AliasNamespacesFactory( Set<String> namespaces ) {
>> _namespaces.addAll( namespaces );
>> }
>>
>> public <T extends Element> T getElementWrapper(Element internal) {
>> // ????????
>> }
>>
>> public <T extends Base> String getMimeType(T base) {
>> // ??????????
>> }
>>
>> public String[] getNamespaces() {
>> return _namespaces.toArray( new String[ _namespaces.size() ] );
>> }
>>
>> public boolean handlesNamespace(String namespace) {
>> return _namespaces.contains( namespace );
>> }
>> }
>>
>>
>> do i have to have a if/else to instantiate FOMEntry, FOMLink, etc.. ?
>> most of the constructors are protected, which makes that sort of a non-starter.
>>
>> FOMFactory seems to have a lot of methods, but these take objects that
>> i don't have at my disposal. And these seem much more geared toward
>> creation for population, not for cloning or refacing an existing
>> "Element".
>>
>> do i need to basically recreate the FOMFactory for myself? and
>> subsequently all of the objects?
>>
>> on a complete hack approach:
>> if i ask the ClientResponse for a reader and put the entire response
>> in a string replacing the namespace with the "correct" namespace. i
>> could just ask for the default parser and continue right?
>> i mean this would be ugly in the extreme, but it sounds only slightly
>> worse than recreating the entire FOM factory just to change broken-ns
>> to atom-ns.
>>
>> and the only other way i see to get in front of the system is to front
>> a stream reader via. createXMLStreamReader, but that seems tied up in
>> axiom.. which is an extra helping of confusing.
>>
>> thoughts?
>> -w
>>
>> On 10/31/07, James M Snell <jasnell@gmail.com> wrote:
>>> Ok, this is actually somewhat difficult right now but definitely
>>> possible. What you'd need to do is create a custom ExtensionFactory
>>> implementation (that does not extend AbstractExtensionFactory) and use
>>> that to create the appropriate objects. The getElementWrapper method is
>>> not required to return an instance of an actual ElementWrapper subclass.
>>>
>>> It would take a bit of work to do, because the internal element passed
>>> in to getElementWrapper would need to be used to create a new instance
>>> of the appropriate FOM impl.
>>>
>>> It's entirely possible that this could be made easier.
>>>
>>> - James
>>>
>>> Woody Anderson wrote:
>>>> hello,
>>>>
>>>> i'm getting an errant namespace in responses from various servers.
>>>>
>>>> e.g.
>>>> <?xml version="1.0" encoding="utf-8"?>
>>>> <entry xmlns="">
>>>> <title xmlns="">Example Title</title>
>>>> <summary xmlns="">Example Text</summary>
>>>> <content xmlns="" mode="xml">
>>>> <div xmlns="">Example Text</div>
>>>> </content>
>>>> <id xmlns="">urn:lj:livejournal.com:atom1:username:number</id>
>>>> <link xmlns="" type="application/x.atom+xml"
>>>>>>> href="" title="Example
>>>> Title"/>
>>>> <link xmlns="" type="text/html"
>>>>>>>
>>>> </entry>
>>>>
>>>> i want to handle this as though it were a correctly namespaced entry.
>>>> all types of elements from this server comeback with this namespace,
>>>> so i need this for each of the model elements.
>>>>
>>>> I'm a bit confused about how i do this for all elements. I've been
>>>> looking at AbstractExtensionFactory.
>>>> and ExtensionFactory docs, but it is unclear what getElementWrapper()
>>>> is supposed to do to make it all "work".
>>>>
>>>> i would hope that it's fairly simple to consume this bogus namespace.
>>>>
>>>> i found an old example doing something *similar* that extended
>>>> FOMExtensionFactory (which no longer exists..) to handle an Atom03
>>>> feed. This example doesn't work anymore and was still pretty confusing
>>>> as it seemed to work for Feed only.
>>>>
>>>> is there a simple way to handle this errant ns?
>>>> thanks
>>>> -w
>>>>
> | http://mail-archives.apache.org/mod_mbox/abdera-user/200711.mbox/%3C472FBB41.8000801@gmail.com%3E | CC-MAIN-2018-34 | en | refinedweb |
Current Version:
Linux Kernel - 3.80
Synopsis
#include <stdio.h> FILE *popen(const char *command, const char *type); int pclose(FILE *stream);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
popen(), pclose():
- _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE
Description aqraq for reading or the letter aqwaq for writing. Since glibc 2.9, this argument can additionally include the letter aqeaq,
Errors
Conforming To
The aqeaq value for type is a Linux extension.
Bugs
Failure to execute the shell is indistinguishable from the shell's failure to execute command, or an immediate exit of the command. The only hint is an exit status of 127.
Colophon
License & Copyright
Copyright @(#)popen.3) | https://community.spiceworks.com/linux/man/3/popen | CC-MAIN-2018-34 | en | refinedweb |
VLCMobileKit does not play RTSP video
VLCMobileKit cannot open RTSP streaming video.
It shows the error:
VLC is unable to open the MRL 'rtsp://193.159.244.134/rtsp_tunnel?profile=0&h26x=4&enableaudio=1&audio_mode=1&vcd=2'.
- How do I write a script that configures an applications settings for me?
I need help on how to write a script that configures an applications (VLC) settings to my needs without having to do it manually myself. The reason for this is because I will eventually need to start this application on boot with the correct settings already configured.
Steps I need done in the script.
1) I need to open the application.
2) Open the “Open Network Stream…” tab (Can be done with Ctrl+N).
3) Type a string of characters “String of characters”
4) Push “Enter” twice on the keyboard.
I’ve checked various websites across the internet and could not find any information regarding this. I am sure it’s possible but I am new to writing scripts and not too experienced. Are commands like the steps above possible to be completed in a script?
Note: Using Linux based OS (Raspbian).
Thank you.
- Split path when opening a media in vlc via c# process
I'm making a WinForm app that let a user to open video through a media player (vlc in the current case). The video path is selected through a openFileDialog control. Here is the code that I use:
private void button1_Click(object sender, EventArgs e) { Process.Start(@"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe", openFileDialog.FileName); }
The problem is that this code split file path by space and open each part of path as a file for exemple: The chosen path is
c:\folde1\folder 2\my awesome movie.mp4So it will treat
c:\folde1\folder,
2\my,
awesomeand
movie.mp4as seperate files. How can deal with this issues?
- VLC doesnt create rtsp stream
I`m trying to create a RTSP stream with VLC, but vlc doesn`t create it. I use this code:
:sout=#transcode{vcodec=h264,acodec=mpga,ab=128,channels=2,samplerate=44100}:rtp{sdp=rtsp://:8554/test} :no-sout-all :sout-keep
I can streaming using RTP and http without proublems, but i need RTSP. Also i can connect to some RTSP-stream (ip-cam for example) and play it using VLC or self-created app with vlcj.
- Android LibVLC options do not work
I am working with streaming RTSP using LibVLC. I have it working where I can view the stream, but the latency is set to the default ~2seconds.
On the Ubuntu Desktop I can launch vlc with the following options to improve the latency greatly:
$ vlc -vvv rtsp://192.168.2.1:1234 --network-caching=50 --clock-jitter=0 --clock-synchro=0
however, when I add these options to LibVLC, there is no positive effect:
ArrayList<String> options = new ArrayList<>(); options.add("-vvv"); options.add("--network-caching=50"); options.add("--clock-jitter=0"); options.add("--clock-synchro=0"); mLibVLC = new LibVLC(this, options);
Is there something I'm missing?
- How to streaming video via VLC api in C#
I'm working on small home project for video broadcasting. I've found some example. I've found some example Example, but it does not works, because needed old version of library 0.8.6. So I found it, but I have exceptions on unmanaged code when I've tried to get components from API. So maybe somebody works with VLC for videobrodcasting I would like if you are Advise any examples.
- Vlc.DotNet.Core taking snapshot while streaming
I am using Vlc.DotNet.Core for multicast video streaming. Also, I want to take snapshots. For testing, I am working on a simple program that calling snapshot function for every 2 seconds. However snapshot function is not working, when
TakeSnapshotfunction called, it is not calling
OnMediaPlayerSnapshotTakenevent.
Besides that, I made a snapshot tests for
Vlc.DotNet.Formslibrary and its working quite well.
The simple code I am working on is given below :
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Timers; using Vlc.DotNet.Core; namespace SnapshotTest { class Program { static void Main(string[] args) { VlcStreamerSnapshotText myObject = new VlcStreamerSnapshotText(); myObject.streamFile(); } } class VlcStreamerSnapshotText { System.Timers.Timer aTimer = new System.Timers.Timer(); static Vlc.DotNet.Core.VlcMediaPlayer mediaPlayer; public bool streamFile(string source = "") { aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.Interval = 2000; aTimer.Enabled = true; var currentDirectory = Directory.GetCurrentDirectory(); var libDirectory = new DirectoryInfo(Path.Combine(currentDirectory, "libvlc", IntPtr.Size == 4 ? "x86" : "x64")); var options = new string[] { "--no-snapshot-preview", "--no-audio" //"--no-video" // VLC options can be given here. Please refer to the VLC command line documentation. }; mediaPlayer = new Vlc.DotNet.Core.VlcMediaPlayer(new DirectoryInfo(libDirectory.FullName), options); string[] mediaOptions = new string[] { ":sout=#duplicate{dst=rtp{sdp=rtsp://127.0.0.1:1000/},dst=display}", ":sout-all", ":sout-keep" }; //string[] mediaOptions = new string[] { string.Concat("--sout=#duplicate{dst=rtp{sdp=rtsp://", IpAddress, ":", "1000", "/}} --sout-all --sout-keep") }; mediaPlayer.SetMedia(new Uri(""), mediaOptions); mediaPlayer.SnapshotTaken += OnMediaPlayerSnapshotTaken; bool playFinished = false; mediaPlayer.PositionChanged += (sender, e) => { Console.Write("\r" + Math.Floor(e.NewPosition * 100) + "%"); }; mediaPlayer.EncounteredError += (sender, e) => { Console.Error.Write("An error occurred"); playFinished = true; }; mediaPlayer.EndReached += (sender, e) => { playFinished = true; }; Task.Factory.StartNew(() => mediaPlayer.Play()); //mediaPlayer.Play(); // Ugly, sorry while (!playFinished) { Thread.Sleep(TimeSpan.FromMilliseconds(500)); } return true; } ManualResetEvent m_mreSnapshot = new ManualResetEvent(false); private readonly object m_snapLock = new object(); private bool m_SnapshotIsTaken = false; public bool GetSnapshot() { m_SnapshotIsTaken = false; if (mediaPlayer == null) { return false; } string currentTime = DateTime.Now.ToString("yyyyMMdd_HHmmss"); string uniqueId = generateID(string.Empty); string snapName = string.Format("{0}_{1}.png", currentTime, uniqueId); string tempFilePathCand = Path.GetTempPath(); if (!tempFilePathCand.EndsWith("\\")) tempFilePathCand = tempFilePathCand + "\\" + snapName; else tempFilePathCand = tempFilePathCand + snapName; FileInfo snapPathInfo = new FileInfo(tempFilePathCand); //mediaPlayer.Manager.TakeSnapshot(); mediaPlayer.TakeSnapshot(snapPathInfo); m_mreSnapshot.WaitOne(TimeSpan.FromSeconds(2)); if (m_SnapshotIsTaken) return true; return false; } private string generateID(string tip) { return string.Format(@"{0}_{1}", tip, Guid.NewGuid().ToString("N")); } void OnMediaPlayerSnapshotTaken(object sender, VlcMediaPlayerSnapshotTakenEventArgs e) { mediaPlayer.SnapshotTaken -= OnMediaPlayerSnapshotTaken; m_SnapshotIsTaken = true; mediaPlayer.SnapshotTaken += OnMediaPlayerSnapshotTaken; } private void OnTimedEvent(object source, ElapsedEventArgs e) { GetSnapshot(); } } }
So, What am I missing? | http://quabr.com/50363266/vlcmobilekit-does-not-play-rtsp-video | CC-MAIN-2018-34 | en | refinedweb |
Introducing Caching for Java Applications (Part 1)
Introducing Caching for Java Applications (Part 1)
Caching may address new challenges when developing performing applications.
Join the DZone community and get the full member experience.Join For Free
How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.
An increasing volume of critical data presents new challenges when developing performing applications with Java. Caching may address these challenges if applied right. This series of two articles explores ways for improving performance, concurrency and scalability in Java applications through caching.
Notion of Cache
A cache is an area of local memory that holds a copy of frequently accessed data that is otherwise expensive to get or compute. Examples of such data include a result of a query to a database, a disk file or a report. A typical interface for a Java cache provides access to the data using a unique key:
public interface Cache { Object get(final Object key);Object put(final Object key, final Object value);}
A cache works as the following: An application requests data from cache using a key. If the key is not found, the application retrieves the data from a slow data source and puts it into the cache. The next request for a key is serviced from the cache.
Improving Performance with Caching
Caching may provide significant performance improvement for a Java application, often in orders of magnitude. The performance improvement comes from serving hard to get data from the local memory of the application.
For example, consider an application that shows a 50-line system status report displayed on a web page after the user logs into the system. For each line it sends a complex SQL query to a database. To execute each query and to fetch results over the network takes 100 milliseconds on average. The total average time to collect all data for the page is about 5 seconds. Getting the same results from a cache takes about 5 microseconds on a modern 2GHz CPU. The performance improvement for this particular use scenario is 1,000,000!
Requirement for Temporal and Spatial Locality
A cache uses a part of the application's memory. That is why the size of the cache has to be small. A special algorithm should be used to remove (evict) data from the cache that has low chances of access. Such algorithm is called an eviction policy. To benefit from caching, the access to data should display properties of temporal and spatial locality. The data should be accessed often (temporal locality) and the probability of accessing a near cache element should be high (spatial locality). Increasing cache size for the data that satisfies this requirement increases hit/miss ratio.
The data from the example in the beginning of the article satisfies the requirement of temporal and spatial locality . Users log into the system around the same time and the number of items from the reports that are accessed in rapid succession is small.
Data that does not satisfy the requirement of temporal and spatial locality of access leads to faster eviction of cache elements and as a result will lower the number of cache hits and increase cache maintenance.
Cache Performance Characteristics
The main performance characteristic of a cache is a hit/miss ratio. The hit/miss ratio is calculated as number of cache hits divided by number of cache misses. The hit/miss ratio is calculated using hit and miss counters accumulated over a period of time. A high hit/miss ratio means that a cache performs well. A low hit/miss ratio means that the cache is applied to data that should not be cached. Also, the low hit/miss ratio may mean that a cache is too small to capture temporal locality of data access.
Cache Eviction Policy
A cache eviction policy is an algorithm according to which an existing element is removed from a cache when a new element is added. The eviction policy is applied to ensure that the size of the cache does not exceed a maximum size. Least Recently Used (LRU) is one of the most popular among a number of eviction policies. LRU earned its popularity for being the best in capturing temporal and spatial locality of data access.
A minor disadvantage or LRU is its sensitivity to a full scan. The sensitivity manifests itself in evicting accumulated frequently accessed cache elements when accessing data that does not satisfy the requirement of temporal locality. This disadvantage is minor because LRU recovers from full scans quickly.
A typical implementation of a cache with the LRU eviction policy consists of a map and a linked list. The map stores cached elements. The linked list keep tracks of the least recently used cache elements. When a cache element is updated, it is removed from the list and added to the top of the list. The new elements are added to the top of the list as well. If the cache grows bigger than its maximum size, an element is removed from the bottom of the list and from the map. This way the least recently used elements are evicted first.
Simple LRU Cache in Ten Lines
Java 5 added a class java.util.LinkedHashMap. The main goal of this class is to provide the key, value and entry iteration that are consistent with an order of entry. In addition, LinkedHashMap includes a provision for implementing a simple LRU cache. Below is an implementation of a simple LRU cache that uses only 10 lines of code:
import java.util.Map;import java.util.LinkedHashMap; public final class SimpleLRUCache extends LinkedHashMap{ private int maxSize; public SimpleLRUCache(final int maxSize) { super(1, 0.75f, true); this.maxSize = maxSize; } protected boolean removeEldestEntry(final Map.Entry eldest) { return size() > maxSize; } }
While this simple cache does evict least recently used elements, it is missing important features that a cache needs to have in order to be usable in a real application. Please see section Caching Products for Java for a detailed discussion.
Common Cache Use Scenarios
Common cache use scenarios include an application cache, a second level (L2) cache and a hybrid cache.
Application Cache
An application cache is a cache that an application accesses directly. An application benefits from using a cache by keeping most frequently accessed data in memory .
The following communication diagram illustrates using an application cache:
Level-2 Cache
One of the major use scenarios for a cache is a level-2 (L2) cache . An L2 cache provides caching services to an object-relational mapping (ORM) framework or a data mapping (DM) framework such as Hibernate or iBatis respectively. An L2 cache hides the complexity of the caching logic from an application.
An L2 cache improves performance of an ORM or DM framework by reducing unnecessary trips to the database .
The following communication diagram illustrates using an L2 cache:
The application does not access cache directly in this use scenario. Instead, the application utilizes a high level interface provided by an ORM or a DM framework. The framework uses cache for caching its internal data structures such as mapped objects and database query results. If the cached data is not available, the framework retrieves it from the database and puts it into the cache.
Hybrid Cache
A hybrid cache is a cache that uses an external data source to retrieve data that is not present in the cache. An application using a hybrid cache benefits from simplified programming of cache access.
This use scenario is different from the application or the second-level cache when an application or a data access framework is responsible for populating the cache in case of cache misses.
The following communication diagram illustrates using a hybrid cache:
Caching Anti-Patterns
Caching provides such a great improvement of performance that it is often used without limit. An anti-pattern Cache Them All is characterized by caching all data, without regard to temporal or spatial locality of data access . Cache Them All degrades application performance instead of improving it. The degradation of performance is caused by the overhead of maintaining a cache without benefiting from reduced cost of access to frequently used data.
To avoid the pitfall of the Cache Them All , only data that is hard to get and shows temporal and spatial locality of access should be cached.
Caching Products for Java
While it takes only 10 lines of code to write your own cache for Java, developing a usable cache is a challenging task. The simple 10-line cache is missing many important features required for using it in an application. Some of these features include concurrent access, configuration, eviction to disk and statistics.
Fortunately, several projects have already developed working caching APIs, so there is no need to reinvent the wheel.
A commercial caching API maybe a safe bet if your organization wants to be sure that its requests for help are addressed in time and that a caching API is developed professionally.
Often an organization cannot afford commercial software and is ready to take risks. In such situation a free caching API may be a solution.
The following sections outline some commercial and free product supporting local caching.
Commercial Products
Free Products
About Author
Slava Imeshev is a president and CEO of Cacheonix Systems. You can reach Slava at simeshev@cacheonix }} | https://dzone.com/articles/inroducing-caching-java-applic | CC-MAIN-2018-34 | en | refinedweb |
While working on an socket-based application, we received the following warnings from the compiler:
implicit declaration of function 'read' implicit declaration of function 'write'
read and
write functions are declared in
unistd.h which we forgot to include in our code.
Adding the directive
#include <unistd.h>
to the source file that used
read and/or
write removed the warnings.
This post is also available in: Greek
I was having the same trouble and your solution worked for me, thank you very much!!!
This helped.
Thanks.
—
Furry cows moo and decompress. | https://bytefreaks.net/programming-2/c-programming-2/c-implicit-declaration-of-function-read-and-write | CC-MAIN-2018-34 | en | refinedweb |
I just announced the new Spring 5 modules in REST With Spring:
1. Overview
The 2.0 Version of the Java Bean Validation specification adds several new features, among which is the possibility to validate elements of containers.
This new functionality takes advantage of type annotations introduced in Java 8. Therefore it requires Java version 8 or higher to work.
Validation annotations can be added to containers such as collections, Optional objects, and other built-in as well as custom containers.
For an introduction to Java Bean Validation and how to setup the Maven dependencies we need, check out our previous article here.
In the following sections, we’ll focus on validating elements of each type of container.
2. Collection Elements
We can add validation annotations to elements of collections of type java.util.Iterable, java.util.List and java.util.Map.
Let’s see an example of validating the elements of a List:
public class Customer { List<@NotBlank(message="Address must not be blank") String> addresses; // standard getters, setters }
In the example above, we’ve defined an addresses property for a Customer class, which contains elements that cannot be empty Strings.
Note that the @NotBlank validation applies to the String elements, and not the entire collection. If the collection is empty, then no validation is applied.
Let’s verify that if we attempt to add an empty String to the addresses list, the validation framework will return a ConstraintViolation:
@Test public void whenEmptyAddress_thenValidationFails() { Customer customer = new Customer(); customer.setName("John"); customer.setAddresses(Collections.singletonList(" ")); Set<ConstraintViolation<Customer>> violations = validator.validate(customer); assertEquals(1, violations.size()); assertEquals("Address must not be blank", violations.iterator().next().getMessage()); }
Next, let’s see how we can validate the elements of a collection of type Map:
public class CustomerMap { private Map<@Email String, @NotNull Customer> customers; // standard getters, setters }
Notice that we can add validation annotations for both the key and the value of a Map element.
Let’s verify that adding an entry with an invalid email will result in a validation error:
@Test public void whenInvalidEmail_thenValidationFails() { CustomerMap map = new CustomerMap(); map.setCustomers(Collections.singletonMap("john", new Customer())); Set<ConstraintViolation<CustomerMap>> violations = validator.validate(map); assertEquals(1, violations.size()); assertEquals( "Must be a valid email", violations.iterator().next().getMessage()); }
3. Optional Values
Validation constraints can also be applied to an Optional value:
private Integer age; public Optional<@Min(18) Integer> getAge() { return Optional.ofNullable(age); }
Let’s create a Customer with an age that is too low – and verify that this results in a validation error:
@Test public void whenAgeTooLow_thenValidationFails() { Customer customer = new Customer(); customer.setName("John"); customer.setAge(15); Set<ConstraintViolation<Customer>> violations = validator.validate(customer); assertEquals(1, violations.size()); }
On the other hand, if the age is null, then the Optional value is not validated:
@Test public void whenAgeNull_thenValidationSucceeds() { Customer customer = new Customer(); customer.setName("John"); Set<ConstraintViolation<Customer>> violations = validator.validate(customer); assertEquals(0, violations.size()); }
4. Non-Generic Container Elements
Besides adding annotations for type arguments, we can also apply validation to non-generic containers, as long as there is a value extractor for the type with the @UnwrapByDefault annotation.
Value extractors are the classes that extract the values from the containers for validation.
The reference implementation contains value extractors for OptionalInt, OptionalLong and OptionalDouble:
@Min(1) private OptionalInt numberOfOrders;
In this case, the @Min annotation applies to the wrapped Integer value, and not the container.
5. Custom Container Elements
In addition to the built-in value extractors, we can also define our own and register them with a container type.
In this way, we can add validation annotations to elements of our custom containers.
Let’s add a new Profile class that contains a companyName property:
public class Profile { private String companyName; // standard getters, setters }
Next, we want to add a Profile property in the Customer class with a @NotBlank annotation – which verifies the companyName is not an empty String:
@NotBlank private Profile profile;
For this to work, we need a value extractor that determines the validation to be applied to the companyName property and not the profile object directly.
Let’s add a ProfileValueExtractor class that implements the ValueExtractor interface and overrides the extractValue() method:
@UnwrapByDefault public class ProfileValueExtractor implements ValueExtractor<@ExtractedValue(type = String.class) Profile> { @Override public void extractValues(Profile originalValue, ValueExtractor.ValueReceiver receiver) { receiver.value(null, originalValue.getCompanyName()); } }
This class also need to specify the type of the value extracted using the @ExtractedValue annotation.
Also, we’ve added the @UnwrapByDefault annotation that specifies the validation should be applied to the unwrapped value and not the container.
Finally, we need to register the class by adding a file called javax.validation.valueextraction.ValueExtractor to the META-INF/services directory, which contains the full name of our ProfileValueExtractor class:
org.baeldung.valueextractors.ProfileValueExtractor
Now, when we validate a Customer object with a profile property with an empty companyName, we will see a validation error:
@Test public void whenProfileCompanyNameBlank_thenValidationFails() { Customer customer = new Customer(); customer.setName("John"); Profile profile = new Profile(); profile.setCompanyName(" "); customer.setProfile(profile); Set<ConstraintViolation<Customer>> violations = validator.validate(customer); assertEquals(1, violations.size()); }
Note that if you are using hibernate-validator-annotation-processor, adding a validation annotation to a custom container class, when it’s marked as @UnwrapByDefault, will result in a compilation error in version 6.0.2.
This is a known issue and will likely be resolved in a future version.
6. Conclusion
In this article, we’ve shown how we can validate several types of container elements using Java Bean Validation 2.0.
You can find the full source code of the examples over on GitHub. | https://www.baeldung.com/bean-validation-container-elements | CC-MAIN-2018-34 | en | refinedweb |
Thinking in Java EE (At Least Trying To!)
Thinking in Java EE (At Least Trying To!)
The CDI programming model isn't self-contained. But injecting the right beans will make it easier to think in Java EE. Here are a few.
Join the DZone community and get the full member experience.Join For Free
The CDI programming model has prerequisite requirements for beans which are lucky enough to leverage its services (DI, contextual state management etc.). This ranges from typical Java EE Managed Beans, EJB (session) beans etc. (I’ll leave the details for another post).
But the Good Thing is That
...it also provides some freebies i.e. beans which are available for injection by default
- HttpSession
- HttpServletRequest
- ServletContext
- UserTransaction
- Principal
To be Noted
- One can user either @Resource or the more obvious @Inject annotation to trigger injection
- The @Default qualifier is applicable to injected instances of these beans
@Stateless @TransactionManagement(TransactionManagementType.BEAN) @Path("cdi/freebies") public class CDIFreebieResource { @Inject UserTransaction uTx; @Inject Principal actor; @Inject HttpSession httpSession; @Inject HttpServletRequest httpSR; @Inject ServletContext sCtx; @GET public String get() throws Exception{ return "User Tx status: " + uTx.getStatus() + "\n" + "Principal: " + actor.getName() + "\n" + "HTTP Session ID: " + httpSession.getId() + "\n" + "HTTP Method: " + httpSR.getMethod() + "\n" + "Context Path: " + sCtx.getContextPath(); } }
Where can I Inject These Beans ?
Well, standard rules (defined by the CDI specification) apply here. I would recommend looking into the official Java EE Platform specification document (section EE 5.2.5, Table EE.5-1) which details this clearly. Here is a snapshot – Java EE managed beans, CDI managed beans, EJB, Servlet spec components, Web Socket endpoints, JSF managed beans etc.
Go on, check out the freebies … }} | https://dzone.com/articles/thinking-in-java-ee-at-least-trying-to-1 | CC-MAIN-2020-29 | en | refinedweb |
import "github.com/mailru/easyjson/jlexer"
Package jlexer contains a JSON lexer implementation.
It is expected that it is mostly used with generated parser code, so the interface is tuned for a parser that knows what kind of data is expected.
bytestostr.go error.go lexer.go
type Lexer struct { Data []byte // Input data given to the lexer. UseMultipleErrors bool // If we want to use multiple errors. // contains filtered or unexported fields }
Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice.
Bool reads a true or false boolean keyword.
Bytes reads a string literal and base64 decodes it into a byte slice.
Consumed reads all remaining bytes from the input, publishing an error if there is anything but whitespace remaining.
Delim consumes a token and verifies that it is the given delimiter.
FetchToken scans the input for the next token.
func (r *Lexer) GetNonFatalErrors() []*LexerError
Interface fetches an interface{} analogous to the 'encoding/json' package.
IsDelim returns true if there was no scanning error and next token is the given delimiter.
IsNull returns true if the next token is a null keyword.
IsStart returns whether the lexer is positioned at the start of an input string.
JsonNumber fetches and json.Number from 'encoding/json' package. Both int, float or string, contains them are valid values
Null verifies that the next token is null and consumes it.
Ok returns true if no error (including io.EOF) was encountered during scanning.
Raw fetches the next item recursively as a data slice
Skip skips a single token.
SkipRecursive skips next array or object completely, or just skips a single token if not an array/object.
Note: no syntax validation is performed on the skipped data.
String reads a string literal.
StringIntern reads a string literal, and performs string interning on it.
UnsafeBytes returns the byte slice if the token is a string literal.
UnsafeFieldName returns current member name string token
UnsafeString returns the string value if the token is a string literal.
Warning: returned string may point to the input buffer, so the string should not outlive the input buffer. Intended pattern of usage is as an argument to a switch statement.
WantColon requires a colon to be present before fetching next token.
WantComma requires a comma to be present before fetching next token.
LexerError implements the error interface and represents all possible errors that can be generated during parsing the JSON data.
func (l *LexerError) Error() string
Package jlexer imports 13 packages (graph) and is imported by 1197 packages. Updated 2020-04-26. Refresh now. Tools for package owners. | https://godoc.org/github.com/mailru/easyjson/jlexer | CC-MAIN-2020-29 | en | refinedweb |
November 7, 1988, petitioner filed an Urgent Motion to Discharge Attachment [8] without submittingherself to the jurisdiction of the trial court. She pointed out that up to then, she had not been served acopy of the Complaint and the summons. Hence, petitioner claimed the court had not acquired jurisdictionover her person.[9]In the hearing of the Urgent Motion to Discharge Attachment on November 11, 1988, privaterespondent sought and was granted a re-setting to December 9, 1988. On that date, private respondentscounsel did not appear, so the Urgent Motion to Discharge Attachment was deemed submitted forresolution.[10]The trial court granted the Motion to Discharge Attachment on January 13, 1989 upon filing ofpetitioners counter-bond. The trial court, however, did not rule on the question of jurisdiction and on thevalidity of the writ of preliminary attachment.On December 26, 1988, private respondent applied for an alias summons, which the trial court issuedon January 19, 1989.[11] It was only on January 26, 1989 that summons was finally served on petitioner. [12]On February 9, 1989, petitioner filed a Motion to Dismiss the Complaint on the ground of impropervenue. Private respondents invoice for the freight forwarding service stipulates that if court litigationbecomes necessary to enforce collection xxx the agreed venue for such action is Makati, Metro Manila.[13]Private respondent filed an Opposition asserting that although Makati appears as the stipulated venue,the same was merely an inadvertence by the printing press whose general manager executed anaffidavit[14] admitting such inadvertence. Moreover, private respondent claimed that petitioner knew thatprivate respondent was holding office in Pasay City and not in Makati. [15] The lower court, finding credencein private respondents assertion, denied the Motion to Dismiss and gave petitioner five days to file herAnswer. Petitioner filed a Motion for Reconsideration but this too was denied.Petitioner filed her Answer[16] on June 16, 1989, maintaining her contention that the venue wasimproperly laid.On June 26, 1989, the trial court issued an Order setting the pre-trial for July 18, 1989 at 8:30 a.m. andrequiring the parties to submit their pre-trial briefs. Meanwhile, private respondent filed a Motion to SellAttached Properties but the trial court denied the motion.On motion of petitioner, the trial court issued an Order resetting the pre-trial from July 18, 1989 toAugust 24, 1989 at 8:30 a.m..On August 24, 1989, the day of the pre-trial, the trial court issued an Order [17] terminating the pre-trialand allowing the private respondent to present evidence ex-parte on September 12, 1989 at 8:30 a.m..The Order stated that when the case was called for pre-trial at 8:31 a.m., only the counsel for privaterespondent appeared. Upon the trial courts second call 20 minutes later, petitioners counsel was stillnowhere to be found. Thus, upon motion of private respondent, the pre-trial was considered terminated.On September 12, 1989, petitioner filed her Motion for Reconsideration of the Order terminating thepre-trial. Petitioner explained that her counsel arrived 5 minutes after the second call, as shown by thetranscript of stenographic notes, and was late because of heavy traffic. Petitioner claims that the lowercourt erred in allowing private respondent to present evidence ex-parte since there was no Orderconsidering the petitioner as in default. Petitioner contends that the Order of August 24, 1989 did not statethat petitioner was declared as in default but still the court allowed private respondent to present evidenceex-parte.[18]On October 6, 1989, the trial court denied the Motion for Reconsideration and scheduled thepresentation of private respondents evidence ex-parte on October 10, 1989.
On October 10, 1989, petitioner filed an Omnibus Motion stating that the presentation of evidence exparte should be suspended because there was no declaration of petitioner as in default and petitionerscounsel was not absent, but merely late.On October 18, 1989, the trial court denied the Omnibus Motion. [19]On November 20, 1989, the petitioner received a copy of the Decision of November 10, 1989, orderingpetitioner to pay respondent P109,376.95 plus 18 percent interest per annum, 25 percent attorneys feesand costs of suit. Private respondent filed a Motion for Execution Pending Appeal but the trial court deniedthe same.The Ruling of the Court of AppealsOn December 15, 1995, the Court of Appeals rendered a decision affirming the decision of the trialcourt. The Court of Appeals upheld the validity of the issuance of the writ of attachment and sustained thefiling of the action in the RTC of Pasay. The Court of Appeals also affirmed the declaration of default onpetitioner and concluded that the trial court did not commit any reversible error.Petitioner filed a Motion for Reconsideration on January 5, 1996 but the Court of Appeals denied thesame in a Resolution dated May 20, 1996.Hence, this petition.The IssuesThe issues raised by petitioner may be re-stated as follows:I.WHETHER RESPONDENT COURT ERRED IN NOT HOLDING THAT THE WRIT OF ATTACHMENT WASIMPROPERLY ISSUED AND SERVED;II.WHETHER THERE WAS A VALID DECLARATION OF DEFAULT;III.WHETHER THERE WAS IMPROPER VENUE.IV.WHETHER RESPONDENT COURT ERRED IN DECLARING THAT PETITIONER IS OBLIGED TO PAY P109, 376.95,PLUS ATTORNEYS FEES.[20]The Ruling of the CourtImproper Issuance and Service of Writ of AttachmentPetitioner ascribes several errors to the issuance and implementation of the writ of attachment.Among petitioners arguments are: first, there was no ground for the issuance of the writ since the intent todefraud her creditors had not been established; second, the value of the properties levied exceeded thevalue of private respondents claim. However, the crux of petitioners arguments rests on the question of
the validity of the writ of attachment. Because of failure to serve summons on her before or simultaneouslywith the writs implementation, petitioner claims that the trial court had not acquired jurisdiction over herperson and thus the service of the writ is void.As a preliminary note, a distinction should be made between issuance and implementation of the writof attachment. It is necessary to distinguish between the two to determine when jurisdiction over theperson of the defendant should be acquired to validly implement the writ. This distinction is crucial inresolving whether there is merit in petitioners argument.This Court has long settled the issue of when jurisdiction over the person of the defendant should beacquired in cases where a party resorts to provisional remedies. A party to a suit may, at any time afterfiling the complaint, avail of the provisional remedies under the Rules of Court. Specifically, Rule 57 onpreliminary attachment speaks of the grant of the remedy at the commencement of the action or atany time thereafter.[21] This phrase refers to the date of filing of the complaint which is the moment thatmarks the commencement of the action. The reference plainly is to a time before summons is served onthe defendant, or even before summons issues.In Davao Light & Power Co., Inc. v. Court of Appeals, [22] this Court clarified the actual time whenjurisdiction should be had:It goes without saying that whatever be the acts done by the Court prior to the acquisition of jurisdictionover the person of defendant - issuance of summons, order of attachment and writ of attachment these do not and cannot bind and affect the defendant until and unless jurisdiction over hisperson is eventually obtained by the court, either by service on him of summons or other coerciveprocess or his voluntary submission to the courts authority. Hence, when the sheriff or other proper officercommences implementation of the writ of attachment, it is essential that he serve on the defendant notonly a copy of the applicants affidavit and attachment bond, and of the order of attachment, as explicitlyrequired by Section 5 of Rule 57, but also the summons addressed to said defendant as well as a copy ofthe complaint xxx. (Emphasis supplied.)Furthermore, we have held that the grant of the provisional remedy of attachment involves three stages:first, the court issues the order granting the application; second, the writ of attachment issues pursuant tothe order granting the writ; and third, the writ is implemented. For the initial two stages, it is notnecessary that jurisdiction over the person of the defendant be first obtained. However, oncethe implementation of the writ commences, the court must have acquired jurisdiction over thedefendant for without such jurisdiction, the court has no power and authority to act in any manner againstthe defendant. Any order issuing from the Court will not bind the defendant. [23]In the instant case, the Writ of Preliminary Attachment was issued on September 27, 1988 andimplemented on October 28, 1988. However, the alias summons was served only onJanuary 26, 1989 or almost three months after the implementation of the writ of attachment.The trial court had the authority to issue the Writ of Attachment on September 27 since a motion forits issuance can be filed at the commencement of the action. However, on the day the writ wasimplemented, the trial court should have, previously or simultaneously with the implementation of the writ,acquired jurisdiction over the petitioner. Yet, as was shown in the records of the case, the summons wasactually served on petitioner several months after the writ had been implemented.Private respondent, nevertheless, claims that the prior or contemporaneous service of summonscontemplated in Section 5 of Rule 57 provides for exceptions. Among such exceptions are where thesummons could not be served personally or by substituted service despite diligent efforts or where thedefendant is a resident temporarily absent therefrom x x x. Private respondent asserts that when shecommenced this action, she tried to serve summons on petitioner but the latter could not be located at her
customary address in Kamuning, Quezon City or at her new address in Guagua, Pampanga. [24] Furthermore,respondent claims that petitioner was not even in Pampanga; rather, she was in Guam purportedly on abusiness trip.Private respondent never showed that she effected substituted service on petitioner after her personalservice failed. Likewise, if it were true that private respondent could not ascertain the whereabouts ofpetitioner after a diligent inquiry, still she had some other recourse under the Rules of Civil Procedure.The rules provide for certain remedies in cases where personal service could not be effected on aparty. Section 14, Rule 14 of the Rules of Court provides that whenever the defendants whereabouts areunknown and cannot be ascertained by diligent inquiry, service may, by leave of court, be effected uponhim by publication in a newspaper of general circulation x x x. Thus, if petitioners whereabouts could notbe ascertained after the sheriff had served the summons at her given address, then respondent could haveimmediately asked the court for service of summons by publication on petitioner. [25]Moreover, as private respondent also claims that petitioner was abroad at the time of the service ofsummons, this made petitioner a resident who is temporarily out of the country. This is the exact situationcontemplated in Section 16,[26] Rule 14 of the Rules of Civil Procedure, providing for service of summons bypublication.In conclusion, we hold that the alias summons belatedly served on petitioner cannot be deemed tohave cured the fatal defect in the enforcement of the writ. The trial court cannot enforce such a coerciveprocess on petitioner without first obtaining jurisdiction over her person. The preliminary writ ofattachment must be served after or simultaneous with the service of summons on the defendant whetherby personal service, substituted service or by publication as warranted by the circumstances of the case.[27]The subsequent service of summons does not confer a retroactive acquisition of jurisdiction over herperson because the law does not allow for retroactivity of a belated service.Improper VenuePetitioner assails the filing of this case in the RTC of Pasay and points to a provision in privaterespondents invoice which contains the following:3. If court litigation becomes necessary to enforce collection, an additional equivalent (sic) to 25% of theprincipal amount will be charged. The agreed venue for such action is Makati, Metro Manila, Philippines. [28]Based on this provision, petitioner contends that the action should have been instituted in the RTC ofMakati and to do otherwise would be a ground for the dismissal of the case.We resolve to dismiss the case on the ground of improper venue but not for the reason stated bypetitioner.The Rules of Court provide that parties to an action may agree in writing on the venue on which anaction should be brought.[29] However, a mere stipulation on the venue of an action is not enough topreclude parties from bringing a case in other venues. [30] The parties must be able to show that suchstipulation is exclusive. Thus, absent words that show the parties intention to restrict the filing of a suit in aparticular place, courts will allow the filing of a case in any venue, as long as jurisdictional requirementsare followed. Venue stipulations in a contract, while considered valid and enforceable, do not as a rulesupersede the general rule set forth in Rule 4 of the Revised Rules of Court. [31] In the absence of qualifyingor restrictive words, they should be considered merely as an agreement on additional forum, not aslimiting venue to the specified place.[32]
In the instant case, the stipulation does not limit the venue exclusively to Makati. There are noqualifying or restrictive words in the invoice that would evince the intention of the parties that Makati isthe only or exclusive venue where the action could be instituted. We therefore agree with privaterespondent that Makati is not the only venue where this case could be filed.Nevertheless, we hold that Pasay is not the proper venue for this case.Under the 1997 Rules of Civil Procedure, the general rule is venue in personal actions is where thedefendant or any of the defendants resides or may be found, or where the plaintiff or any of the plaintiffsresides, at the election of the plaintiff. [33] The exception to this rule is when the parties agree on anexclusive venue other than the places mentioned in the rules. But, as we have discussed, this exception isnot applicable in this case. Hence, following the general rule, the instant case may be brought in the placeof residence of the plaintiff or defendant, at the election of the plaintiff (private respondent herein).In the instant case, the residence of private respondent (plaintiff in the lower court) was not alleged inthe complaint. Rather, what was alleged was the postal address of her sole proprietorship, Air SwiftInternational. It was only when private respondent testified in court, after petitioner was declared indefault, that she mentioned her residence to be in Better Living Subdivision, Paraaque City.In the earlier case of Sy v. Tyson Enterprises, Inc.,[34] the reverse happened. The plaintiff in that casewas Tyson Enterprises, Inc., a corporation owned and managed by Dominador Ti. The complaint, however,did not allege the office or place of business of the corporation, which was in Binondo, Manila. What wasalleged was the residence of Dominador Ti, who lived in San Juan, Rizal. The case was filed in the Court ofFirst Instance of Rizal, Pasig. The Court there held that the evident purpose of alleging the address of thecorporations president and manager was to justify the filing of the suit in Rizal, Pasig instead of in Manila.Thus, the Court ruled that there was no question that venue was improperly laid in that case and held thatthe place of business of Tyson Enterpises, Inc. is considered as its residence for purposes of venue.Furthermore, the Court held that the residence of its president is not the residence of the corporationbecauseCity, where the business of private respondent is found. This would have been permissible had privaterespondents business been a corporation, just like the case in Sy v. Tyson Enterprises, Inc. However, asadmitted by private respondent in her Complaint[37] in the lower court, her business is a sole proprietorship,and as such, does not have a separate juridical personality that could enable it to file a suit in court. [38] Infact, there is no law authorizing sole proprietorships to file a suit in court. [39]A sole proprietorship does not possess a juridical personality separate and distinct from thepersonality of the owner of the enterprise. [40] The law merely recognizes the existence of a soleproprietorship as a form of business organization conducted for profit by a single individual and requires itsproprietor or owner to secure licenses and permits, register its business name, and pay taxes to thenational government.[41] The law does not vest a separate legal personality on the sole proprietorship orempower it to file or defend an action in court.[42]Thus, not being vested with legal personality to file this case, the sole proprietorship is not the plaintiffin this case but rather Loreta Guina in her personal capacity. In fact, the complaint in the lower courtacknowledges in its caption that the plaintiff and defendant are Loreta Guina and Anita Mangila,respectively. The title of the petition before us does not state, and rightly so, Anita Mangila v. Air SwiftInternational, but rather Anita Mangila v. Loreta Guina. Logically then, it is the residence of privaterespondent Guina, the proprietor with the juridical personality, which should be considered as one of theproperimproper venue.Although petitioner filed an Urgent Motion to Discharge Attachment in the lower court, petitionerexpressly stated that she was filing the motion without submitting to the jurisdiction of the court. At thattime, petitioner had not been served the summons and a copy of the complaint. [43] Thereafter, petitionertimely filed a Motion to Dismiss[44] on the ground of improper venue. Rule 16, Section 1 of the Rules ofCourt provides that a motion to dismiss may be filed [W]ithin the time for but before filing the answer tothe complaint or pleading asserting a claim. Petitioner even raised the issue of improper venue in hisAnswer[45] as a special and affirmative defense. Petitioner also continued to raise the issue of impropervenue in her Petition for Review [46] before this Court. We thus hold that the dismissal of this case on theground of improper venue is warranted.The rules on venue, like other procedural rules, are designed to insure a just and orderlyadministration of justice or the impartial and evenhanded determination of every action and proceeding.Obviously, this objective will not be attained if the plaintiff is given unrestricted freedom to choose whereto file the complaint or petition.[47]We find no reason to rule on the other issues raised by petitioner.WHEREFORE, the petition is GRANTED on the grounds of improper venue and invalidity of the serviceof the writ of attachment. The decision of the Court of Appeals and the order of respondent judge denyingthe motion to dismiss are REVERSED and SET ASIDE. Civil Case No. 5875 is hereby dismissed withoutprejudice to refiling it in the proper venue. The attached properties of petitioner are ordered returned toher immediately.SO ORDERED.Puno, (Chairman), and Panganiban, JJ., concur.Sandoval-Gutierrez, J., on leave.
A. M. No. 09-6-9-SCPresent:PUNO, CJ,QUISUMBING*,YNARES-SANTIAGO*,CARPIO,CORONA,CARPIO MORALES,CHICO-NAZARIO,VELASCO, JR.,NACHURA,LEONARDO-DE CASTRO,BRION,PERALTA,BERSAMIN,DEL CASTILLO**, andABAD**, JJ.Promulgated:August 19, 2009
x-----------------------------------------------------------------------------------------xRESOLUTIONBERSAMIN, J.:In his letter dated May 22, 2009 addressed to the Chief Justice, Mr. Roger C. Prioreschi,administrator of the Good Shepherd Foundation, Inc., wrote:The Good Shepherd Foundation, Inc. is very grateful for your 1rst. Indorsement to pay anominal fee of Php 5,000.00 and the balance upon the collection action of 10 million pesos,thus giving us access to the Justice System previously denied by an up-front excessive courtfee.The Hon. Court Administrator Jose Perez pointed out to the need of complying with OCACircular No. 42-2005 and Rule 141 that reserves this privilege to indigent persons. Whilejudges are appointed to interpret the law, this type of law seems to be extremely detailedwith requirements that do not leave much room for interpretations.In addition, this law deals mainly with individual indigent and it does not includeFoundations or Associations that work with and for the most Indigent persons. As seen in ourArticle of Incorporation, since 1985 the Good Shepherd Foundation, Inc. reached-out to thepoorest among the poor, to the newly born and abandoned babies, to children who neversaw the smile of their mother, to old people who cannot afford a few pesos to pay forcommon prescriptions, to broken families who returned to a normal life. In other words, wehave been working hard for the very Filipino people, that the Government and the societycannot reach to, or have rejected or abandoned them.Can the Courts grant to our Foundation who works for indigent andunderprivileged people, the same option granted to indigent people?
The two Executive Judges, that we have approached, fear accusations of favoritism orother kind of attack if they approve something which is not clearly and specifically stated inthe law or approved by your HONOR.Can your Honor help us once more?Grateful for your understanding, God bless you and your undertakings.We shall be privileged if you find time to visit our orphanage the Home of Love andthe Spiritual Retreat Center in Antipolo City.To answer the query of Mr. Prioreschi, the Courts cannot grant to foundations like the GoodShepherd Foundation, Inc. the same exemption from payment of legal fees granted to indigent litigantseven if the foundations are working for indigent and underprivileged people.The basis for the exemption from legal and filing fees is the free access clause, embodied in Sec.11, Art. III of the 1987 Constitution, thus:Sec. 11. Free access to the courts and quasi judicial bodies and adequate legal assistanceshall not be denied to any person by reason of poverty.The importance of the right to free access to the courts and quasi judicial bodies and to adequatelegal assistance cannot be denied. A move to remove the provision on free access from the Constitution onthe ground that it was already covered by the equal protection clause was defeated by the desire to giveconstitutional stature to such specific protection of the poor. [1]In implementation of the right of free access under the Constitution, the Supreme Court promulgated rules,specifically, Sec. 21, Rule 3, Rules of Court,[2] and Sec. 19, Rule 141, Rules of Court,[3] which respectivelystate thus:Sec. 21. Indigent party. A party may be authorized to litigate his action, claim ordefense as an indigent if the court, upon an ex parte application and hearing, is satisfiedthat the party is one who has no money or property sufficient and available for food, shelterand basic necessities for himself and his family.Such authority shall include an exemption from payment of docket and other lawfulfees, and of transcripts of stenographic notes which the court may order to be furnishedhim. The amount of the docket and other lawful fees which the indigent was exempted frompaying shall be a lien on any judgment rendered in the case favorable to the indigent, unlessthe court otherwise provides.Any adverse party may contest the grant of such authority at any time beforejudgment is rendered by the trial court. If the court should determine after hearing that theparty declared as an indigent is in fact a person with sufficient income or property, theproper docket and other lawful fees shall be assessed and collected by the clerk of court. Ifpayment is not made within the time fixed by the court, execution shall issue for thepayment thereof, without prejudice to such other sanctions as the court may impose. (22a)Sec. 19. Indigent litigants exempt from payment of legal fees. Indigent litigants (a)whose gross income and that of their immediate family do not exceed an amount double themonthly minimum wage of an employee and (b) who do not own real property with a fairmarket value as stated in the current tax declaration of more than three hundred thousand(P300,000.00) pesos shall be exempt from payment of legal fees.The legal fees shall be a lien on any judgment rendered in the case favorable to theindigent litigant unless the court otherwise provides.To be entitled to the exemption herein provided, the litigant shall execute an affidavitthat he and his immediate family do not earn a gross income abovementioned, and they donot own any real property with the fair value aforementioned, supported by an affidavit of a
Any falsity in the affidavit of litigant or disinterested person shall be sufficient cause todismiss the complaint or action or to strike out the pleading of that party, without prejudiceto whatever criminal liability may have been incurred.The clear intent and precise language of the aforequoted provisions of the Rules of Court indicatethat only a natural party litigant may be regarded as an indigent litigant. The Good Shepherd Foundation,Inc., being a corporation invested by the State with a juridical personality separate and distinct from thatof its members,[4] is a juridical person. Among others, it has the power to acquire and possess property ofall kinds as well as incur obligations and bring civil or criminal actions, in conformity with the laws andregulations of their organization.[5] As a juridical person, therefore, it cannot be accorded the exemptionfrom legal and filing fees granted to indigent litigants.That the Good Shepherd Foundation, Inc. is working for indigent and underprivileged people is of nomoment. Clearly, the Constitution has explicitly premised the free access clause on a persons poverty, acondition that only a natural person can suffer.There are other reasons that warrant the rejection of the request for exemption in favor of ajuridical person. For one, extending the exemption to a juridical person on the ground that it works forindigent and underprivileged people may be prone to abuse (even with the imposition of rigiddocumentation requirements), particularly by corporations and entities bent on circumventing the rule onpayment of the fees. Also, the scrutiny of compliance with the documentation requirements may prove tootime-consuming and wasteful for the courts.IN VIEW OF THE FOREGOING, the Good Shepherd Foundation, Inc. cannot be extended the exemptionfrom legal and filing fees despite its working for indigent and underprivileged people.SO ORDERED.
BPI filed a complaint for sum of money against CCCC and the spouses before the Regional Trial Court ofButuan City (RTC Butuan), seeking to recover the deficiency of the loan of CCCC and the spouses with BPIButuan. The trial court ruled in favor of BPI. Pursuant to the decision, BPI instituted extrajudicial foreclosureof the spouses mortgaged property.14On 10 April 1985, the spouses filed an action for Injunction With Damages, With A Prayer For A RestrainingOrder and/ or Writ of Preliminary Injunction.15 The spouses claimed that the foreclosure of the real estatemortgages is illegal because BPI should have exhausted CCCCs properties first, stressing that they aremere guarantors of the renewed loans. They also prayed that they be awarded moral and exemplarydamages, attorneys fees, litigation expenses and cost of suit. Subsequently, the spouses filed anamended complaint,16 additionally alleging that CCCC had opened and maintained a foreign currencysavings account (FCSA-197) with bpi, Makati branch (BPI-Makati), and that said FCSA was used as securityfor a P450,000.00 loan also extended by BPI-Makati. TheP450,000.00 loan was allegedly paid, andthereafter the spouses demanded the return of the FCSA passbook. BPI rejected the demand; thus, thespouses were unable to withdraw from the said account to pay for their other obligations to BPI.The trial court dismissed the spouses complaint and ordered them to pay moral and exemplary damagesand attorneys fees to BPI.17 It ruled that since the spouses agreed to bind themselves jointly and severally,they are solidarily liable for the loans; hence, BPI can validly foreclose the two real estate mortgages.Moreover, being guarantors-mortgagors, the spouses are not entitled to the benefit of exhaustion. Anentthe FCSA, the trial court found that CCCC originally had FCDU SA No. 197 with BPI, Dewey Boulevardbranch, which was transferred to BPI-Makati as FCDU SA 76/0035, at the request of Desamparados Crystal.FCDU SA 76/0035 was thus closed, but Desamparados Crystal failed to surrender the passbook because itwas lost. The transferred FCSA in BPI-Makati was the one used as security for CCCCs P450,000.00 loanfrom BPI-Makati. CCCC was no longer allowed to withdraw from FCDU SA No. 197 because it was alreadyclosed.The spouses appealed the decision of the trial court to the Court of Appeals, but their appeal wasdismissed.18 The spouses moved for the reconsideration of the decision, but the Court of Appeals alsodenied their motion for reconsideration.19 Hence, the present petition.Before the Court, petitioners who are the heirs of the spouses argue that the failure of the spouses to paythe BPI-Cebu City loan of P120,000.00 was due to BPIs illegal refusal to accept payment for the loanunless the P300,000.00 loan from BPI-Butuan would also be paid. Consequently, in view of BPIs unjustrefusal to accept payment of the BPI-Cebu City loan, the loan obligation of the spouses was extinguished,petitioners contend.The contention has no merit. Petitioners rely on IBAAs offer to purchase the mortgaged lot from them andto directly pay BPI out of the proceeds thereof to settle the loan. 20 BPIs refusal to agree to such paymentscheme cannot extinguish the spouses loan obligation. In the first place, IBAA is not privy to the loanagreement or the promissory note between the spouses and BPI. Contracts, after all, take effect onlybetween the parties, their successors in interest, heirsand assigns.21 Besides, under Art. 1236 of the Civil Code, the creditor is not bound to accept payment orperformance by a third person who has no interest in the fulfillment of the obligation, unless there is astipulation to the contrary. We see no stipulation in the promissory note which states that a third personmay fulfill the spouses obligation. Thus, it is clear that the spouses alone bear responsibility for the same.In any event, the promissory note is the controlling repository of the obligation of the spouses. Under thepromissory note, the spouses defined the parameters of their obligation as follows:On or before June 29, 1980 on demand, for value received, I/we promise to pay, jointly andseverally, to the BANK OF THE PHILIPPINE ISLANDS, at its office in the city of Cebu Philippines, thesum of ONE HUNDRED TWENTY THOUSAND PESOS (P120,0000.00), Philippine Currency, subject toperiodic installments on the principal as follows: P30,000.00 quarterly amortization startingSeptember 28, 1979. x x x 22A solidary obligation is one in which each of the debtors is liable for the entire obligation, and each of thecreditors is entitled to demand the satisfaction of the whole obligation from any or all of the debtors. 23 A
liability is solidary "only when the obligation expressly so states, when the law so provides or when thenature of theobligation so requires."24 Thus, when the obligor undertakes to be "jointly and severally" liable, it meansthat the obligation is solidary,25 such as in this case. By stating "I/we promise to pay, jointly and severally,to the BANK OF THE PHILIPPINE ISLANDS," the spouses agreed to be sought out and be demandedpayment from, by BPI. BPI did demand payment from them, but they failed to comply with their obligation,prompting BPIs valid resort to the foreclosure of the chattel mortgage and the real estate mortgages.More importantly, the promissory note, wherein the spouses undertook to be solidarily liable for theprincipal loan, partakes the nature of a suretyship and therefore is an additional security for the loan. Thuswe held in one case that if solidary liability was instituted to "guarantee" a principal obligation, the lawdeems the contract to be one of suretyship.26 And while a contract of a surety is in essence secondary onlyto a valid principal obligation, the suretys liability to the creditor or promisee of the principal is said to bedirect, primary, and absolute; in other words, the surety is directly and equally bound with the principal.The surety therefore becomes liable for the debt or duty of another even if he possesses no direct orpersonal interest over the obligations nor does he receive any benefit therefrom. 27Petitioners contend that the Court of Appeals erred in not granting their counterclaims, considering thatthey suffered moral damages in view of the unjust refusal of BPI to accept the payment scheme proposedby IBAA and the allegedly unjust and illegal foreclosure of the real estate mortgages on theirproperty.28 Conversely, they argue that the Court of Appeals erred in awarding moral damages to BPI,which is a corporation, as well as exemplary damages, attorneys fees and expenses of litigation. 29We do not agree. Moral damages are meant to compensate the claimant for any physical suffering, mentalanguish, fright, serious anxiety, besmirched reputation, wounded feelings, moral shock, social humiliationand similar injuries unjustly caused.30 Such damages, to be recoverable, must be the proximate result of awrongful act or omission the factual basis for which is satisfactorily established by the aggrievedparty.31 There being no wrongful or unjust act on the part of BPI in demanding payment from them and inseeking the foreclosure of the chattel and real estate mortgages, there is no lawful basis for award ofdamages in favor of the spouses.Neither is BPI entitled to moral damages. A juridical person is generally not entitled to moral damagesbecause, unlike a natural person, it cannot experience physical suffering or such sentiments as woundedfeelings, serious anxiety, mental anguish or moral shock.32 The Court of Appeals found BPI as "beingfamous and having gained its familiarity and respect not only in the Philippines but also in the whole worldbecause of its good will and good reputation must protect and defend the same against any unwarrantedsuit such as the case at bench."33 In holding that BPI is entitled to moral damages, the Court of Appealsrelied on the case of People v. Manero,34 wherein the Court ruled that "[i]t is only when a juridical personhas a good reputation that is debased, resulting in social humiliation, that moral damages may beawarded."35We do not agree with the Court of Appeals. A statement similar to that made by the Court in Manerocan befound in the case of Mambulao Lumber Co. v. PNB, et al.,36 thus:x x x Obviously, an artificial person like herein appellant corporation cannot experience physicalsufferings, mental anguish, fright, serious anxiety, wounded feelings, moral shock or socialhumiliation which are basis of moral damages. A corporation may have good reputationwhich, if besmirched may also be a ground for the award of moral damages. x x x(Emphasis supplied)Nevertheless, in the more recent cases of ABS-CBN Corp. v. Court of Appeals, et al.,37 and FilipinasBroadcasting Network, Inc. v. Ago Medical and Educational Center-Bicol Christian College of Medicine(AMEC-BCCM),38 the Court held that the statements in Manero and Mambulao were mere obiter dicta,implying that the award of moral damages to corporations is not a hard and fast rule. Indeed, while theCourt may allow the grant of moral damages to corporations, it is not automatically granted; there muststill be proof of the existence of the factual basis of the damage and its causal relation to the defendantsacts. This is so because moral damages, though incapable of pecuniary estimation, are in the category ofan award designed to compensate the claimant for actual injurysuffered and not to impose a penalty onthe wrongdoer.39
The spouses complaint against BPI proved to be unfounded, but it does not automatically entitle BPI tomoral damages. Although the institution of a clearly unfounded civil suit can at times be a legaljustification for an award of attorney's fees, such filing, however, has almost invariably been held not to bea ground for an award of moral damages. The rationale for the rule is that the law could not have meant toimpose a penalty on the right to litigate. Otherwise, moral damages must every time be awarded in favorof the prevailing defendant against an unsuccessful plaintiff. 40 BPI may have been inconvenienced by thesuit, but we do not see how it could have possibly suffered besmirched reputation on account of the singlesuit alone. Hence, the award of moral damages should be deleted.The awards of exemplary damages and attorneys fees, however, are proper. Exemplary damages, on theother hand, are imposed by way of example or correction for the public good, when the party to a contractacts in a wanton, fraudulent, oppressive or malevolent manner, while attorneys fees are allowed whenexemplary damages are awarded and when the party to a suit is compelled to incur expenses to protecthis interest.41 The spouses instituted their complaint against BPI notwithstanding the fact that they werethe ones who failed to pay their obligations. Consequently, BPI was forced to litigate and defend itsinterest. For these reasons, BPI is entitled to the awards of exemplary damages and attorneys fees.WHEREFORE, the petition is DENIED. The Decision and Resolution of the Court of Appeals dated 24 October2005 and 31 March 2006, respectively, are hereby AFFIRMED, with the MODIFICATION that the award ofmoral damages to Bank of the Philippine Islands is DELETED.Costs against the petitioners.SO ORDERED.
to stop the flow of support of foreign foundations who assist the medical school on the basis of the latterspurpose. But if the purpose of the institution (AMEC) is to deceive students at cross purpose with its reasonfor being it is possible for these foreign foundations to lift or suspend their donations temporarily. [8]xxxOn the other hand, the administrators of AMEC-BCCM, AMEC Science High School and theAMEC-Institute of Mass Communication in their effort to minimize expenses in terms of salaryare absorbing or continues to accept rejects. For example how many teachers in AMEC are formerteachers of Aquinas University but were removed because of immorality? Does it mean that the presentadministration of AMEC have the total definite moral foundation from catholic administrator of AquinasUniversity. I will prove to you my friends, that AMEC is a dumping ground, garbage, not merely ofmoral and physical misfits. Probably they only qualify in terms of intellect. The Dean of Student Affairsof AMEC is Justita Lola, as the family name implies. She is too old to work, being an old woman. Is theAMEC administration exploiting the very [e]nterprising or compromising and undemanding Lola? Could itbe that AMEC is just patiently making use of Dean Justita Lola were if she is very old. As in atmosphericsituation zero visibility the plane cannot land, meaning she is very old, low pay follows. By the way, DeanJustita Lola is also the chairman of the committee on scholarship in AMEC. She had retired from BicolUniversity a long time ago but AMEC has patiently made use of her.xxxMEL RIMA:xxx My friends based on the expose, AMEC is a dumping ground for moral and physically misfit people.What does this mean? Immoral and physically misfits as teachers.May I say Im sorry to Dean Justita Lola. But this is the truth. The truth is this, that your are no longer fit toteach. You are too old. As an aviation, your case is zero visibility. Dont insist.xxx Why did AMEC still absorb her as a teacher, a dean, and chairman of the scholarship committee atthat. The reason is practical cost saving in salaries, because an old person is not fastidious, so long as shehas money to buy the ingredient of beetle juice. The elderly can get by thats why she (Lola) was taken inas Dean.xxxxxx On our end our task is to attend to the interests of students. It is likely that the students would beinfluenced by evil. When they become members of society outside of campus will be liabilitiesrather than assets. What do you expect from a doctor who while studying at AMEC is so much burdenedwith unreasonable imposition? What do you expect from a student who aside from peculiar problemsbecause not all students are rich in their struggle to improve their social status are even more burdenedwith false regulations. xxx[9] (Emphasis supplied)The complaint further alleged that AMEC is a reputable learning institution. With the supposed exposs,FBNI, Rima and Alegre transmitted malicious imputations, and as such, destroyed plaintiffs (AMEC andAgo) reputation. AMEC and Ago included FBNI as defendant for allegedly failing to exercise due diligence inthe selection and supervision of its employees, particularly Rima and Alegre.On 18 June 1990, FBNI, Rima and Alegre, through Atty. Rozil Lozares, filed an Answer [10] alleging thatthe broadcasts against AMEC were fair and true. FBNI, Rima and Alegre claimed that they were plainlyimpelled by a sense of public duty to report the goings-on in AMEC, [which is] an institution imbued withpublic interest.Thereafter, trial ensued. During the presentation of the evidence for the defense, Atty. Edmundo Cea,collaborating counsel of Atty. Lozares, filed a Motion to Dismiss [11] on FBNIs behalf. The trial court deniedthe motion to dismiss. Consequently, FBNI filed a separate Answer claiming that it exercised due diligencein the selection and supervision of Rima and Alegre. FBNI claimed that before hiring a broadcaster, thebroadcaster should (1) file an application; (2) be interviewed; and (3) undergo an apprenticeship andtraining program after passing the interview. FBNI likewise claimed that it always reminds its broadcasters
to observe truth, fairness and objectivity in their broadcasts and to refrain from using libelous and indecentlanguage. Moreover, FBNI requires all broadcasters to pass the Kapisanan ng mga Brodkaster saPilipinas (KBP) accreditation test and to secure a KBP permit.On 14 December 1992, the trial court rendered a Decision [12] finding FBNI and Alegre liable for libelexcept Rima. The trial court held that the broadcasts are libelous per se. The trial court rejected thebroadcasters claim that their utterances were the result of straight reporting because it had no factualbasis. The broadcasters did not even verify their reports before airing them to show good faith. In holdingFBNI liable for libel, the trial court found that FBNI failed to exercise diligence in the selection andsupervision of its employees.In absolving Rima from the charge, the trial court ruled that Rimas only participation was when heagreed with Alegres expos. The trial court found Rimas statement within the bounds of freedom of speech,expression, and of the press. The dispositive portion of the decision reads:WHEREFORE, premises considered, this court finds for the plaintiff. Considering the degree ofdamages caused by the controversial utterances, which are not found by this court to be reallyvery serious and damaging, and there being no showing that indeed the enrollment of plaintiffschool dropped, defendants Hermogenes Jun Alegre, Jr. and Filipinas Broadcasting Network (owner of theradio station DZRC), are hereby jointly and severally ordered to pay plaintiff Ago Medical and EducationalCenter-Bicol Christian College of Medicine (AMEC-BCCM) the amount of P300,000.00 moral damages,plus P30,000.00 reimbursement of attorneys fees, and to pay the costs of suit.SO ORDERED. [13] (Emphasis supplied)Both parties, namely, FBNI, Rima and Alegre, on one hand, and AMEC and Ago, on the other, appealedthe decision to the Court of Appeals. The Court of Appeals affirmed the trial courts judgment withmodification. The appellate court made Rima solidarily liable with FBNI and Alegre. The appellate courtdenied Agos claim for damages and attorneys fees because the broadcasts were directed against AMEC,and not against her. The dispositive portion of the Court of Appeals decision reads:WHEREFORE, the decision appealed from is hereby AFFIRMED, subject to the modification thatbroadcaster Mel Rima is SOLIDARILY ADJUDGED liable with FBN[I] and Hermo[g]enes Alegre.SO ORDERED.[14]FBNI, Rima and Alegre filed a motion for reconsideration which the Court of Appeals denied in its 26January 2000 Resolution.Hence, FBNI filed this petition.[15]The Ruling of the Court of AppealsThe Court of Appeals upheld the trial courts ruling that the questioned broadcasts are libelous perse and that FBNI, Rima and Alegre failed to overcome the legal presumption of malice. The Court ofAppeals found Rima and Alegres claim that they were actuated by their moral and social duty to inform thepublic of the students gripes as insufficient to justify the utterance of the defamatory remarks.Finding no factual basis for the imputations against AMECs administrators, the Court of Appeals ruledthat the broadcasts were made with reckless disregard as to whether they were true or false. The appellatecourt pointed out that FBNI, Rima and Alegre failed to present in court any of the students who allegedlycomplained against AMEC. Rima and Alegre merely gave a single name when asked to identify thestudents. According to the Court of Appeals, these circumstances cast doubt on the veracity of thebroadcasters claim that they were impelled by their moral and social duty to inform the public about thestudents gripes.The Court of Appeals found Rima also liable for libel since he remarked that (1) AMEC-BCCM is adumping ground for morally and physically misfit teachers; (2) AMEC obtained the services of Dean JustitaLola to minimize expenses on its employees salaries; and (3) AMEC burdened the students withunreasonable imposition and false regulations.[16]
The Court of Appeals held that FBNI failed to exercise due diligence in the selection and supervision ofits employees for allowing Rima and Alegre to make the radio broadcasts without the proper KBPaccreditation. The Court of Appeals denied Agos claim for damages and attorneys fees because thelibelous remarks were directed against AMEC, and not against her. The Court of Appeals adjudged FBNI,Rima and Alegre solidarily liable to pay AMEC moral damages, attorneys fees and costs of suit.IssuesFBNI raises the following issues for resolution:I. WHETHER THE BROADCASTS ARE LIBELOUS;II. WHETHER AMEC IS ENTITLED TO MORAL DAMAGES;III. WHETHER THE AWARD OF ATTORNEYS FEES IS PROPER; andIV. WHETHER FBNI IS SOLIDARILY LIABLE WITH RIMA AND ALEGRE FOR PAYMENT OF MORAL DAMAGES,ATTORNEYS FEES AND COSTS OF SUIT.The Courts RulingWe deny the petition.This is a civil action for damages as a result of the allegedly defamatory remarks of Rima and Alegreagainst AMEC.[17] While AMEC did not point out clearly the legal basis for its complaint, a reading of thecomplaint reveals that AMECs cause of action is based on Articles 30 and 33 of the Civil Code. Article30[18] authorizes a separate civil action to recover civil liability arising from a criminal offense. On the otherhand, Article 33[19] particularly provides that the injured party may bring a separate civil action fordamages in cases of defamation, fraud, and physical injuries. AMEC also invokes Article 19 [20] of the CivilCode to justify its claim for damages. AMEC cites Articles 2176 [21] and 2180[22] of the Civil Code to hold FBNIsolidarily liable with Rima and Alegre.I.Whether the broadcasts are libelousA libel[23] is a public and malicious imputation of a crime, or of a vice or defect, real or imaginary, orany act or omission, condition, status, or circumstance tending to cause the dishonor, discredit, orcontempt of a natural or juridical person, or to blacken the memory of one who is dead. [24]There is no question that the broadcasts were made public and imputed to AMEC defects orcircumstances tending to cause it dishonor, discredit and contempt. Rima and Alegres remarks such asgreed for money on the part of AMECs administrators; AMEC is a dumping ground, garbage of xxx moraland physical misfits; and AMEC students who graduate will be liabilities rather than assets of the societyare libelous per se. Taken as a whole, the broadcasts suggest that AMEC is a money-making institutionwhere physically and morally unfit teachers abound.However, FBNI contends that the broadcasts are not malicious. FBNI claims that Rima and Alegre wereplainly impelled by their civic duty to air the students gripes. FBNI alleges that there is no evidence that illwill or spite motivated Rima and Alegre in making the broadcasts. FBNI further points out that Rima andAlegre exerted efforts to obtain AMECs side and gave Ago the opportunity to defend AMEC and itsadministrators. FBNI concludes that since there is no malice, there is no libel.FBNIs contentions are untenable.Every defamatory imputation is presumed malicious. [25] Rima and Alegre failed to show adequatelytheir good intention and justifiable motive in airing the supposed gripes of the students. As hosts of adocumentary or public affairs program, Rima and Alegre should have presented the public issues freefrom inaccurate and misleading information.[26] Hearing the students alleged complaints a month beforethe expos,[27] they had sufficient time to verify their sources and information. However, Rima and Alegrehardly made a thorough investigation of the students alleged gripes. Neither did they inquire about norconfirm the purported irregularities in AMEC from the Department of Education, Culture and Sports. Alegretestified that he merely went to AMEC to verify his report from an alleged AMEC official who refused todisclose any information. Alegre simply relied on the words of the students because they were many and
not because there is proof that what they are saying is true. [28] This plainly shows Rima and Alegresreckless disregard of whether their report was true or not.Contrary to FBNIs claim, the broadcasts were not the result of straight reporting. Significantly, somecourts in the United States apply the privilege of neutral reportage in libel cases involving matters of publicinterest or public figures. Under this privilege, a republisher who accurately and disinterestedly reportscertain defamatory statements made against public figures is shielded from liability, regardless of therepublishers subjective awareness of the truth or falsity of the accusation. [29] Rima and Alegre cannotinvoke the privilege of neutral reportage because unfounded comments abound in the broadcasts.Moreover, there is no existing controversy involving AMEC when the broadcasts were made. The privilegeof neutral reportage applies where the defamed person is a public figure who is involved in an existingcontroversy, and a party to that controversy makes the defamatory statement. [30]However, FBNI argues vigorously that malice in law does not apply to this case. Citing Borjal v. Courtof Appeals,[31] FBNI contends that the broadcasts fall within the coverage of qualifiedly privilegedcommunications for being commentaries on matters of public interest. Such being the case, AMEC shouldprove malice in fact or actual malice. Since AMEC allegedly failed to prove actual malice, there is no libel.FBNIs reliance on Borjal is misplaced. In Borjal, the Court elucidated on the doctrine of fair comment,thus:[F]air commentaries on matters of public interest are privileged and constitute a valid defense in an actionfor libel or slander. The doctrine of fair comment means that while in general every discreditableimputation publicly made is deemed false, because every man is presumed innocent until his guilt isjudicially proved, and every false imputation is deemed malicious, nevertheless, when the discreditableimputation is directed against a public person in his public capacity, it is not necessarily actionable. Inorder that such discreditable imputation to a public official may be actionable, it must eitherbe a false allegation of fact or a comment based on a false supposition. If the comment is anexpression of opinion, based on established facts, then it is immaterial that the opinion happens tobe mistaken, as long as it might reasonably be inferred from the facts. [32] (Emphasis supplied)True, AMEC is a private learning institution whose business of educating students is genuinely imbuedwith public interest. The welfare of the youth in general and AMECs students in particular is a matter whichthe public has the right to know. Thus, similar to the newspaper articles in Borjal, the subject broadcastsdealt with matters of public interest. However, unlike in Borjal, the questioned broadcasts are not basedon established facts. The record supports the following findings of the trial court:xxx Although defendants claim that they were motivated by consistent reports of students and parentsagainst plaintiff, yet, defendants have not presented in court, nor even gave name of a single student whomade the complaint to them, much less present written complaint or petition to that effect. To accept thisdefense of defendants is too dangerous because it could easily give license to the media to malign peopleand establishments based on flimsy excuses that there were reports to them although they could notsatisfactorily establish it. Such laxity would encourage careless and irresponsible broadcasting which isinimical to public interests.Secondly, there is reason to believe that defendant radio broadcasters, contrary to the mandates of theirduties, did not verify and analyze the truth of the reports before they aired it, in order to prove that theyare in good faith.Alegre contended that plaintiff school had no permit and is not accredited to offer Physical Therapycourses. Yet, plaintiff produced a certificate coming from DECS that as of Sept. 22, 1987 or more than 2years before the controversial broadcast, accreditation to offer Physical Therapy course had already beengiven the plaintiff, which certificate is signed by no less than the Secretary of Education and Cultureherself, Lourdes R. Quisumbing (Exh. C-rebuttal). Defendants could have easily known this were theycareful enough to verify. And yet, defendants were very categorical and sounded too positive when theymade the erroneous report that plaintiff had no permit to offer Physical Therapy courses which they wereoffering.The allegation that plaintiff was getting tremendous aids from foreign foundations like McdonaldFoundation prove not to be true also. The truth is there is no Mcdonald Foundation existing. Although a bigbuilding of plaintiff school was given the name Mcdonald building, that was only in order to honor the first
missionary in Bicol of plaintiffs religion, as explained by Dr. Lita Ago. Contrary to the claim of defendantsover the air, not a single centavo appears to be received by plaintiff school from the aforementionedMcDonald Foundation which does not exist.Defendants did not even also bother to prove their claim, though denied by Dra. Ago, that when medicalstudents fail in one subject, they are made to repeat all the other subject[s], even those they have alreadypassed, nor their claim that the school charges laboratory fees even if there are no laboratories in theschool. No evidence was presented to prove the bases for these claims, at least in order to give semblanceof good faith.As for the allegation that plaintiff is the dumping ground for misfits, and immoral teachers, defendant[s]singled out Dean Justita Lola who is said to be so old, with zero visibility already. Dean Lola testified incourt last Jan. 21, 1991, and was found to be 75 years old. xxx Even older people prove to be effectiveteachers like Supreme Court Justices who are still very much in demand as law professors in their lateyears. Counsel for defendants is past 75 but is found by this court to be still very sharp and effective. So isplaintiffs counsel.Dr. Lola was observed by this court not to be physically decrepit yet, nor mentally infirmed, but is still alertand docile.The contention that plaintiffs graduates become liabilities rather than assets of our society is a mereconclusion. Being from the place himself, this court is aware that majority of the medical graduates ofplaintiffs pass the board examination easily and become prosperous and responsible professionals. [33]Had the comments been an expression of opinion based on established facts, it is immaterial that theopinion happens to be mistaken, as long as it might reasonably be inferred from the facts. [34] However, thecomments of Rima and Alegre were not backed up by facts. Therefore, the broadcasts are not privilegedand remain libelous per se.The broadcasts also violate the Radio Code [35] of the Kapisanan ng mga Brodkaster sa Pilipinas,Ink. (Radio Code). Item I(B) of the Radio Code provides:B. PUBLIC AFFAIRS, PUBLIC ISSUES AND COMMENTARIES1. x x x4. Public affairs program shall present public issues free from personal bias, prejudiceand inaccurate and misleading information. x x x Furthermore, the station shall strive topresent balanced discussion of issues. x x x.xxx7. The station shall be responsible at all times in the supervision of public affairs, public issues andcommentary programs so that they conform to the provisions and standards of this code.8. It shall be the responsibility of the newscaster, commentator, host and announcer to protectpublic interest, general welfare and good order in the presentation of public affairs and publicissues.[36](Emphasis supplied)The broadcasts fail to meet the standards prescribed in the Radio Code, which lays down the code ofethical conduct governing practitioners in the radio broadcast industry. The Radio Code is a voluntary codeof conduct imposed by the radio broadcast industry on its own members. The Radio Code is a publicwarranty by the radio broadcast industry that radio broadcast practitioners are subject to a code by whichtheir conduct are measured for lapses, liability and sanctions.The public has a right to expect and demand that radio broadcast practitioners live up to the code ofconduct of their profession, just like other professionals. A professional code of conduct provides thestandards for determining whether a person has acted justly, honestly and with good faith in the exerciseof his rights and performance of his duties as required by Article 19 [37] of the Civil Code. A professionalcode of conduct also provides the standards for determining whether a person who willfully causes loss or
injury to another has acted in a manner contrary to morals or good customs under Article 21 [38] of the CivilCode.II.Whether AMEC is entitled to moral damagesFBNI contends that AMEC is not entitled to moral damages because it is a corporation. [39]A juridical person is generally not entitled to moral damages because, unlike a natural person, itcannot experience physical suffering or such sentiments as wounded feelings, serious anxiety, mentalanguish or moral shock.[40] The Court of Appeals cites Mambulao Lumber Co. v. PNB, et al.[41] to justifythe award of moral damages. However, the Courts statement in Mambulao that a corporation may have agood reputation which, if besmirched, may also be a ground for the award of moral damages is an obiterdictum.[42]Nevertheless, AMECs claim for moral damages falls under item 7 of Article 2219 [43] of the Civil Code.This provision expressly authorizes the recovery of moral damages in cases of libel, slander or any otherform of defamation. Article 2219(7) does not qualify whether the plaintiff is a natural or juridical person.Therefore, a juridical person such as a corporation can validly complain for libel or any other form ofdefamation and claim for moral damages.[44]Moreover, where the broadcast is libelous per se, the law implies damages.[45] In such a case, evidenceof an honest mistake or the want of character or reputation of the party libeled goes only in mitigation ofdamages.[46] Neither in such a case is the plaintiff required to introduce evidence of actual damages as acondition precedent to the recovery of some damages. [47] In this case, the broadcasts are libelous per se.Thus, AMEC is entitled to moral damages.However, we find the award of P300,000 moral damages unreasonable. The record shows that eventhough the broadcasts were libelous per se, AMEC has not suffered any substantial or material damage toits reputation. Therefore, we reduce the award of moral damages from P300,000 to P150,000.
III.Whether the award of attorneys fees is properFBNI contends that since AMEC is not entitled to moral damages, there is no basis for the award ofattorneys fees. FBNI adds that the instant case does not fall under the enumeration in Article 2208 [48] ofthe Civil Code.The award of attorneys fees is not proper because AMEC failed to justify satisfactorily its claim forattorneys fees. AMEC did not adduce evidence to warrant the award of attorneys fees. Moreover, both thetrial and appellate courts failed to explicitly state in their respective decisions the rationale for the awardof attorneys fees.[49] In Inter-Asia Investment Industries, Inc. v. Court of Appeals,[50] we held that:[I]t is an accepted doctrine that the award thereof as an item of damages is the exception rather than therule, and counsels fees are not to be awarded every time a party wins a suit. The power of the court toaward attorneys fees under Article 2208 of the Civil Code demands factual, legal and equitablejustification, without which the award is a conclusion without a premise, its basis beingimproperly left to speculation and conjecture. In all events, the court must explicitly state in the textof the decision, and not only in the decretal portion thereof, the legal reason for the award of attorneysfees.[51] (Emphasis supplied)While it mentioned about the award of attorneys fees by stating that it lies within the discretion of thecourt and depends upon the circumstances of each case, the Court of Appeals failed to point out anycircumstance to justify the award.IV.Whether FBNI is solidarily liable with Rima and Alegrefor moral damages, attorneys feesand costs of suit
FBNI contends that it is not solidarily liable with Rima and Alegre for the payment of damages andattorneys fees because it exercised due diligence in the selection and supervision of its employees,particularly Rima and Alegre. FBNI maintains that its broadcasters, including Rima and Alegre, undergo avery regimented process before they are allowed to go on air. Those who apply for broadcaster aresubjected to interviews, examinations and an apprenticeship program.FBNI further argues that Alegres age and lack of training are irrelevant to his competence as abroadcaster. FBNI points out that the minor deficiencies in the KBP accreditation of Rima and Alegre do notin any way prove that FBNI did not exercise the diligence of a good father of a family in selecting andsupervising them. Rimas accreditation lapsed due to his non-payment of the KBP annual fees while Alegresaccreditation card was delayed allegedly for reasons attributable to the KBP Manila Office. FBNI claims thatmembership in the KBP is merely voluntary and not required by any law or government regulation.FBNIs arguments do not persuade us.The basis of the present action is a tort. Joint tort feasors are jointly and severally liable for the tortwhich they commit.[52] Joint tort feasors are all the persons who command, instigate, promote, encourage,advise, countenance, cooperate in, aid or abet the commission of a tort, or who approve of it after it isdone, if done for their benefit.[53] Thus, AMEC correctly anchored its cause of action against FBNI on Articles2176 and 2180 of the Civil Code.As operator of DZRC-AM and employer of Rima and Alegre, FBNI is solidarily liable to pay for damagesarising from the libelous broadcasts. As stated by the Court of Appeals, recovery for defamatorystatements published by radio or television may be had from the owner of the station, alicensee, the operator of the station, or a person who procures, or participates in, the making of thedefamatory statements.[54] An employer and employee are solidarily liable for a defamatory statement bythe employee within the course and scope of his or her employment, at least when the employerauthorizes or ratifies the defamation.[55] In this case, Rima and Alegre were clearly performing their officialduties as hosts of FBNIs radio program Expos when they aired the broadcasts. FBNI neither alleged norproved that Rima and Alegre went beyond the scope of their work at that time. There was likewise noshowing that FBNI did not authorize and ratify the defamatory broadcasts.Moreover, there is insufficient evidence on record that FBNI exercised due diligence inthe selection and supervision of its employees, particularly Rima and Alegre. FBNI merely showed thatit exercised diligence in the selection of its broadcasters without introducing any evidence to prove that itobserved the same diligence in the supervision of Rima and Alegre. FBNI did not show how it exerciseddiligence in supervising its broadcasters. FBNIs alleged constant reminder to its broadcasters to observetruth, fairness and objectivity and to refrain from using libelous and indecent language is not enough toprove due diligence in the supervision of its broadcasters. Adequate training of the broadcasters on theindustrys code of conduct, sufficient information on libel laws, and continuous evaluation of thebroadcasters performance are but a few of the many ways of showing diligence in the supervision ofbroadcasters.FBNI claims that it has taken all the precaution in the selection of Rima and Alegre as broadcasters,bearing in mind their qualifications. However, no clear and convincing evidence shows that Rima andAlegre underwent FBNIs regimented process of application. Furthermore, FBNI admits that Rima and Alegrehad deficiencies in their KBP accreditation, [56] which is one of FBNIs requirements before it hires abroadcaster. Significantly, membership in the KBP, while voluntary, indicates the broadcasters strongcommitment to observe the broadcast industrys rules and regulations. Clearly, these circumstances showFBNIs lack of diligence in selecting and supervising Rima and Alegre. Hence, FBNI is solidarily liable to paydamages together with Rima and Alegre.WHEREFORE, we DENY the instant petition. We AFFIRM the Decision of 4 January 1999 and Resolutionof 26 January 2000 of the Court of Appeals in CA-G.R. CV No. 40151 with the MODIFICATION that the awardof moral damages is reduced from P300,000 to P150,000 and the award of attorneys fees is deleted. Costsagainst petitioner.
6. lady Commando7. Batang Matadero8. RebelyonI hope you will consider this request of mine.The other dramatic films have been offered to us before and have been rejected because of the ruling ofMTRCB to have them aired at 9:00 p.m. due to their very adult themes.As for the 10 titles I have choosen [sic] from the 3 packages please consider including all the other Vivamovies produced last year, I have quite an attractive offer to make.Thanking you and with my warmest regards.(Signed)Charo Santos-ConcioOn February 27, 1992, defendant Del Rosario approached ABS-CBNs Ms. Concio, with a list consisting of 52original movie titles (i.e., not yet aired on television) including the 14 titles subject of the present case, aswell as 104 re-runs (previously aired on television) from which ABS-CBN may choose another 52 titles, as atotal of 156 titles, proposing to sell to ABS-CBN airing rights over this package of 52 originals and 52 reruns for P60,000,000.00 of which P30,000,000.00 will be in cash and P30,000,000.00 worth of televisionspots (Exh. 4 to 4-C Viva; 9 Viva).On April 2, 1992, defendant Del Rosario and ABS-CBNs general manager, Eugenio Lopez III, met at theTamarind Grill Restaurant in Quezon City to discuss the package proposal of VIVA. What transpired in thatlunch meeting is the subject of conflicting versions. Mr. Lopez testified that he and Mr. Del Rosarioallegedly agreed that ABS-CBN was granted exclusive film rights to fourteen (14) films for a totalconsideration ofP36 million; that he allegedly put this agreement as to the price and number of films in anapkin and signed it and gave it to Mr. Del Rosario (Exh. D; TSN, pp. 24-26, 77-78, June 8, 1992). On theother hand. Del Rosario denied having made any agreement with Lopez regarding the 14 Viva films; deniedthe existence of a napkin in which Lopez wrote something; and insisted that what he and Lopez discussedat the lunch meeting was Vivas film package offer of 104 films (52 originals and 52 re-runs) for a total priceof P60 million. Mr. Lopez promising [sic]to make a counter proposal which came in the form of a proposalcontract Annex C of the complaint (Exh. 1 Viva; Exh C ABS-CBN).On April 06, 1992, Del Rosario and Mr. Graciano Gozon of RBS Senior vice-president for Finance discussedthe terms and conditions of Vivas offer to sell the 104 films, after the rejection of the same package byABS-CBN.On April 07, 1992, defendant Del Rosario received through his secretary , a handwritten note from Ms.Concio, (Exh. 5 Viva), which reads: Heres the draft of the contract. I hope you find everything in order, towhich was attached a draft exhibition agreement (Exh. C ABS-CBN; Exh. 9 Viva p. 3) a counter-proposalcovering 53 films, 52 of which came from the list sent by defendant Del Rosario and one film was added byMs. Concio, for a consideration of P35 million. Exhibit C provides that ABS-CBN is granted film rights to 53films and contains a right of first refusal to 1992 Viva Films. The said counter proposal was howeverrejected by Vivas Board of Directors [in the] evening of the same day, April 7, 1992, as Viva would not sellanything less than the package of 104 films for P60 million pesos (Exh. 9 Viva), and such rejection wasrelayed to Ms. Concio.On April 29, 1992, after the rejection of ABS-CBN and following several negotiations and meetingsdefendant Del Rosario and Vivas President Teresita Cruz, in consideration of P60 million, signed a letter ofagreement dated April 24, 1992, granting RBS the exclusive right to air 104 Viva-produced and/or acquiredfilms (Exh. 7-A - RBS; Exh. 4 RBS) including the fourteen (14) films subject of the present case. [4]On 27 May 1992, ABS-CBN filed before the RTC a complaint for specific performance with a prayer for awrit of preliminary injunction and/or temporary restraining order against private respondents RepublicBroadcasting Corporation[5] (hereafter RBS), Viva Production (hereafter VIVA), and Vicente del Rosario. Thecomplaint was docketed as Civil Case No. Q-92-12309.
On 28 May 1992, the RTC issued a temporary restraining order [6] enjoining private respondents fromproceeding with the airing, broadcasting, and televising of the fourteen VIVA films subject of thecontroversy, starting with the film Maging Sino Ka Man, which was scheduled to be shown on privaterespondent RBS channel 7 at seven oclock in the evening of said date.On 17 June 1992, after appropriate proceedings, the RTC issued an order [7] directing the issuance of awrit of preliminary injunction upon ABS-CBNs posting of a P35 million bond. ABS-CBN moved for thereduction of the bond,[8] while private respondents moved for reconsideration of the order and offered toput up a counterbond.[9]In the meantime, private respondents filed separate answer with counterclaim. [10] RBS also set up across-claim against VIVA.On 3 August 1992, the RTC issued an order [11] dissolving the writ of preliminary injunction upon theposting by RBS of a P30 million counterbond to answer for whatever damages ABS-CBN might suffer byvirtue of such dissolution. However, it reduced petitioners injunction bond to P15 million as a conditionprecedent for the reinstatement of the writ of preliminary injunction should private respondents be unableto post a counterbond.At the pre-trial[12] on 6 August 1992, the parties upon suggestion of the court, agreed to explore thepossibility of an amicable settlement. In the meantime, RBS prayed for and was granted reasonable timewithin which to put up a P30 million counterbond in the event that no settlement would be reached.As the parties failed to enter into an amicable settlement, RBS posted on 1 October 1992 acounterbond, which the RTC approved in its Order of 15 October 1992. [13]On 19 October 1992, ABS-CBN filed a motion for reconsideration [14] of the 3 August and 15 October1992 Orders, which RBS opposed.[15]On 29 October, the RTC conducted a pre-trial.[16]Pending resolution of its motion for reconsideration, ABS-CBN filed with the Court of Appeals apetition[17] challenging the RTCs Order of 3 August and 15 October 1992 and praying for the issuance of awrit of preliminary injunction to enjoin the RTC from enforcing said orders. The case was docketed as C CAG.R. SP No. 29300 for being premature. ABS-CBN challenged the dismissal in a petition for review filed withthis Court on 19 January 1993, which was docketed s G.R. No. 108363.In the meantime the RTC received the evidence for the parties in Civil Case No. Q-9212309. Thereafter, on 28 April 1993, it rendered a decision [20] in favor of RBS and VIVA and against ABSCBN disposingas follows:WHEREFORE, under cool reflection and prescinding from the foregoing, judgment is rendered in favor ofdefendants and against the plaintiff.(1) The complaint is hereby dismissed;(2) Plaintiff ABS-CBN is ordered to pay defendant RBS the following:a) P107,727.00 the amount of premium paid by RBS to the surety which issued defendantsRBSs bond to lift the injunction;b) P191,843.00 for the amount of print advertisement for Maging Sino Ka Man in variousnewspapers;c) Attorneys fees in the amount of P1 million;d) P5 million as and by way of moral damages;e) P5 million as and by way of exemplary damages;(3) For the defendant VIVA, plaintiff ABS-CBN is ordered to pay P212,000.00 by way of reasonableattorneys fees.
reputation was debased by the filing of the complaint in Civil Case No. Q-92-12309 and by the non-showingof the film Maging Sino Ka Man. Respondent court also held that exemplary damages were correctlyimposed by way of example or correction for the public good in view of the filing of the complaint despitepetitioners knowledge that the contract with VIVA had not been perfected. It also upheld the award ofattorneys fees, reasoning that with ABS-CBNs act of instituting Civil Case No. Q-92-12309, RBS wasunnecessarily forced to litigate. The appellate court, however, reduced the awards of moral damagesto P 2 million, exemplary damages to P2 million, and attorneys fees to P500,000.00.On the other hand, respondent Court of Appeals denied VIVA and Del Rosarios appeal because it wasRBS and not VIVA which was actually prejudiced when the complaint was filed by ABS-CBN.Its motion for reconsideration having been denied, ABS-CBN filed the petition in this case, contendingthat the Court of Appeals gravely erred inIRULING THAT THERE WAS NO PERFECTED CONTRACT BETWEEN PETITIONER AND PRIVATERESPONDENT VIVA NOTWITHSTANDING PREPONFERANCE OF EVIDENCE ADDUCED BYPETITIONER TO THE CONTRARY.IIIN AWARDING ACTUAL AND COMPENSATORY DAMAGES IN FAVOR OF PRIVATE RESPONDENTRBS.IIIIN AWARDING MORAL AND EXEMPLARY DAMAGES IN FAVOR OF PRIVATE RESPONDENT RBS.IVIN AWARDING ATORNEYS FEES OF RBS.ABS-CBN claims that it had yet to fully exercise its right of first refusal over twenty-four titles under the1990 Film Exhibition Agreement, as it had chosen only ten titles from the first list. It insists that we givecredence to Lopezs testimony that he and Del Rosario met at the Tamarind Grill Restaurant, discussed theterms and conditions of the second list (the 1992 Film Exhibition Agreement) and upon agreement thereon,wrote the same on a paper napkin. It also asserts that the contract has already been effective, as theelements thereof, namely, consent, object, and consideration were established. It then concludes that theCourt of Appeals pronouncements were not supported by law and jurisprudence, as per our decision of 1December 1995 in Limketkai Sons Milling, Inc. v. Court of Appeals, [23] which cited Toyota Shaw, Inc. v. Courtofpremium on the counterbond of its own volition in order to negate the injunction issued by the trial courtafter the parties had ventilated their respective positions during the hearings for the purpose. The filing ofthe counterbond was an option available to RBS, but it can hardly be argued that ABS-CBN compelled RBSto incur such expense. Besides, RBS had another available option, i.e., move for the dissolution of theinjunction; or if it was determined to put up a counterbond, it could have presented a cashbond. Furthermore under Article 2203 of the Civil Code, the party suffering loss injury is also required toexercise the diligence of a good father of a family to minimize the damages resulting from the act oromission. As regards the cost of print advertisements, RBS had not convincingly established that this was aloss attributable to the non-showing of Maging Sino Ka Man; on the contrary, it was brought out during trialthat with or without the case or injunction, RBS would have spent such an amount to generate interest inthe film.ABS-CBN further contends that there was no other clear basis for the awards of moral and exemplarydamages. The controversy involving ABS-CBN and RBS did not in any way originate from businesstransaction between them. The claims for such damages did not arise from any contractual dealings orfrom specific acts committed by ABS-CBN against RBS that may be characterized as wanton, fraudulent, orreckless; they arose by virtue only of the filing of the complaint. An award of moral and exemplarydamages is not warranted where the record is bereft of any proof that a party acted maliciously or in badfaith in filing an action.[27] In any case, free resort to courts for redress of wrongs is a matter of publicpolicy. The law recognizes the right of every one to sue for that which he honestly believes to be his rightwithout fear of standing trial for damages where by lack of sufficient evidence, legal technicalities, or adifferent interpretation of the laws on the matter, the case would lose ground. [28] One who, makes use of
his own legal right does no injury. [29] If damage results from filing of the complaint, it is damnum absqueinjuria.[30] Besides, moral damages are generally not awarded in favor of a juridical person, unless it enjoysa good reputation that was debased by the offending party resulting in social humiliation. [31]As regards the award of attorneys fees, ABS-CBN maintains that the same had no factual, legal, orequitable justification. In sustaining the trial courts award, the Court of Appeals acted in clear disregard ofthe doctrine laid down in Buan v. Camaganacan[32] that the text of the decision should state the reason whyattorneys fees are being awarded; otherwise, the award should be disallowed. Besides, no bad faith hasbeen imputed on, much less proved as having been committed by, ABS-CBN. It has been held that whereno sufficient showing of bad faith would be reflected in a partys persistence in a case other than anerroneous conviction of the righteousness of his cause, attorneys fees shall not be recovered as cost. [33]On the other hand, RBS asserts that there was no perfected contract between ABS-CBN and VIVAabsent meeting of minds between them regarding the object and consideration of the alleged contract. Itaffirms that ABS-CBNs claim of a right of first refusal was correctly rejected by the trial court. RBS insiststhe premium it had paid for the counterbond constituted a pecuniary loss upon which it may recover. Itwas obliged to put up the counterbond due to the injunction procured by ABS-CBN. Since the trial courtfound that ABS-CBN had no cause of action or valid claim against RBS and, therefore not entitled to thewrit of injunction, RBS could recover from ABS-CBN the premium paid on the counterbond. Contrary to theclaim of ABS-CBN, the cash bond would prove to be more expensive, as the loss would be equivalent to thecost of money RBS would forego in case the P30 million came from its funds or was borrowed from banks.RBS likewise asserts that it was entitled to the cost of advertisements for the cancelled showing of thefilm Maging Sino Ka Man because the print advertisements were out to announce the showing on aparticular day and hour on Channel 7, i.e., in its entirety at one time, not as series to be shown on aperiodic basis. Hence, the print advertisements were good and relevant for the particular date of showing,and since the film could not be shown on that particular date and hour because of the injunction, theexpenses for the advertisements had gone to waste.As regards moral and exemplary damages, RBS asserts that ABS-CBN filed the case and securedinjunctions purely for the purpose of harassing and prejudicing RBS. Pursuant then to Articles 19 and 21 ofthe Civil Code, ABS-CBN must be held liable for such damages. Citing Tolentino,[34] damages may beawarded in cases of abuse of rights even if the done is not illicit, and there is abuse of rights where aplaintiff institutes an action purely for the purpose of harassing or prejudicing the defendant.In support of its stand that a juridical entity can recover moral and exemplary damages, privaterespondent RBS cited People v. Manero, [35] where it was stated that such entity may recover moral andexemplary damages if it has a good reputation that is debased resulting in social humiliation. It thenratiocinates; thus:There can be no doubt that RBS reputation has been debased by ABS-CBNs acts in this case. When RBSwas not able to fulfill its commitment to the viewing public to show the film Maging Sino Ka Man on thescheduled dates and times (and on two occasions that RBS advertised), it suffered serious embarrassmentand social humiliation. When the showing was cancelled, irate viewers called up RBS offices and subjectedRBS to verbal abuse (Announce kayo ng announce, hindi ninyo naman ilalabas, nanloloko yata kayo) (Exh.3-RBS, par.3). This alone was not something RBS brought upon itself. It was exactly what ABS-CBN hadplanted to happen.The amount of moral and exemplary damages cannot be said to be excessive. Two reasons justify theamount of the award.The first is that the humiliation suffered by RBS, is national in extent. RBS operations as a broadcastingcompany is [sic] nationwide. Its clientele, like that of ABS-CBN, consists of those who own and watchtelevision. It is not an exaggeration to state, and it is a matter of judicial notice that almost every otherperson in the country watches television. The humiliation suffered by RBS is multiplied by the number ofteleviewers who had anticipated the showing of the film, Maging Sino Ka Man on May 28 and November 3,1992 but did not see it owing to the cancellation. Added to this are the advertisers who had placedcommercial spots for the telecast and to whom RBS had a commitment in consideration of the placementto show the film in the dates and times specified.
The second is that it is a competitor that caused RBS suffer the humiliation. The humiliation and injury arefar greater in degree when caused by an entity whose ultimate business objective is to lure customers(viewers in this case) away from the competition.[36]For their part, VIVA and Vicente del Rosario contend that the findings of fact of the trial court and theCourt of Appeals do not support ABS-CBNs claim that there was a perfected contract. Such factual findingscan no longer beABS-CBN, and (2) whether RBS is entitled to damages and attorneys fees. It may be noted that that awardof attorneys fees of P212,000 in favor of VIVA is not assigned as another error.IThe first issue should be resolved against ABS-CBN. A contract is a meeting of minds between twopersons whereby one binds himself to give something or render some service to another [37] for aconsideration.There is no contract unless the following requisites concur: (1) consent of the contractingparties; (2) object certain which is the subject of the contract; and (3) cause of the obligation, which isestablished.[38] A contract undergoes three stages:(a) preparation, conception, or generation, which is the period of negotiation and bargaining,ending at the moment of agreement of the parties;(b) perfection or birth of the contract, which is the moment when the parties come to agree on theterms of the contract; and(c) consummation or death, which is the fulfillment or performance of the terms agreed upon inthe contract.[39]Contracts that are consensual in nature are perfected upon mere meeting of the minds. Once there isconcurrence between the offer and the acceptance upon the subject matter, consideration, and terms ofpayment a contract is produced. The offer must be certain. To convert the offer into a contract, theacceptance must be absolute and must not qualify the terms of the offer; it must be plain, unequivocal,unconditional, and without variance of any sort from the proposal. A qualified acceptance, or one thatinvolves a new proposal, constitutes a counter-offer and is a rejection of the original offer. Consequently,when something is desired which is not exactly what is proposed in the offer, such acceptance is notsufficient to generate consent because any modification or variation from the terms of the offer annuls theoffer.[40]When Mr. Del Rosario of Viva met Mr. Lopez of ABS-CBN at the Tamarind Grill on 2 April 1992 to discussthe package of films, said package of 104 VIVA films was VIVAs offer to ABS-CBN to enter into a new FilmExhibition Agreement. But ABS-CBN, sent through Ms. Concio, counter-proposal in the form a draft contractproposing exhibition of 53 films for a consideration of P35 million. This counter-proposal could be nothingless than the counter-offer of Mr. Lopez during his conference with Del Rosario at Tamarind GrillRestaurant. Clearly, there was no acceptance of VIVAs offer, for it was met by a counter-offer whichsubstantially varied the terms of the offer.ABS-CBNs reliance in Limketkai Sons Milling, Inc. v. Court of Appeals [41] and Villonco Realty Company v.Bormaheco, Inc.,[42] is misplaced. In these cases, it was held that an acceptance may contain a request forcertain changes in the terms of the offer and yet be a binding acceptance as long as it is clear that themeaning of the acceptance is positively and unequivocally to accept the offer, whether such request isgranted or not. This ruling was, however, reversed in the resolution of 29 March 1996, [43] which ruled thatthe acceptance of an offer must be unqualified and absolute, i.e., it must be identical in all respects withthat of the offer so as to produce consent or meetings of the minds.On the other hand, in Villonco, cited in Limketkai, the alleged changes in the revised counter-offerwere not material but merely clarificatory of what had previously been agreed upon. It cited the statementinStuart v. Franklin Life Insurance Co. [44] that a vendors change in a phrase of the offer to purchase, whichchange does not essentially change the terms of the offer, does not amount to a rejection of the offer andthe tender of a counter-offer.[45] However, when any of the elements of the contract is modified uponacceptance, such alteration amounts to a counter-offer.In the case at bar, ABS-CBN made no unqualified acceptance of VIVAs offer hence, they underwentperiod of bargaining. ABS-CBN then formalized its counter-proposals or counter-offer in a draft
could not therefore legally bind Viva, not having agreed thereto. In fact, Ms. Concio admitted that theterms and conditions embodied in Exhibit C were prepared by ABS-CBNs lawyers and there was nodiscussion on said terms and conditions.As the parties had not yet discussed the proposed terms and conditions in Exhibit C, and there was noevidence whatsoever that Viva agreed to the terms and conditions thereof, said document cannot be abinding contract. The fact that Viva refused to sign Exhibit C reveals only two [sic] well that it did not agreeon its terms and conditions, and this court has no authority to compel Viva to agree thereto.FIFTH. Mr. Lopez understand [sic] that what he and Mr. Del Rosario agreed upon at the Tamarind Grill wasonly provisional, in the sense that it was subject to approval by the Board of Directors of Viva. He testified:Q Now, Mr. Witness, and after that Tamarinf meeting the second meeting wherein you claimed that youhave the meeting of the minds between you and Mr. Vic del Rosario, what happened?A Vic Del Rosario was supposed to call us up and tell us specifically the result of the discussion with theBoard of Directors.Q And you are referring to the so-called agreement which you wrote in [sic] a piece of authority tobind Viva to a contract with ABS-CBN until and unless its Board of Directors approved it. The complaint, infact, alleges that Mr. Del Rosario is the Executive Producer of defendant Viva which is a corporation. (par. 2,complaint). As a mere agent of Viva, Del Rosario could not bind Viva unless what he did is ratified by itsDirectors. (Vicente vs.Geraldez, 52 SCRA 210; Arnold vs. Willets and Paterson, 44 Phil. 634). As a mereagent, recognized as such by plaintiff, Del Rosario could not be held liable jointly and severally with Vivaand his inclusion as party defendant has no legal basis. (Salonga vs. Warner Barnes [sic],COLTA, 88 Phil.125; Salmon vs. Tan, 36 Phil. 556).The testimony of Mr. Lopez and the allegations in the complaint are clear admissions that what wassupposed to have been agreed upon at the Tamarind Grill between Mr. Lopez and Del Rosario was not abinding agreement. It is as it should be because corporate power to enter into a contract is lodged in theBoard of Directors. (Sec. 23, Corporation Code). Without such board approval by the Viva board, whateveragreement Lopez and Del Rosario arrived at could not ripen into a valid binding upon Viva (Yao Ka SinTrading vs. Court of Appeals, 209 SCRA 763). The evidence adduced shows that the Board of Directors ofViva rejected Exhibit C and insisted that the film package for 104 films be maintained (Exh. 7-1 Cica). [49]The contention that ABS-CBN had yet to fully exercise its right of first refusal over twenty-four filmsunder the 1990 Film Exhibition Agreement and that the meeting between Lopez and Del Rosario was acontinuation of said previous contract is untenable. As observed by the trial court, ABS-CBNs right of firstrefusal had already been exercised right offirst refusal may have been already exercised by Ms. Concio (as she had). (TSN, June 8, 1992, pp. 7175). Del Rosario himself knew and understand [sic] that ABS-CBN has lost its right of first refusal whenhis list of 36 titles were rejected (Tsn, June 9, 1992, pp. 10-11). [50]II
However, we find for ABS-CBN on the issue of damages. We shall first take up actualdamages. Chapter 2, Title XVIII, Book IV of the Civil Code is the specific law on actual or compensatorydamages. Except as provided by law or by stipulation, one is entitled to compensation for actual damagesonly for such pecuniary loss suffered by him as he has duly proved. [51] The indemnification shallcomprehend not only the value of the loss suffered, but also that of the profits that the obligee failed toobtain.[52] In contracts and quasi-contracts the damages which may be awarded are dependent on whetherthe obligor acted with good faith or otherwise. In case of good faith, the damages recoverable are thosewhich are the natural and probable consequences of the breach of the obligation and which the partieshave foreseen or could have reasonably foreseen at the time of the constitution of the obligation. If theobligor acted with fraud, bad faith, malice, or wanton attitude, he shall be responsible for all damageswhich may be reasonably attributed to the non-performance of the obligation. [53] In crimes and quasidelicts, the defendants shall be liable for all damages which are the natural and probable consequences ofthe act or omission complained of, whether or not such damages have been foreseen or could havereasonably been foreseen by the defendant.[54]Actual damages may likewise be recovered for loss or impairment of earning capacity in cases oftemporary or permanent personal injury, or for injury to the plaintiffs business standing or commercialcredit.[55]The claim of RBS for actual damages did not arise from contract, quasi-contract, delict, or quasidelict. It arose from the fact of filing of the complaint despite ABS-CBNs alleged knowledge of lack of causeof action. Thus paragraph 12 of RBSs Answer with Counterclaim and Cross-claim under the headingCOUNTERCLAIM specifically alleges:12. ABS-CBN filed the complaint knowing fully well that it has no cause of action against RBS. As aresult thereof, RBS suffered actual damages in the amount of P6,621,195.32.[56]Needless to state the award of actual damages cannot be comprehended under the above law on actualdamages. RBS could only probably take refuge under Articles 19, 20, and 21 of the Civil Code, which readas follows:ART. 19. Every person must, in the exercise of hid rights and in the performance of his duties, act withjustice, give everyone his due, and observe honesty and good faith.ART. 20. Every person who, contrary to law, wilfully or negligently causes damage to another shallindemnify the latter for thewhich the defendant may suffer by reason of the writ are recoverable from the injunctive bond. [57] In thiscase, ABS-CBN had not yet filed the required bond; as a matter of fact, it asked for reduction of the bondand even went to the Court of Appeals to challenge the order on the matter. Clearly then, it was notnecessary for RBS to file a counterbond. Hence, ABS-CBN cannot be held responsible for the premium RBSpaid for the counterbond.Neither could ABS-CBN be liable for the print advertisements for Maging Sino Ka Man for lack ofsufficient legal basis. The RTC issued a temporary restraining order and later, a writ of preliminaryinjunction on the basis of its determination that there existed sufficient ground for the issuancethereof. Notably, the RTC did not dissolve the injunction on the ground of lack of legal and factual basis,but because of the plea of RBS that it be allowed to put up a counterbond.As regards attorneys fees, the law is clear that in the absence of stipulation, attorneys fees may berecovered as actual or compensatory damages under any of the circumstances provided for in Article 2208of the Civil Code.[58]The general rule is that attorneys fees cannot be recovered as part of damages because of the policythat no premium should be placed on the right to litigate. [59] They are not to be awarded every time a partywins a suit. The power of the court t award attorneys fees under Article 2208 demands factual, legal, andequitable justification.[60] Even when a claimant is compelled to litigate with third persons or to incurexpenses to protect his rights, still attorneys fees may not be awarded where no sufficient showing of bad
faith could be reflected in a partys persistence in a case other than an erroneous conviction of therighteousness of his cause.[61]As to moral damages the law is Section 1, Chapter 3, Title XVIII, Book IV of the Civil Code. Article 2217thereof defines what are included in moral damages, while Article 2219 enumerates the cases where theymay be recovered. Article 2220 provides that moral damages may be recovered in breaches of contractwhere the defendant acted fraudulently or in bad faith. RBSs claim for moral damages could possibly fallonly under item (10) of Article 2219, thereof which reads:(10) Acts and actions referred to in Articles 21, 26, 27, 28, 29, 30, 32, 34 and 35.Moral damages are in the category of an award designed to compensate the claimant for actual injurysuffered and not to impose a penalty on the wrongdoer. [62] The award is not meant to enrich thecomplainant at the expense of the defendant, but to enable the injured party to obtain means, diversion,or amusements that will serve to obviate the moral suffering he has undergone. It is aimed at therestoration, within the limits of the possible, of the spiritual status quo ante, and should be proportionateto the suffering inflicted.[63] Trial courts must then guard against the award of exorbitant damages; theyshould exercise balanced restrained and measured objectivity to avoid suspicion that it was due topassion, prejudice, or corruption or the part of the trial court. [64]The award of moral damages cannot be granted in favor of a corporation because, being an artificialperson and having existence only in legal contemplation, it has no feelings, no emotions, no senses. Itcannot, therefore, experience physical suffering and mental anguish, which can be experienced only byone having a nervous system.[65] The statement in People v. Manero[66] and Mambulao Lumber Co. v.PNB[67] that a corporation may recover moral damages if it has a good reputation that is debased, resultingin social humiliation is an obiter dictum. On this score alone the award for damages must be set aside,since RBS is a corporation.The basic law on exemplary damages is Section 5 Chapter 3, Title XVIII, Book IV of the CivilCode. These are imposed by way of example or correction for the public good, in addition to moral,temperate, liquidated, or compensatory damages.[68] They are recoverable in criminal cases as part of thecivil liability when the crime was committed with one or more aggravating circumstances; [69] in quasidelicts, if the defendant acted with gross negligence; [70] and in contracts and quasi-contracts, if thedefendant19, 20, and 21 of the Civil Code.The elements of abuse of right under Article 19 are the following: (1) the existence of a legal right orduty, (2) which is exercised in bad faith, and (3) for the sole intent of prejudicing or injuring another. Article20 speaks of the general sanction for all provisions of law which do not especially provide for their ownsanction; while Article 21 deals with acts contra bonus mores, and has the following elements: (1) there is aconscious and intentional design to do a wrongful act for a dishonest purpose or moral obliquity. [73] Suchmust be substantiated by evidence.[74]There is no adequate proof that ABS-CBN was inspired by malice or bad faith. It was honestlyconvinced of the merits of its cause after it had undergone serious negotiations culminating in its formalsubmission of a draft contract. Settled is the rule that the adverse result of an action does not per se makethe action wrongful and subject the actor to damages, for the law could not have meant impose a penaltyon the right to litigate. If damages result from a persons exercise of a right, it is damnum absque injuria.[75]WHEREFORE, the instant petition is GRANTED. The challenged decision of the Court of Appeals in CAG.R. CV No. 44125 is hereby REVERSED except as to unappealed award of attorneys fees in favor of VIVAProductions, Inc.No pronouncement as to costs.SO ORDERED.Melo, Kapunan, Martinez, and Pardo, JJ., concur.
2. The projects shall be undertaken pursuant to the attached specifications. It is understood thatany item required to complete the project, and those not included in the list of items shall bedeemed included and covered and shall be performed;3. All materials shall be brand new;4. The project shall commence immediately and must be completed within twenty (20) workingdays after the delivery of Generator Set to Marikina Plant, penalty equivalent to 1/10 of 1% of thepurchase price for every day of delay;5. The Contractor shall put up Performance Bond equivalent to thirty (30%) of the contract price,and shall procure All Risk Insurance equivalent to the contract price upon commencement of theproject. The All Risk Insurance Policy shall be endorsed in favor of and shall be delivered to PureFoods Corporation;6. Warranty of one (1) year against defective material and/or workmanship.Once finalized, we shall ask you to sign the formal contract embodying the foregoing terms and conditions.Immediately, FEMSCO submitted the required performance bond in the amount of P1,841,187.90 andcontractor's all-risk insurance policy in the amount of P6,137,293.00 which PUREFOODS through its VicePresident Benedicto G. Tope acknowledged in a letter dated 18 December 1992. FEMSCO also madearrangements with its principal and started the PUREFOODS project by purchasing the necessarymaterials. PUREFOODS on the other hand returned FEMSCO's Bidder's Bond in the amount ofP1,000,000.00, as requested.Later, however, in a letter dated 22 December 1992, PUREFOODS through its Senior Vice President TeodoroL. Dimayuga unilaterally canceledproject and entered into a contract with JARDINE NELL, a division of Jardine Davies, Inc. (hereafterJARDINE), which incidentally was not one of the bidders.1wphi1.ntFEMSCO thus wrote PUREFOODS to honor its contract with the former, and to JARDINE to cease and desistfrom delivering and installing the two (2) generators at PUREFOODS. Its demand letters unheeded,FEMSCO sued both PUREFOODS and JARDINE: PUREFOODS for reneging on its contract, and JARDINE for itsunwarranted interference and inducement. Trial ensued. After FEMSCO presented its evidence, JARDINEfiled a Demurrer to Evidence.On 27 June 1994 the Regional Trial Court of Pasig, Br. 68, 1 granted JARDINE's Demurrer to Evidence. Thetrial court concluded that "[w]hile it may seem to the plaintiff that by the actions of the two defendantsthere is something underhanded going on, this is all a matter of perception, and unsupported by hardevidence, mere suspicions and suppositions would not stand up very well in a court of law." 2 Meanwhiletrial proceeded as regards the case against PUREFOODS.On 28 July 1994 the trial court rendered a decision ordering PUREFOODS: (a) to indemnify FEMSCO the sumof P2,300,000.00 representing the value of engineering services it rendered; (b) to pay FEMSCO the sum ofUS$14,000.00 or its peso equivalent, and P900,000.00 representing contractor's mark-up on installationwork, considering that it would be impossible to compel PUREFOODS to honor, perform and fulfill itscontractual obligations in view of PUREFOOD's contract with JARDINE and noting that construction hadalready started thereon; (c) to pay attorney's fees in an amount equivalent to 20% of the total amount
due; and, (d) to pay the costs. The trial court dismissed the counterclaim filed by PUREFOODS for lack offactual and legal basis.Both FEMSCO and PUREFOODS appealed to the Court of Appeals. FEMSCO appealed the 27 June 1994Resolution of the trial court which granted the Demurrer to Evidence filed by JARDINE resulting in thedismissal of the complaint against it, while PUREFOODS appealed the 28 July 1994 Decision of the samecourt which ordered it to pay FEMSCO.On 14 August 1996 the Court of Appeals affirmed in toto the 28 July 1994 Decision of the trial court. 3 Italso reversed the 27 June 1994 Resolution of the lower court and ordered JARDINE to pay FEMSCOdamages for inducing PUREFOODS to violate the latter's contract with FEMSCO. As such, JARDINE wasordered to pay FEMSCO P2,000,000.00 for moral damages. In addition, PUREFOODS was also directed topayfiled by PUREFOODS and JARDINE. Hence, these two (2) petitions for review filed by PUREFOODS andJARDINE which were subsequently consolidated.PUREFOODS maintains that the conclusions of both the trial court and the appellate court are premised ona misapprehension of facts. It argues that its 12 December 1992 letter to FEMSCO was not an acceptanceof the latter's bid proposal and award of the project but more of a qualified acceptance constituting acounter-offer which required FEMSCO's express conforme. Since PUREFOODS never receivedFEMSCO's conforme, PUREFOODS was very well within reason to revoke its qualified acceptance orcounter-offer. Hence, no contract was perfected between PUREFOODS and FEMSCO. PUREFOODS alsocontends that it was never in bad faith when it dealt with FEMSCO. Hence moral and exemplary damagesshould not have been awarded.Corollarily, JARDINE asserts that the records are bereft of any showing that it had prior knowledge of thesupposed contract between PUREFOODS and FEMSCO, and that it induced PUREFOODS to violate thelatter's alleged contract with FEMSCO. Moreover, JARDINE reasons that FEMSCO, an artificial person, is notentitled to moral damages. But granting arguendo that the award of moral damages is proper,P2,000,000.00 is extremely excessive.In the main, these consolidated cases present two (2) issues: first, whether there existed a perfectedcontract between PUREFOODS and FEMSCO; and second, granting there existed a perfected contract,whether there is any showing that JARDINE induced or connived with PUREFOODS to violate the latter'scontract with FEMSCO.A contract is defined as "a juridical convention manifested in legal form, by virtue of which one or morepersons bind themselves in favor of another or others, or reciprocally, to the fulfillment of a prestation togive, to do, or not to do."4 There can be no contract unless the following requisites concur: (a) consent ofthe contracting parties; (b) object certain which is the subject matter of the contract; and, (c) cause of theobligation which is established. 5 A contract binds both contracting parties and has the force of lawbetween them.Contracts are perfected by mere consent, upon the acceptance by the offeree of the offer made by theofferor. From that moment, the parties are bound not only to the fulfillment of what has been expresslystipulated but also to all the consequences which, according to their nature, may be in keeping with goodfaith, usage and law. 6 To produce a contract, the acceptance must not qualify the terms of the offer.However, the acceptance may be express or implied. 7 For a contract to arise, the acceptance must bemade known to the offeror. Accordingly, the acceptance can be withdrawn or revoked before it is madeknown to the offeror.
In the instant case, there is no issue as regards the subject matter of the contract and the cause of theobligation. The controversy lies in the consent whether there was an acceptance of the offer, and if so, ifit was communicated, thereby perfecting the contract.To resolve the dispute, there is a need to determine what constituted the offer and the acceptance. Sincepetitioner PUREFOODS started the process of entering into the contract by conducting a bidding, Art. 1326of the Civil Code, which provides that "[a]dvertisements for bidders are simply invitations to makeproposals," applies. Accordingly, the Terms and Conditions of the Bidding disseminated by petitionerPUREFOODS constitutes the "advertisement" to bid on the project. The bid proposals or quotationssubmitted by the prospective suppliers including respondent FEMSCO, are the offers. And, the reply ofpetitioner PUREFOODS, the acceptance or rejection of the respective offers.Quite obviously, the 12 December 1992 letter of petitioner. PUREFOODS to FEMSCO constitutedacceptance of respondent FEMSCO's offer as contemplated by law. The tenor of the letter, i.e., "This willconfirm that Pure Foods has awarded to your firm (FEMSCO) the project," could not be more categorical.While the same letter enumerated certain "basic terms and conditions," these conditions were imposed onthe performance of the obligation rather than on the perfection of the contract. Thus, the first "condition"was merely a reiteration of the contract price and billing scheme based on the Terms and Conditions ofBidding and the bid or previous offer of respondent FEMSCO. The second and third "conditions" werenothing more than general statements that all items and materials including those excluded in the list butnecessary to complete the project shall be deemed included and should be brand new. The fourth"condition" concerned the completion of the work to be done, i.e., within twenty (20) days from thedelivery of the generator set, the purchase of which was part of the contract. The fifth "condition" had todo with the putting up of a performance bond and an all-risk insurance, both of which should be givenupon commencement of the project. The sixth "condition" related to the standard warranty of one (1) year.In fine, the enumerated "basic terms and conditions" were prescriptions on how the obligation was to beperformed and implemented. They were far from being conditions imposed on the perfection of thecontract.In Babasa v. Court of Appeals 8 we distinguished between a condition imposed on the perfection of acontract and a condition imposed merely on the performance of an obligation. While failure to comply withthe first condition results in the failure of a contract, failure to comply with the second merely gives theother party options and/or remedies to protect his interests.We thus agree with the conclusion of respondent appellate court which affirmed the trial court As can be inferred from the actual phrase used in the first portion of the letter, the decision toaward the contract has already been made. The letter only serves as a confirmation of suchdecision. Hence, to the Court's mind, there is already an acceptance made of the offer received byPurefoods. Notwithstanding the terms and conditions enumerated therein, the offer has beenaccepted and/or amplified the details of the terms and conditions contained in the Terms andConditions of Bidding given out by Purefoods to prospective bidders. 9But even granting arguendo that the 12 December 1992 letter of petitioner PUREFOODS constituted a"conditional counter-offer," respondent FEMCO's submission of the performance bond and contractor's allrisk insurance was an implied acceptance, if not a clear indication of its acquiescence to, the "conditionalcounter-offer," which expressly stated that the performance bond and the contractor's all-risk insuranceshould be given upon the commencement of the contract. Corollarily, the acknowledgment thereof bypetitioner PUREFOODS, not to mention its return of FEMSCO's bidder's bond, was a concrete manifestationof its knowledge that respondent FEMSCO indeed consented to the "conditional counter-offer." After all, asearlier adverted to, an acceptance may either be express or implied, 10 and this can be inferred from thecontemporaneous and subsequent acts of the contracting parties.
Accordingly, for all intents and purposes, the contract at that point has been perfected, and respondentFEMSCO'sconforme would only be a mere surplusage. The discussion of the price of the project two (2)months after the 12 December 1992 letter can be deemed as nothing more than a pressure being exertedby petitioner PUREFOODS on respondent FEMSCO to lower the price even after the contract had beenperfected. Indeed from the facts, it can easily be surmised that petitioner PUREFOODS was haggling for alower price even after agreeing to the earlier quotation, and was threatening to unilaterally cancel thecontract, which it eventually did. Petitioner PUREFOODS also makes an issue out of the absence of apurchase order (PO). Suffice it to say that purchase orders or POs do not make or break a contract. Thus,even the tenor of the subsequent letter of petitioner PUREFOODS, i.e., "Pure Foods Corporation is herebycanceling the award to your company of the project," presupposes that the contract has been perfected.For, there can be no cancellation if the contract was not perfected in the first place.Petitioner PUREFOODS also argues that it was never in bad faith.1avvphi1 On the contrary, it believed ingood faith that no such contract was perfected. We are not convinced. We subscribe to the factual findingsand conclusions of the trial court which were affirmed by the appellate court Hence, by the unilateral cancellation of the contract, the defendant (petitioner PURE FOODS) hasacted with bad faith and this was further aggravated by the subsequent inking of a contractbetween defendant Purefoods and erstwhile co-defendant Jardine. It is very evident that Purefoodsthought that by the expedient means of merely writing a letter would automatically cancel or nullifythe existing contract entered into by both parties after a process of bidding. This, to the Court'smind, is a flagrant violation of the express provisions of the law and is contrary to fair and justdealings to which every man is due. 11This Court has awarded in the past moral damages to a corporation whose reputation has beenbesmirched. 12 In the instant case, respondent FEMSCO has sufficiently shown that its reputation wastarnished after it immediately ordered equipment from its suppliers on account of the urgency of theproject, only to be canceled later. We thus sustain respondent appellate court's award of moral damages.We however reduce the award from P2,000,000.00 to P1,000,000.00, as moral damages are neverintended to enrich the recipient. Likewise, the award of exemplary damages by way of example for thepublic good is excessive and should be reduced to P100,000.00.Petitioner JARDINE maintains on the other hand that respondent appellate court erred in ordering it to paymoral damages to respondent FEMSCO as it supposedly induced PUREFOODS to violate the contract withFEMSCO. We agree. While it may seem that petitioners PUREFOODS and JARDINE connived to deceiverespondent FEMSCO, we find no specific evidence on record to support such perception. Likewise, there isno showing whatsoever that petitioner JARDINE induced petitioner PUREFOODS. The similarity in thedesign submitted to petitioner PUREFOODS by both petitioner JARDINE and respondent FEMSCO, and thetender of a lower quotation by petitioner JARDINE are insufficient to show that petitioner JARDINE indeedinduced petitioner PUREFOODS to violate its contract with respondent FEMSCO.WHEREFORE, judgment is hereby rendered as follows:(a) The petition in G.R. No. 128066 is GRANTED. The assailed Decision of the Court of Appealsreversing the 27 June 1994 resolution of the trial court and ordering petitioner JARDINE DAVIES,INC., to pay private respondent FAR EAST MILLS SUPPLY CORPORATION P2,000,000.00 as moraldamages is REVERSED and SET ASIDE for insufficiency of evidence; and(b) The petition in G.R. No. 128069 is DENIED. The assailed Decision of the Court of Appealsordering petitioner PUREFOODS CORPORATION to pay private respondent FAR EAST MILLS SUPPLYCORPORATION the sum of P2,300,000.00 representing the value of engineering services it rendered,US$14,000.00 or its peso equivalent, and P900,000.00 representing the contractor's mark-up oninstallation work, as well as attorney's fees equivalent to twenty percent (20%) of the total amount
due, is AFFIRMED. In addition, petitioner PURE FOODS CORPORATION is ordered to pay privaterespondent FAR EAST MILLS SUPPLY CORPORATION moral damages in the amount of P1,000,000.00and exemplary damages in the amount of P1,000,000.00. Costs against petitioner.G.R. No. L-22973
On August 2, 1956, the PNB released from the approved loan the sum of P27,500, for which theplaintiff signed a promissory note wherein it promised to pay to the PNB the said sum in five equalyearly installments at the rate of P6,528.40 beginning July 31, 1957, and every year thereafter, thelast of which would be on July 31, 1961.On October 19, 1956, the PNB made another release of P15,500 as part of the approved loangranted to the plaintiff and so on the said date, the latter executed another promissory notewherein it agreed to pay to the former the said sum in five equal yearly installments at the rate ofP3,679.64 beginning July 31, 1957, and ending on July 31, 1961.The plaintiff failed to pay the amortization on the amounts released to and received by it. Repeateddemands were made upon the plaintiff to pay its obligation but it failed or otherwise refused to doso. Upon inspection and verification made by employees of the PNB, it was found that the plaintiffhad already stopped operation about the end of 1957 or early part of 1958.On September 27, 1961, the PNB sent a letter to the Provincial Sheriff of Camarines Norterequesting him to take possession of the parcel of land, together with the improvements existingthereon, covered by Transfer Certificate of Title No. 381 of the land records of Camarines Norte, andto sell it at public auction in accordance with the provisions of Act No. 3135, as amended, for thesatisfaction of the unpaid obligation of the plaintiff, which as of September 22, 1961, amounted toP57,646.59, excluding attorney's fees. In compliance with the request, on October 16, 1961, theProvincial Sheriff of Camarines Norte issued the corresponding notice of extra-judicial sale and senta copy thereof to the plaintiff. According to the notice, the mortgaged property would be sold atpublic auction at 10:00 a.m. on November 21, 1961, at the ground floor of the Court House in Daet,Camarines Norte.On November 6, 1961, the PNB sent a letter to the Provincial Sheriff of Camarines Norte requestinghim to take possession of the chattels mortgaged to it by the plaintiff and sell them at publicauction also on November 21, 1961, for the satisfaction of the sum of P57,646.59, plus 6% annualinterest therefore from September 23, 1961, attorney's fees equivalent to 10% of the amount dueand the costs and expenses of the sale. On the same day, the PNB sent notice to the plaintiff thatthe former was foreclosing extrajudicially the chattels mortgaged by the latter and that the auctionsale thereof would be held on November 21, 1961, between 9:00 and 12:00 a.m., in Mambulao,Camarines Norte, where the mortgaged chattels were situated.On November 8, 1961, Deputy Provincial Sheriff Anacleto Heraldo took possession of the chattelsmortgaged by the plaintiff and made an inventory thereof in the presence of a PC Sergeant and apoliceman of the municipality of Jose Panganiban. On November 9, 1961, the said Deputy Sheriffissued the corresponding notice of public auction sale of the mortgaged chattels to be held onNovember 21, 1961, at 10:00 a.m., at the plaintiff's compound situated in the municipality of JosePanganiban, Province of Camarines Norte.On November 19, 1961, the plaintiff sent separate letters, posted as registered air mail matter, oneto the Naga Branch of the PNB and another to the Provincial Sheriff of Camarines Norte, protestingagainst the foreclosure of the real estate and chattel mortgages on the grounds that they could notbe effected unless a Court's order was issued against it (plaintiff) for said purpose and that theforeclosure proceedings, according to the terms of the mortgage contracts, should be made inManila. In said letter to the Naga Branch of the PNB, it was intimated that if the public auction salewould be suspended and the plaintiff would be given an extension of ninety (90) days, its obligationwould be settled satisfactorily because an important negotiation was then going on for the sale ofits "whole interest" for an amount more than sufficient to liquidate said obligation.The letter of the plaintiff to the Naga Branch of the PNB was construed by the latter as a request forextension of the foreclosure sale of the mortgaged chattels and so it advised the Sheriff ofCamarines Norte to defer it to December 21, 1961, at the same time and place. A copy of saidadvice was sent to the plaintiff for its information and guidance.The foreclosure sale of the parcel of land, together with the buildings and improvements thereon,covered by Transfer Certificate of Title No. 381, was, however, held on November 21, 1961, and thesaid property was sold to the PNB for the sum of P56,908.00, subject to the right of the plaintiff to
redeem the same within a period of one year. On the same date, Deputy Provincial Sheriff Heraldoexecuted a certificate of sale in favor of the PNB and a copy thereof was sent to the plaintiff.In a letter dated December 14, 1961 (but apparently posted several days later), the plaintiff sent abank draft for P738.59 to the Naga Branch of the PNB, allegedly in full settlement of the balance ofthe obligation of the plaintiff after the application thereto of the sum of P56,908.00 representing theproceeds of the foreclosure sale of parcel of land described in Transfer Certificate of Title No. 381. Inthe said letter, the plaintiff reiterated its request that the foreclosure sale of the mortgaged chattelsbe discontinued on the grounds that the mortgaged indebtedness had been fully paid and that itcould not be legally effected at a place other than the City of Manila.In a letter dated December 16, 1961, the plaintiff advised the Provincial Sheriff of Camarines Nortethat it had fully paid its obligation to the PNB, and enclosed therewith a copy of its letter to thelatter dated December 14, 1961.On December 18, 1961, the Attorney of the Naga Branch of the PNB, wrote to the plaintiffacknowledging the remittance of P738.59 with the advice, however, that as of that date thebalance of the account of the plaintiff was P9,161.76, to which should be added the expenses ofguarding the mortgaged chattels at the rate of P4.00 a day beginning December 19, 1961. It wasfurther explained in said letter that the sum of P57,646.59, which was stated in the request for theforeclosure of the real estate mortgage, did not include the 10% attorney's fees and expenses ofthe sale. Accordingly, the plaintiff was advised that the foreclosure sale scheduled on the 21st ofsaid month would be stopped if a remittance of P9,161.76, plus interest thereon and guarding fees,would be made.On December 21, 1961, the foreclosure sale of the mortgaged chattels was held at 10:00 a.m. andthey were awarded to the PNB for the sum of P4,200 and the corresponding bill of sale was issuedin its favor by Deputy Provincial Sheriff Heraldo.In a letter dated December 26, 1961, the Manager of the Naga Branch of the PNB advised theplaintiff giving it priority to repurchase the chattels acquired by the former at public auction. Thisoffer was reiterated in a letter dated January 3, 1962, of the Attorney of the Naga Branch of the PNBto the plaintiff, with the suggestion that it exercise its right of redemption and that it apply for thecondonation of the attorney's fees. The plaintiff did not follow the advice but on the contrary itmade known of its intention to file appropriate action or actions for the protection of its interests.On May 24, 1962, several employees of the PNB arrived in the compound of the plaintiff in JosePanganiban, Camarines Norte, and they informed Luis Salgado, Chief Security Guard of thepremises, that the properties therein had been auctioned and bought by the PNB, which in turn soldthem to Mariano Bundok. Upon being advised that the purchaser would take delivery of the thingshe bought, Salgado was at first reluctant to allow any piece of property to be taken out of thecompound of the plaintiff. The employees of the PNB explained that should Salgado refuse, hewould be exposing himself to a litigation wherein he could be held liable to pay big sum of moneyby way of damages. Apprehensive of the risk that he would take, Salgado immediately sent a wireto the President of the plaintiff in Manila, asking advice as to what he should do. In the meantime,Mariano Bundok was able to take out from the plaintiff's compound two truckloads of equipment.In the afternoon of the same day, Salgado received a telegram from plaintiff's President directinghim not to deliver the "chattels" without court order, with the information that the company wasthen filing an action for damages against the PNB. On the following day, May 25, 1962, two trucksand men of Mariano Bundok arrived but Salgado did not permit them to take out any equipmentfrom inside the compound of the plaintiff. Thru the intervention, however, of the local police and PCsoldiers, the trucks of Mariano Bundok were able finally to haul the properties originally mortgagedby the plaintiff to the PNB, which were bought by it at the foreclosure sale and subsequently sold toMariano Bundok.Upon the foregoing facts, the trial court rendered the decision appealed from which, as stated in the firstparagraph of this opinion, sentenced the Mambulao Lumber Company to pay to the defendant PNB thesum of P3,582.52 with interest thereon at the rate of 6% per annum from December 22, 1961 (day
following the date of the questioned foreclosure of plaintiff's chattels) until fully paid, and the costs.Mambulao Lumber Company interposed the instant appeal.We shall discuss the various points raised in appellant's brief in seriatim.The first question Mambulao Lumber Company poses is that which relates to the amount of itsindebtedness to the PNB arising out of the principal loans and the accrued interest thereon. It is contendedthat its obligation under the terms of the two promissory notes it had executed in favor of the PNBamounts only to P56,485.87 as of November 21, 1961, when the sale of real property was effected, andnot P58,213.51 as found by the trial court.There is merit to this claim. Examining the terms of the promissory note executed by the appellant in favorof the PNB, we find that the agreed interest on the loan of P43,000.00 P27,500.00 released on August 2,1956 as per promissory note of even date (Exhibit C-3), and P15,500.00 released on October 19, 1956, asper promissory note of the same date (Exhibit C-4) was six per cent (6%) per annum from the respectivedate of said notes "until paid". In the statement of account of the appellant as of September 22, 1961,submitted by the PNB, it appears that in arriving at the total indebtedness of P57,646.59 as of that date,the PNB had compounded the principal of the loan and the accrued 6% interest thereon each time theyearly amortizations became due, and on the basis of these compounded amounts charged additionaldelinquency interest on them up to September 22, 1961; and to this erroneously computed total ofP57,646.59, the trial court added 6% interest per annum from September 23, 1961 to November 21 of thesame year. In effect, the PNB has claimed, and the trial court has adjudicated to it, interest on accruedinterests from the time the various amortizations of the loan became due until the real estate mortgageexecuted to secure the loan was extra-judicially foreclosed on November 21, 1961. This is an error. Section5 of Act No. 2655 expressly provides that in computing the interest on any obligation, promissory note orother instrument or contract, compound interest shall not be reckoned, except by agreement, or in defaultthereof, whenever the debt is judicially claimed. This is also the clear mandate of Article 2212 of the newCivil Code which provides that interest due shall earn legal interest only from the time it is judiciallydemanded, and of Article 1959 of the same code which ordains that interest due and unpaid shall not earninterest. Of course, the parties may, by stipulation, capitalize the interest due and unpaid, which as addedprincipal shall earn new interest; but such stipulation is nowhere to be found in the terms of the promissorynotes involved in this case. Clearly therefore, the trial court fell into error when it awarded interest onaccrued interests, without any agreement to that effect and before they had been judicially demanded.Appellant next assails the award of attorney's fees and the expenses of the foreclosure sale in favor of thePNB. With respect to the amount of P298.54 allowed as expenses of the extra-judicial sale of the realproperty, appellant maintains that the same has no basis, factual or legal, and should not have beenawarded. It likewise decries the award of attorney's fees which, according to the appellant, should not bededucted from the proceeds of the sale of the real property, not only because there is no expressagreement in the real estate mortgage contract to pay attorney's fees in case the same is extra-judiciallyforeclosed, but also for the reason that the PNB neither spent nor incurred any obligation to pay attorney'sfees in connection with the said extra-judicial foreclosure under consideration.There is reason for the appellant to assail the award of P298.54 as expenses of the sale. In this respect, thetrial court said:The parcel of land, together with the buildings and improvements existing thereon covered byTransfer Certificate of Title No. 381, was sold for P56,908. There was, however, no evidence howmuch was the expenses of the foreclosure sale although from the pertinent provisions of the Rulesof Court, the Sheriff's fees would be P1 for advertising the sale (par. k, Sec. 7, Rule 130 of the OldRules) and P297.54 as his commission for the sale (par. n, Sec. 7, Rule 130 of the Old Rules) or atotal of P298.54.There is really no evidence of record to support the conclusion that the PNB is entitled to the amountawarded as expenses of the extra-judicial foreclosure sale. The court below committed error in applyingthe provisions of the Rules of Court for purposes of arriving at the amount awarded. It is to be borne inmind that the fees enumerated under paragraphs k and n, Section 7, of Rule 130 (now Rule 141) aredemandable, only by a sheriff serving processes of the court in connection with judicial foreclosure ofmortgages under Rule 68 of the new Rules, and not in cases of extra-judicial foreclosure of mortgagesunder Act 3135. The law applicable is Section 4 of Act 3135 which provides that the officer conducting the
sale is entitled to collect a fee of P5.00 for each day of actual work performed in addition to his expenses inconnection with the foreclosure sale. Admittedly, the PNB failed to prove during the trial of the case, that itactually spent any amount in connection with the said foreclosure sale. Neither may expenses forpublication of the notice be legally allowed in the absence of evidence on record to support it. 1 It is true, aspointed out by the appellee bank, that courts should take judicial notice of the fees provided for by lawwhich need not be proved; but in the absence of evidence to show at least the number of working days thesheriff concerned actually spent in connection with the extra-judicial foreclosure sale, the most that hemay be entitled to, would be the amount of P10.00 as a reasonable allowance for two day's work one forthe preparation of the necessary notices of sale, and the other for conducting the auction sale andissuance of the corresponding certificate of sale in favor of the buyer. Obviously, therefore, the award ofP298.54 as expenses of the sale should be set aside.But the claim of the appellant that the real estate mortgage does not provide for attorney's fees in casethe same is extra-judicially foreclosed, cannot be favorably considered, as would readily be revealed by anexamination of the pertinent provision of the mortgage contract. The parties to the mortgage appear tohave stipulated under paragraph (c) thereof, inter alia:. . . For the purpose of extra-judicial foreclosure, the Mortgagor hereby appoints the Mortgagee hisattorney-in-fact to sell the property mortgaged under Act 3135, as amended, to sign all documentsand to perform all acts requisite and necessary to accomplish said purpose and to appoint itssubstitute as such attorney-in-fact with the same powers as above specified. In case of judicialforeclosure, the Mortgagor hereby consents to the appointment of the Mortgagee or any of itsemployees as receiver, without any bond, to take charge of the mortgaged property at once, and tohold possession of the same and the rents, benefits and profits derived from the mortgagedproperty before the sale, less the costs and expenses of the receivership; the Mortgagor herebyagrees further that in all cases, attorney's fees hereby fixed at Ten Per cent (10%) of the totalindebtedness then unpaid which in no case shall be less than P100.00 exclusive of all fees allowedby law, and the expenses of collection shall be the obligation of the Mortgagor and shall withpriority, be paid to the Mortgagee out of any sums realized as rents and profits derived from themortgaged property or from the proceeds realized from the sale of the said property and thismortgage shall likewise stand as security therefor. . . .We find the above stipulation to pay attorney's fees clear enough to cover both cases of foreclosure salementioned thereunder, i.e., judicially or extra-judicially. While the phrase "in all cases" appears to be partof the second sentence, a reading of the whole context of the stipulation would readily show that itlogically refers to extra-judicial foreclosure found in the first sentence and to judicial foreclosure mentionedin the next sentence. And the ambiguity in the stipulation suggested and pointed out by the appellant byreason of the faulty sentence construction should not be made to defeat the otherwise clear intention ofthe parties in the agreement.It is suggested by the appellant, however, that even if the above stipulation to pay attorney's fees wereapplicable to the extra-judicial foreclosure sale of its real properties, still, the award of P5,821.35 forattorney's fees has no legal justification, considering the circumstance that the PNB did not actually spendanything by way of attorney's fees in connection with the sale. In support of this proposition, appellantcites authorities to the effect: (1) that when the mortgagee has neither paid nor incurred any obligation topay an attorney in connection with the foreclosure sale, the claim for such fees should be denied; 2 and (2)that attorney's fees will not be allowed when the attorney conducting the foreclosure proceedings is anofficer of the corporation (mortgagee) who receives a salary for all the legal services performed by him forthe corporation. 3 These authorities are indeed enlightening; but they should not be applied in this case.The very same authority first cited suggests that said principle is not absolute, for there is authority to thecontrary. As to the fact that the foreclosure proceeding's were handled by an attorney of the legal staff ofthe PNB, we are reluctant to exonerate herein appellant from the payment of the stipulated attorney's feeson this ground alone, considering the express agreement between the parties in the mortgage contractunder which appellant became liable to pay the same. At any rate, we find merit in the contention of theappellant that the award of P5,821.35 in favor of the PNB as attorney's fees is unconscionable andunreasonable, considering that all that the branch attorney of the said bank did in connection with theforeclosure sale of the real property was to file a petition with the provincial sheriff of Camarines Norterequesting the latter to sell the same in accordance with the provisions of Act 3135.
The principle that courts should reduce stipulated attorney's fees whenever it is found under thecircumstances of the case that the same is unreasonable, is now deeply rooted in this jurisdiction toentertain any serious objection to it. Thus, this Court has explained:But the principle that it may be lawfully stipulated that the legal expenses involved in the collectionof a debt shall be defrayed by the debtor does not imply that such stipulations must be enforced inaccordance with the terms, no matter how injurious or oppressive they may be. The lawful purposeto be accomplished by such a stipulation is to permit the creditor to receive the amount due himunder his contract without a deduction of the expenses caused by the delinquency of the debtor. Itshould not be permitted for him to convert such a stipulation into a source of speculative profit atthe expense of the debtor.Contracts for attorney's services in this jurisdiction stands upon an entirely different footing fromcontracts for the payment of compensation for any other services. By express provision of section29 of the Code of Civil Procedure, an attorney is not entitled in the absence of express contract torecover more than a reasonable compensation for his services; and even when an express contractis made the court can ignore it and limit the recovery to reasonable compensation if the amount ofthe stipulated fee is found by the court to be unreasonable. This is a very different rule from thatannounced in section 1091 of the Civil Code with reference to the obligation of contracts in general,where it is said that such obligation has the force of law between the contracting parties. Had theplaintiff herein made an express contract to pay his attorney an uncontingent fee of P2,115.25 forthe services to be rendered in reducing the note here in suit to judgment, it would not have beenenforced against him had he seen fit to oppose it, as such a fee is obviously far greater than isnecessary to remunerate the attorney for the work involved and is therefore unreasonable. In orderto enable the court to ignore an express contract for an attorney's fees, it is not necessary to show,as in other contracts, that it is contrary to morality or public policy (Art. 1255, Civil Code). It isenough that it is unreasonable or unconscionable. 4Since then this Court has invariably fixed counsel fees on a quantum meruit basis whenever the feesstipulated appear excessive, unconscionable, or unreasonable, because a lawyer is primarily a court officercharged with the duty of assisting the court in administering impartial justice between the parties, andhence, the fees should be subject to judicial control. Nor should it be ignored that sound public policydemands that courts disregard stipulations for counsel fees, whenever they appear to be a source ofspeculative profit at the expense of the debtor or mortgagor. 5 And it is not material that the present actionis between the debtor and the creditor, and not between attorney and client. As court have power to fixthe fee as between attorney and client, it must necessarily have the right to say whether a stipulation likethis, inserted in a mortgage contract, is valid. 6In determining the compensation of an attorney, the following circumstances should be considered: theamount and character of the services rendered; the responsibility imposed; the amount of money or thevalue of the property affected by the controversy, or involved in the employment; the skill and experiencecalled for in the performance of the service; the professional standing of the attorney; the results secured;and whether or not the fee is contingent or absolute, it being a recognized rule that an attorney mayproperly charge a much larger fee when it is to be contingent than when it is not. 7 From the stipulation inthe mortgage contract earlier quoted, it appears that the agreed fee is 10% of the total indebtedness,irrespective of the manner the foreclosure of the mortgage is to be effected. The agreement is perhaps fairenough in case the foreclosure proceedings is prosecuted judicially but, surely, it is unreasonable when, asin this case, the mortgage was foreclosed extra-judicially, and all that the attorney did was to file a petitionfor foreclosure with the sheriff concerned. It is to be assumed though, that the said branch attorney of thePNB made a study of the case before deciding to file the petition for foreclosure; but even with this inmind, we believe the amount of P5,821.35 is far too excessive a fee for such services. Considering theabove circumstances mentioned, it is our considered opinion that the amount of P1,000.00 would be morethan sufficient to compensate the work aforementioned.The next issue raised deals with the claim that the proceeds of the sale of the real properties alonetogether with the amount it remitted to the PNB later was more than sufficient to liquidate its totalobligation to herein appellee bank. Again, we find merit in this claim. From the foregoing discussion of thefirst two errors assigned, and for purposes of determining the total obligation of herein appellant to thePNB as of November 21, 1961 when the real estate mortgage was foreclosed, we have the followingillustration in support of this conclusion:1wph1.t
A. I.
Principal Loan(a) Promissory note dated August 2, 1956
P27,500.00
(1) Interest at 6% per annum from Aug. 2, 1956 to Nov. 21, 1961(b) Promissory note dated October 19, 1956
P15,500.00
(1) Interest at 6% per annum from Oct.19, 1956 to Nov. 21, 1961II.
III.
Attorney's fee
8,751.784,734.0810.001,000.00
P57,495.86
B. I.
Proceeds of the foreclosure sale of the real estate mortgage on Nov. 21, 1961
II.
P56,908.00738.59
P57,646.59
P 150.73========
From the foregoing illustration or computation, it is clear that there was no further necessity to foreclosethe mortgage of herein appellant's chattels on December 21, 1961; and on this ground alone, we maydeclare the sale of appellant's chattels on the said date, illegal and void. But we take into consideration thefact that the PNB must have been led to believe that the stipulated 10% of the unpaid loan for attorney'sfees in the real estate mortgage was legally maintainable, and in accordance with such belief, hereinappellee bank insisted that the proceeds of the sale of appellant's real property was deficient to liquidatethe latter's total indebtedness. Be that as it may, however, we still find the subsequent sale of hereinappellant's chattels illegal and objectionable on other grounds.That appellant vigorously objected to the foreclosure of its chattel mortgage after the foreclosure of its realestate mortgage on November 21, 1961, can not be doubted, as shown not only by its letter to the PNB onNovember 19, 1961, but also in its letter to the provincial sheriff of Camarines Norte on the same date.These letters were followed by another letter to the appellee bank on December 14, 1961, wherein hereinappellant, in no uncertain terms, reiterated its objection to the scheduled sale of its chattels on December21, 1961 at Jose Panganiban, Camarines Norte for the reasons therein stated that: (1) it had settled in fullits total obligation to the PNB by the sale of the real estate and its subsequent remittance of the amount ofP738.59; and (2) that the contemplated sale at Jose Panganiban would violate their agreement embodiedunder paragraph (i) in the Chattel Mortgage which provides as follows:(i) In case of both judicial and extra-judicial foreclosure under Act 1508, as amended, the partieshereto agree that the corresponding complaint for foreclosure or the petition for sale should be filedwith the courts or the sheriff of the City of Manila, as the case may be; and that the Mortgagor shallpay attorney's fees hereby fixed at ten per cent (10%) of the total indebtedness then unpaid but inno case shall it be less than P100.00, exclusive of all costs and fees allowed by law and of otherexpenses incurred in connection with the said foreclosure. [Emphasis supplied]Notwithstanding the abovequoted agreement in the chattel mortgage contract, and in utter disregard ofthe objection of herein appellant to the sale of its chattels at Jose Panganiban, Camarines Norte and not inthe City of Manila as agreed upon, the PNB proceeded with the foreclosure sale of said chattels. The trialcourt, however, justified said action of the PNB in the decision appealed from in the following rationale:
While it is true that it was stipulated in the chattel mortgage contract that a petition for the extrajudicial foreclosure thereof should be filed with the Sheriff of the City of Manila, nevertheless, theeffect thereof was merely to provide another place where the mortgage chattel could be sold inaddition to those specified in the Chattel Mortgage Law. Indeed, a stipulation in a contract cannotabrogate much less impliedly repeal a specific provision of the statute. Considering that Section 14of Act No. 1508 vests in the mortgagee the choice where the foreclosure sale should be held,hence, in the case under consideration, the PNB had three places from which to select, namely: (1)the place of residence of the mortgagor; (2) the place of the mortgaged chattels were situated; and(3) the place stipulated in the contract. The PNB selected the second and, accordingly, theforeclosure sale held in Jose Panganiban, Camarines Norte, was legal and valid.To the foregoing conclusion, We disagree. While the law grants power and authority to the mortgagee tosell the mortgaged property at a public place in the municipality where the mortgagor resides or where theproperty is situated, 8 this Court has held that the sale of a mortgaged chattel may be made in a placeother than that where it is found, provided that the owner thereof consents thereto; or that there is anagreement to this effect between the mortgagor and the mortgagee. 9 But when, as in this case, the partiesagreed to have the sale of the mortgaged chattels in the City of Manila, which, any way, is the residence ofthe mortgagor, it cannot be rightly said that mortgagee still retained the power and authority to selectfrom among the places provided for in the law and the place designated in their agreement over theobjection of the mortgagor. In providing that the mortgaged chattel may be sold at the place of residenceof the mortgagor or the place where it is situated, at the option of the mortgagee, the law clearlycontemplated benefits not only to the mortgagor but to the mortgagee as well. Their right arisingthereunder, however, are personal to them; they do not affect either public policy or the rights of thirdpersons. They may validly be waived. So, when herein mortgagor and mortgagee agreed in the mortgagecontract that in cases of both judicial and extra-judicial foreclosure under Act 1508, as amended, thecorresponding complaint for foreclosure or the petition for sale should be filed with the courts or theSheriff of Manila, as the case may be, they waived their corresponding rights under the law. The correlativeobligation arising from that agreement have the force of law between them and should be complied with ingood faith. 10By said agreement the parties waived the legal venue, and such waiver is valid and legallyeffective, because it, was merely a personal privilege they waived, which is not contrary, to publicpolicy or to the prejudice of third persons. It is a general principle that a person may renounce anyright which the law gives unless such renunciation is expressly prohibited or the right conferred is ofsuch nature that its renunciation would be against public policy. 11On the other hand, if a place of sale is specified in the mortgage and statutory requirements inregard thereto are complied with, a sale is properly conducted in that place. Indeed, in the absenceof a statute to the contrary, a sale conducted at a place other than that stipulated for in themortgage is invalid, unless the mortgagor consents to such sale. 12Moreover, Section 14 of Act 1508, as amended, provides that the officer making the sale should make areturn of his doings which shall particularly describe the articles sold and the amount received from eacharticle. From this, it is clear that the law requires that sale be made article by article, otherwise, it would beimpossible for him to state the amount received for each item. This requirement was totally disregarded bythe Deputy Sheriff of Camarines Norte when he sold the chattels in question in bulk, notwithstanding thefact that the said chattels consisted of no less than twenty different items as shown in the bill ofsale. 13 This makes the sale of the chattels manifestly objectionable. And in the absence of any evidence toshow that the mortgagor had agreed or consented to such sale in gross, the same should be set aside.It is said that the mortgagee is guilty of conversion when he sells under the mortgage but not inaccordance with its terms, or where the proceedings as to the sale of foreclosure do not comply with thestatute. 14 This rule applies squarely to the facts of this case where, as earlier shown, herein appellee bankinsisted, and the appellee deputy sheriff of Camarines Norte proceeded with the sale of the mortgagedchattels at Jose Panganiban, Camarines Norte, in utter disregard of the valid objection of the mortgagorthereto for the reason that it is not the place of sale agreed upon in the mortgage contract; and the saiddeputy sheriff sold all the chattels (among which were a skagit with caterpillar engine, three GMC 6 x 6trucks, a Herring Hall Safe, and Sawmill equipment consisting of a 150 HP Murphy Engine, plainer, largecircular saws etc.) as a single lot in violation of the requirement of the law to sell the same article byarticle. The PNB has resold the chattels to another buyer with whom it appears to have actively cooperated
in subsequently taking possession of and removing the chattels from appellant compound by force, asshown by the circumstance that they had to take along PC soldiers and municipal policemen of JosePanganiban who placed the chief security officer of the premises in jail to deprive herein appellant of itspossession thereof. To exonerate itself of any liability for the breach of peace thus committed, the PNBwould want us to believe that it was the subsequent buyer alone, who is not a party to this case, that wasresponsible for the forcible taking of the property; but assuming this to be so, still the PNB cannot escapeliability for the conversion of the mortgaged chattels by parting with its interest in the property. Neitherwould its claim that it afterwards gave a chance to herein appellant to repurchase or redeem the chattels,improve its position, for the mortgagor is not under obligation to take affirmative steps to repossess thechattels that were converted by the mortgagee. 15 As a consequence of the said wrongful acts of the PNBand the Deputy Sheriff of Camarines Norte, therefore, We have to declare that herein appellant is entitledto collect from them, jointly and severally, the full value of the chattels in question at the time they wereillegally sold by them. To this effect was the holding of this Court in a similar situation. 16The effect of this irregularity was, in our opinion to make the plaintiff liable to the defendant for thefull value of the truck at the time the plaintiff thus carried it off to be sold; and of course, theburden is on the defendant to prove the damage to which he was thus subjected. . . .This brings us to the problem of determining the value of the mortgaged chattels at the time of their salein 1961. The trial court did not make any finding on the value of the chattels in the decision appealed fromand denied altogether the right of the appellant to recover the same. We find enough evidence of record,however, which may be used as a guide to ascertain their value. The record shows that at the time hereinappellant applied for its loan with the PNB in 1956, for which the chattels in question were mortgaged aspart of the security therefore, herein appellant submitted a list of the chattels together with its applicationfor the loan with a stated value of P107,115.85. An official of the PNB made an inspection of the chattels inthe same year giving it an appraised value of P42,850.00 and a market value of P85,700.00. 17 The samechattels with some additional equipment acquired by herein appellant with part of the proceeds of the loanwere reappraised in a re-inspection conducted by the same official in 1958, in the report of which he gaveall the chattels an appraised value of P26,850.00 and a market value of P48,200.00. 18 Another reinspection report in 1959 gave the appraised value as P19,400.00 and the market value atP25,600.00. 19 The said official of the PNB who made the foregoing reports of inspection and re-inspectionstestified in court that in giving the values appearing in the reports, he used a conservative method ofappraisal which, of course, is to be expected of an official of the appellee bank. And it appears that thevalues were considerably reduced in all the re-inspection reports for the reason that when he went toherein appellant's premises at the time, he found the chattels no longer in use with some of the heavierequipments dismantled with parts thereof kept in the bodega; and finding it difficult to ascertain the valueof the dismantled chattels in such condition, he did not give them anymore any value in his reports.Noteworthy is the fact, however, that in the last re-inspection report he made of the chattels in 1961, just afew months before the foreclosure sale, the same inspector of the PNB reported that the heavy equipmentof herein appellant were "lying idle and rusty" but were "with a shed free from rains" 20 showing thatalthough they were no longer in use at the time, they were kept in a proper place and not exposed to theelements. The President of the appellant company, on the other hand, testified that its caterpillar (tractor)alone is worth P35,000.00 in the market, and that the value of its two trucks acquired by it with part of theproceeds of the loan and included as additional items in the mortgaged chattels were worth no less thanP14,000.00. He likewise appraised the worth of its Murphy engine at P16,000.00 which, according to him,when taken together with the heavy equipments he mentioned, the sawmill itself and all other equipmentforming part of the chattels under consideration, and bearing in mind the current cost of equipments thesedays which he alleged to have increased by about five (5) times, could safely be estimated at P120,000.00.This testimony, except for the appraised and market values appearing in the inspection and re-inspectionreports of the PNB official earlier mentioned, stand uncontroverted in the record; but We are not inclined toaccept such testimony at its par value, knowing that the equipments of herein appellant had been idle andunused since it stopped operating its sawmill in 1958 up to the time of the sale of the chattels in 1961. Wehave no doubt that the value of chattels was depreciated after all those years of inoperation, althoughfrom the evidence aforementioned, We may also safely conclude that the amount of P4,200.00 for whichthe chattels were sold in the foreclosure sale in question was grossly unfair to the mortgagor. Considering,however, the facts that the appraised value of P42,850.00 and the market value of P85,700.00 originallygiven by the PNB official were admittedly conservative; that two 6 x 6 trucks subsequently bought by theappellant company had thereafter been added to the chattels; and that the real value thereof, althoughdepreciated after several years of inoperation, was in a way maintained because the depreciation is off-setby the marked increase in the cost of heavy equipment in the market, it is our opinion that the marketvalue of the chattels at the time of the sale should be fixed at the original appraised value of P42,850.00.
Herein appellant's claim for moral damages, however, seems to have no legal or factual basis. Obviously,an artificial person like herein appellant corporation cannot experience physical sufferings, mental anguish,fright, serious anxiety, wounded feelings, moral shock or social humiliation which are basis of moraldamages. 21 A corporation may have a good reputation which, if besmirched, may also be a ground for theaward of moral damages. The same cannot be considered under the facts of this case, however, not onlybecause it is admitted that herein appellant had already ceased in its business operation at the time of theforeclosure sale of the chattels, but also for the reason that whatever adverse effects of the foreclosuresale of the chattels could have upon its reputation or business standing would undoubtedly be the samewhether the sale was conducted at Jose Panganiban, Camarines Norte, or in Manila which is the placeagreed upon by the parties in the mortgage contract.But for the wrongful acts of herein appellee bank and the deputy sheriff of Camarines Norte in proceedingwith the sale in utter disregard of the agreement to have the chattels sold in Manila as provided for in themortgage contract, to which their attentions were timely called by herein appellant, and in disposing of thechattels in gross for the miserable amount of P4,200.00, herein appellant should be awarded exemplarydamages in the sum of P10,000.00. The circumstances of the case also warrant the award of P3,000.00 asattorney's fees for herein appellant.WHEREFORE AND CONSIDERING ALL THE FOREGOING, the decision appealed from should be, as hereby, itis set aside. The Philippine National Bank and the Deputy Sheriff of the province of Camarines Norte areordered to pay, jointly and severally, to Mambulao Lumber Company the total amount of P56,000.73,broken as follows: P150.73 overpaid by the latter to the PNB, P42,850.00 the value of the chattels at thetime of the sale with interest at the rate of 6% per annum from December 21, 1961, until fully paid,P10,000.00 in exemplary damages, and P3,000.00 as attorney's fees. Costs against both appellees.Concepcion, C.J., Reyes, J.B.L., Dizon, Makalintal, Zaldivar, Sanchez, Castro and Fernando, JJ., concur.Bengzon, J.P. J., took no part.
BELLOSILLO, J.:This was gruesome murder in a main thoroughfare an hour before sundown. A hapless foreign religiousminister was riddled with bullets, his head shattered into bits and pieces amidst the revelling of hisexecutioners as they danced and laughed around their quarry, chanting the tune "Mutya Ka Baleleng", apopular regional folk song, kicking and scoffing at his prostrate, miserable, spiritless figure that wasgasping its last. Seemingly unsatiated with the ignominy of their manslaughter, their leader picked uppieces of the splattered brain and mockingly displayed them before horrified spectators. Some accountsswear that acts of cannibalism ensued, although they were not sufficiently demonstrated. However, fortheir outrageous feat, the gangleader already earned the monicker "cannibal priest-killer" But, what isindubitable is that Fr. Tulio Favali 1 was senselessly killed for no apparent reason than that he was one ofthe Italian Catholic missionaries laboring in heir vineyard in the hinterlands of Mindanao. 2In the aftermath of the murder, police authorities launched a massive manhunt which resulted in thecapture of the perpetrators except Arsenio Villamor, Jr., and two unidentified persons who eluded arrestand still remain at large.Informations for Murder, 3 Attempted Murder 4 and Arson 5 were accordingly filed against those responsiblefor the frenzied orgy of violence that fateful day of 11 April 1985. As these cases arose from the sameoccasion, they were all consolidated in Branch 17 of the Regional Trial Court of Kidapawan, Cotabato. 6After trial, the court a quo held WHEREFORE . . . the Court finds the accused Norberto Manero, Jr. alias Commander Bucay,Edilberto Manero alias Edil, Elpidio Manero, Severino Lines, Rudy Lines, Rodrigo Espia aliasRudy, Efren Pleago and Roger Bedao GUILTY beyond reasonable doubt of the offense ofMurder, and with the aggravating circumstances of superior strength and treachery, herebysentences each of them to a penalty of imprisonment of reclusion perpetua; to pay thePontifical Institute of Foreign Mission (PIME) Brothers, the congregation to which Father TulioFavali belonged, a civil indemnity of P12,000.00; attorney's fees in the sum of P50,000.00 foreach of the eight (8) accused or a total sum of P400,000.00; court appearance fee ofP10,000.00 for every day the case was set for trial; moral damages in the sum ofP100,000.00; and to pay proportionately the costs.Further, the Court finds the accused Norberto Manero, Jr. alias Commander Bucay GUILTYbeyond reasonable doubt of the offense of Arson and with the application of theIndeterminate Sentence Law, hereby sentences him to an indeterminate penalty of
imprisonment of not less than four (4) years, nine (9) months, one (1) day of prisioncorreccional, as minimum, to six (6) years of prision correccional, as maximum, and toindemnify the Pontifical Institute of Foreign Mission (PIME) Brothers, the congregation towhich Father Tulio Favali belonged, the sum of P19,000.00 representing the value of themotorcycle and to pay the costs.Finally, the Court finds the accused Norberto Manero, Jr., alias Commander Bucay, EdilbertoManero alias Edil, Elpidio Manero, Severino Lines, Rudy Lines, Rodrigo Espia alias Rudy, EfrenPleago and Roger Bedao GUILTY beyond reasonable doubt of the offense of AttemptedMurder and with the application of the Indeterminate Sentence Law, hereby sentences eachof them to an indeterminate penalty of imprisonment of not less than two (2) years, four (4)months and one (1) day of prision correccional, and minimum, to eight (8) years and twenty(20) days of prision mayor, as maximum, and to pay the complainant Rufino Robles the sumof P20,000.00 as attorney's fees and P2,000.00 as court appearance fee for every day oftrial and to pay proportionately the costs.The foregoing penalties shall be served by the said accused successively in the order of theirrespective severity in accordance with the provisions of Article 70 of the Revised Penal Code,as amended. 7From this judgment of conviction only accused Severino Lines, Rudy Lines, Efren Pleago and RogerBedao appealed with respect to the cases for Murder and Attempted Murder. The Manero brothers as wellas Rodrigo Espia did not appeal; neither did Norberto Manero, Jr., in the Arson case. Consequently, thedecision as against them already became final.Culled from the records, the facts are: On 11 April 1985, around 10:00 o'clock in the morning, the Manerobrothers Norberto Jr., Edilberto and Elpidio, along with Rodrigo Espia, Severino Lines, Rudy Lines, EfrenPleago and Roger Bedao, were inside the eatery of one Reynaldo Diocades at Km. 125, La Esperanza,Tulunan, Cotabato. They were conferring with Arsenio Villamor, Jr., private secretary to the Municipal Mayorof Tulunan, Cotabato, and his two (2) unidentified bodyguards. Plans to liquidate a number of suspectedcommunist sympathizers were discussed. Arsenio Villamor, Jr. scribbled on a cigarette wrapper thefollowing "NPA v. NPA, starring Fr. Peter, Domingo Gomez, Bantil, Fred Gapate, Rene alias Tabagac andVillaning." "Fr. Peter" is Fr. Peter Geremias, an Italian priest suspected of having links with the communistmovement; "Bantil" is Rufino Robles, a Catholic lay leader who is the complaining witness in the AttemptedMurder; Domingo Gomez is another lay leader, while the others are simply "messengers". On the sameoccasion, the conspirators agreed to Edilberto Manero's proposal that should they fail to kill Fr. PeterGeremias, another Italian priest would be killed in his stead. 8At about 1:00 o'clock that afternoon, Elpidio Manero with two (2) unidentified companions nailed a placardon a street-post beside the eatery of Deocades. The placard bore the same inscriptions as those found onthe cigarette wrapper except for the additional phrase "versus Bucay, Edil and Palo." Some two (2) hourslater, Elpidio also posted a wooden placard bearing the same message on a street cross-sign close to theeatery. 9Later, at 4:00 o'clock, the Manero brothers, together with Espia and the four (4) appellants, all withassorted firearms, proceeded to the house of "Bantil", their first intended victim, which was also in thevicinity of Deocades'carinderia. They were met by "Bantil" who confronted them why his name wasincluded in the placards. Edilberto brushed aside the query; instead, he asked "Bantil" if he had anyqualms about it, and without any provocation, Edilberto drew his revolver and fired at the forehead of"Bantil". "Bantil" was able to parry the gun, albeit his right finger and the lower portion of his right earwere hit. Then they grappled for its possession until "Bantil" was extricated by his wife from the fray. But,as he was running away, he was again fired upon by Edilberto. Only his trousers were hit. "Bantil" howevermanaged to seek refuge in the house of a certain Domingo Gomez. 10 Norberto, Jr., ordered his men to
surround the house and not to allow any one to get out so that "Bantil" would die of hemorrhage. ThenEdilberto went back to the restaurant of Deocades and pistol-whipped him on the face and accused him ofbeing a communist coddler, while appellants and their cohorts relished the unfolding drama. 11Moments later, while Deocades was feeding his swine, Edilberto strewed him with a burst of gunfire fromhis M-14 Armalite. Deocades cowered in fear as he knelt with both hands clenched at the back of his head.This again drew boisterous laughter and ridicule from the dreaded desperados.At 5:00 o'clock, Fr. Tulio Favali arrived at Km. 125 on board his motorcycle. He entered the house of Gomez.While inside, Norberto, Jr., and his co-accused Pleago towed the motorcycle outside to the center of thehighway. Norberto, Jr., opened the gasoline tank, spilled some fuel, lit a fire and burned the motorcycle. Asthe vehicle was ablaze, the felons raved and rejoiced. 12Upon seeing his motorcycle on fire, Fr. Favali accosted Norberto, Jr. But the latter simply steppedbackwards and executed a thumbs-down signal. At this point, Edilberto asked the priest: "Ano ang gustomo, padre (What is it you want, Father)? Gusto mo, Father, bukon ko ang ulo mo (Do you want me, Father,to break your head)?" Thereafter, in a flash, Edilberto fired at the head of the priest. As Fr. Favali droppedto the ground, his hands clasped against his chest, Norberto, Jr., taunted Edilberto if that was the only wayhe knew to kill a priest. Slighted over the remark, Edilberto jumped over the prostrate body three (3)times, kicked it twice, and fired anew. The burst of gunfire virtually shattered the head of Fr. Favali, causinghis brain to scatter on the road. As Norberto, Jr., flaunted the brain to the terrified onlookers, his brothersdanced and sang "Mutya Ka Baleleng" to the delight of their comrades-in-arms who now took guardedpositions to isolate the victim from possible assistance. 13In seeking exculpation from criminal liability, appellants Severino Lines, Rudy Lines, Efren Pleago andRoger Bedao contend that the trial court erred in disregarding their respective defenses of alibi which, ifproperly appreciated, would tend to establish that there was no prior agreement to kill; that the intendedvictim was Fr. Peter Geremias, not Fr. Tulio Favali; that there was only one (1) gunman, Edilberto; and, thatthere was absolutely no showing that appellants cooperated in the shooting of the victim despite theirproximity at the time to Edilberto.But the evidence on record does not agree with the arguments of accused-appellants.On their defense of alibi, accused brothers Severino and Rudy Lines claim that they were harvesting palaythe whole day of 11 April 1985 some one kilometer away from the crime scene. Accused Roger Bedaoalleges that he was on an errand for the church to buy lumber and nipa in M'lang, Cotabato, that morningof 11 April 1985, taking along his wife and sick child for medical treatment and arrived in La Esperanza,Tulunan, past noontime.Interestingly, all appellants similarly contend that it was only after they heard gunshots that they rushed tothe house of Norberto Manero, Sr., Barangay Captain of La Esperanza, where they were joined by theirfellow CHDF members and co-accused, and that it was only then that they proceeded together to wherethe crime took place at Km. 125.It is axiomatic that the accused interposing the defense of alibi must not only be at some other place butthat it must also be physically impossible for him to be at the scene of the crime at the time of itscommission. 14Considering the failure of appellants to prove the required physical impossibility of being present at thecrime scene, as can be readily deduced from the proximity between the places where accused-appellantswere allegedly situated at the time of the commission of the offenses and the locus criminis, 15 the defenseof alibi is definitely feeble. 16 After all, it has been the consistent ruling of this Court that no physicalimpossibility exists in instances where it would take the accused only fifteen to twenty minutes by jeep or
tricycle, or some one-and-a-half hours by foot, to traverse the distance between the place where heallegedly was at the time of commission of the offense and the scene of the crime. 17 Recently, we ruledthat there can be no physical impossibility even if the distance between two places is merely two (2) hoursby bus.18 More important, it is well-settled that the defense of alibi cannot prevail overthe positive identification of the authors of the crime by the prosecution witnesses. 19In the case before Us, two (2) eyewitnesses, Reynaldo Deocades and Manuel Bantolo, testified that theywere both inside the eatery at about 10:00 o'clock in the morning of 11 April 1985 when the Manerobrothers, together with appellants, first discussed their plan to kill some communist sympathizers. Thewitnesses also testified that they still saw the appellants in the company of the Manero brothers at 4:00o'clock in the afternoon when Rufino Robles was shot. Further, at 5:00 o'clock that same afternoon,appellants were very much at the scene of the crime, along with the Manero brothers, when Fr. Favali wasbrutally murdered. 20 Indeed, in the face of such positive declarations that appellants were at the locuscriminis from 10:00 o'clock in the morning up to about 5:00 o'clock in the afternoon, the alibi of appellantsthat they were somewhere else, which is negative in nature, cannot prevail. 21 The presence of appellantsin the eatery at Km. 125 having been positively established, all doubts that they were not privy to the plotto liquidate alleged communist sympathizers are therefore removed. There was direct proof to link them tothe conspiracy.There is conspiracy when two or more persons come to an agreement to commit a crime and decide tocommit it. 22It is not essential that all the accused commit together each and every act constitutive of theoffense. 23 It is enough that an accused participates in an act or deed where there is singularity of purpose,and unity in its execution is present. 24The findings of the court a quo unmistakably show that there was indeed a community of design asevidenced by the concerted acts of all the accused. Thus The other six accused, 25 all armed with high powered firearms, were positively identifiedwith Norberto Manero, Jr. and Edilberto Manero in the carinderia of Reynaldo Deocades in LaEsperanza, Tulunan, Cotabato at 10:00 o'clock in the morning of 11 April 1985 morning . . .they were outside of the carinderia by the window near the table where Edilberto Manero,Norberto Manero, Jr., Jun Villamor, Elpidio Manero and unidentified members of the airbornefrom Cotabato were grouped together. Later that morning, they all went to the cockhousenearby to finish their plan and drink tuba. They were seen again with Edilberto Manero andNorberto Manero, Jr., at 4:00 o'clock in the afternoon of that day near the house of RufinoRobles (Bantil) when Edilberto Manero shot Robles. They surrounded the house of DomingoGomez where Robles fled and hid, but later left when Edilberto Manero told them to leave asRobles would die of hemorrhage. They followed Fr. Favali to Domingo Gomez' house,witnessed and enjoyed the burning of the motorcycle of Fr. Favali and later stood guard withtheir firearms ready on the road when Edilberto Manero shot to death Fr. Favali. Finally, theyjoined Norberto Manero, Jr. and Edilberto Manero in their enjoyment and merriment on thedeath of the priest.26From the foregoing narration of the trial court, it is clear that appellants were not merely innocentbystanders but were in fact vital cogs in perpetrating the savage murder of Fr. Favali and the attemptedmurder of Rufino Robles by the Manero brothers and their militiamen. For sure, appellants all assumed afighting stance to discourage if not prevent any attempt to provide assistance to the fallen priest. Theysurrounded the house of Domingo Gomez to stop Robles and the other occupants from leaving so that thewounded Robles may die of hemorrhage. 27Undoubtedly, these were overt acts to ensure success of thecommission of the crimes and in furtherance of the aims of the conspiracy. The appellants acted in concertin the murder of Fr. Favali and in the attempted murder of Rufino Robles. While accused-appellants may nothave delivered the fatal shots themselves, their collective action showed a common intent to commit thecriminal acts.
While it may be true that Fr. Favali was not originally the intended victim, as it was Fr. Peter Geremiaswhom the group targetted for the kill, nevertheless, Fr. Favali was deemed a good substitute in the murderas he was an Italian priest. On this, the conspirators expressly agreed. As witness Manuel Bantoloexplained 28 Q Aside from those persons listed in that paper to be killed, were there otherpersons who were to be liquidated?A There were some others.Q Who were they?A They said that if they could not kill those persons listed in that paper thenthey will (sic) kill anyone so long as he is (sic) an Italian and if they could notkill the persons they like to kill they will (sic) make Reynaldo Deocades as theirsample.That appellants and their co-accused reached a common understanding to kill another Italian priest in theevent that Fr. Peter Geremias could not be spotted was elucidated by Bantolo thus 29 Q Who suggested that Fr. Peter be the first to be killed?A All of them in the group.Q What was the reaction of Norberto Manero with respect to the plan to kill Fr.Peter?A He laughed and even said, "amo ina" meaning "yes, we will kill him ahead."xxx xxx xxxQ What about Severino Lines? What was his reaction?A He also laughed and so conformed and agreed to it.Q Rudy Lines.A He also said "yes".Q What do you mean "yes"?A He also agreed and he was happy and said "yes" we will kill him.xxx xxx xxxQ What about Efren Pleago?A He also agreed and even commented laughing "go ahead".Q Roger Bedao, what was his reaction to that suggestion that should they failto kill Fr. Peter, they will (sic) kill anybody provided he is an Italian and if not,they will (sic) make Reynaldo Deocades an example?
P9,599.072,399.77
70.00500.00
The Club wrote the Collector, requesting for the cancellation of the assessment. The request having beendenied, the Club filed the instant petition for review.The dominant issues involved in this case are twofold:1. Whether the respondent Club is liable for the payment of the sum of 12,068.84, as fixed and percentagetaxes and surcharges prescribed in sections 182, 183 and 191 of the Tax Code, under which theassessment was made, in connection with the operation of its bar and restaurant, during the periodsmentioned above; and2. Whether it is liable for the payment of the sum of P500.00 as compromise penalty.
Section 182, of the Tax Code states, "Unless otherwise provided, every person engaging in a business onwhich the percentage tax is imposed shall pay in full a fixed annual tax of ten pesos for each calendar yearor fraction thereof in which such person shall engage in said business." Section 183 provides in generalthat "the percentage taxes on business shall be payable at the end of each calendar quarter in the amountlawfully due on the business transacted during each quarter; etc." And section 191, same Tax Code,provides "Percentage tax . . . Keepers of restaurants, refreshment parlors and other eating places shall paya tax three per centum, and keepers of bar and cafes where wines or liquors are served five per centum oftheir gross receipts . . .". It has been held that the liability for fixed and percentage taxes, as provided bythese sections, does not ipso facto attach by mere reason of the operation of a bar and restaurant. For theliability to attach, the operator thereof must be engaged in the business as a barkeeper and restaurateur.The plain and ordinary meaning of business is restricted to activities or affairs where profit is the purposeor livelihood is the motive, and the term business when used without qualification, should be construed inits plain and ordinary meaning, restricted to activities for profit or livelihood (The Coll. of Int. Rev. v. ManilaLodge No. 761 of the BPOE [Manila Elks Club] & Court of Tax Appeals, G.R. No. L-11176, June 29, 1959,giving full definitions of the word "business"; Coll. of Int. Rev. v. Sweeney, et al. [International Club of Iloilo,Inc.], G.R. No. L-12178, Aug. 21, 1959, the facts of which are similar to the ones at bar; Manila Polo Club v.B. L. Meer, etc., No. L-10854, Jan. 27, 1960).Having found as a fact that the Club was organized to develop and cultivate sports of all class anddenomination, for the healthful recreation and entertainment of its stockholders and members; that uponits dissolution, its remaining assets, after paying debts, shall be donated to a charitable PhilippineInstitution in Cebu; that it is operated mainly with funds derived from membership fees and dues; that theClub's bar and restaurant catered only to its members and their guests; that there was in fact no cashdividend distribution to its stockholders and that whatever was derived on retail from its bar andrestaurant was used to defray its overall overhead expenses and to improve its golf-course (cost-plusexpenses-basis), it stands to reason that the Club is not engaged in the business of an operator of bar andrestaurant (same authorities, cited above).It is conceded that the Club derived profit from the operation of its bar and restaurant, but such fact doesnot necessarily convert it into a profit-making enterprise. The bar and restaurant are necessary adjuncts ofthe Club to foster its purposes and the profits derived therefrom are necessarily incidental to the primaryobject of developing and cultivating sports for the healthful recreation and entertainment of thestockholders and members. That a Club makes some profit, does not make it a profit-making Club. As hasbeen remarked a club should always strive, whenever possible, to have surplus (Jesus Sacred Heart Collegev. Collector of Int. Rev., G.R. No. L-6807, May 24, 1954; Collector of Int. Rev. v. Sinco Educational Corp., G.R.No. L-9276, Oct. 23, 1956).1wph1.tIt is claimed that unlike the two cases just cited (supra), which are non-stock, the appellee Club is a stockcorporation. This is unmeritorious. The facts that the capital stock of the respondent Club is divided intoshares, does not detract from the finding of the trial court that it is not engaged in the business of operatorof bar and restaurant. What is determinative of whether or not the Club is engaged in such business is itsobject or purpose, as stated in its articles and by-laws. It is a familiar rule that the actual purpose is notcontrolled by the corporate form or by the commercial aspect of the business prosecuted, but may beshown by extrinsic evidence, including the by-laws and the method of operation. From the extrinsicevidence adduced, the Tax Court concluded that the Club is not engaged in the business as a barkeeperand restaurateur.Moreover, for a stock corporation to exist, two requisites must be complied with, to wit: (1) a capital stockdivided into shares and (2) an authority to distribute to the holders of such shares, dividends or allotmentsof the surplus profits on the basis of the shares held (sec. 3, Act No. 1459). In the case at bar, nowhere inits articles of incorporation or by-laws could be found an authority for the distribution of its dividends orsurplus profits. Strictly speaking, it cannot, therefore, be considered a stock corporation, within thecontemplation of the corporation law.A tax is a burden, and, as such, it should not be deemed imposed upon fraternal, civic, non-profit, nonstockorganizations, unless the intent to the contrary is manifest and patent" (Collector v. BPOE Elks Club, etal., supra), which is not the case in the present appeal.
Having arrived at the conclusion that respondent Club is not engaged in the business as an operator of abar and restaurant, and therefore, not liable for fixed and percentage taxes, it follows that it is not liablefor any penalty, much less of a compromise penalty.WHEREFORE, the decision appealed from is affirmed without costs.Padilla, Bautista Angelo, Labrador, Concepcion, Reyes, J.B.L., Barrera and Dizon, JJ., concur.Bengzon, C.J., is on leave.
FERNAN, C.J.:In this petition for review on certiorari, petitioners seek to reverse and set aside [1] the decision of theCourt of Appeals dated July l3, 1981, 1 affirming that of the Court of First Instance of Zambales andOlongapo City which denied petitioners' motion to intervene in an annulment suit filed by herein privaterespondent, and [2] its resolution dated September 7, 1981, denying their motion for reconsideration.Petitioners are raising a purely legal question; whether or not respondent Court of Appeals correctly deniedtheir motion for intervention.The facts are not controverted.On February 9, 1979, Adelaida Rodriguez-Magsaysay, widow and special administratix of the estate of thelate Senator Genaro Magsaysay, brought before the then Court of First Instance of Olongapo an actionagainst Artemio Panganiban, Subic Land Corporation (SUBIC), Filipinas Manufacturer's Bank (FILMANBANK)and the Register of Deeds of Zambales. In her complaint, she alleged that in 1958, she and her husbandacquired, thru conjugal funds, a parcel of land with improvements, known as "Pequena Island", covered byTCT No. 3258; that after the death of her husband, she discovered [a] an annotation at the back of TCT No.3258 that "the land was acquired by her husband from his separate capital;" [b] the registration of a Deedof Assignment dated June 25, 1976 purportedly executed by the late Senator in favor of SUBIC, as a resultof which TCT No. 3258 was cancelled and TCT No. 22431 issued in the name of SUBIC; and [c] theregistration of Deed of Mortgage dated April 28, 1977 in the amount of P 2,700,000.00 executed by SUBICin favor of FILMANBANK; that the foregoing acts were void and done in an attempt to defraud the conjugalpartnership considering that the land is conjugal, her marital consent to the annotation on TCT No. 3258was not obtained, the change made by the Register of Deeds of the titleholders was effected without theapproval of the Commissioner of Land Registration and that the late Senator did not execute the purportedDeed of Assignment or his consent thereto, if obtained, was secured by mistake, violence and intimidation.She further alleged that the assignment in favor of SUBIC was without consideration and consequently nulland void. She prayed that the Deed of Assignment and the Deed of Mortgage be annulled and that theRegister of Deeds be ordered to cancel TCT No. 22431 and to issue a new title in her favor.On March 7, 1979, herein petitioners, sisters of the late senator, filed a motion for intervention on theground that on June 20, 1978, their brother conveyed to them one-half (1/2 ) of his shareholdings in SUBICor a total of 416,566.6 shares and as assignees of around 41 % of the total outstanding shares of suchstocks of SUBIC, they have a substantial and legal interest in the subject matter of litigation and that theyhave a legal interest in the success of the suit with respect to SUBIC.On July 26, 1979, the court denied the motion for intervention, and ruled that petitioners have no legalinterest whatsoever in the matter in litigation and their being alleged assignees or transferees of certainshares in SUBIC cannot legally entitle them to intervene because SUBIC has a personality separate anddistinct from its stockholders.
On appeal, respondent Court of Appeals found no factual or legal justification to disturb the findings of thelower court. The appellate court further stated that whatever claims the petitioners have against the lateSenator or against SUBIC for that matter can be ventilated in a separate proceeding, such that with thedenial of the motion for intervention, they are not left without any remedy or judicial relief under existinglaw.Petitioners' motion for reconsideration was denied. Hence, the instant recourse.Petitioners anchor their right to intervene on the purported assignment made by the late Senator of acertain portion of his shareholdings to them as evidenced by a Deed of Sale dated June 20, 1978. 2 Suchtransfer, petitioners posit, clothes them with an interest, protected by law, in the matter of litigation.Invoking the principle enunciated in the case of PNB v. Phil. Veg. Oil Co., 49 Phil. 857,862 & 853(1927), 3petitioners strongly argue that their ownership of 41.66% of the entire outstanding capital stock ofSUBIC entitles them to a significant vote in the corporate affairs; that they are affected by the action of thewidow of their late brother for it concerns the only tangible asset of the corporation and that it appearsthat they are more vitally interested in the outcome of the case than SUBIC.Viewed in the light of Section 2, Rule 12 of the Revised Rules of Court, this Court affirms the respondentcourt's holding that petitioners herein have no legal interest in the subject matter in litigation so as toentitle them to intervene in the proceedings below. In the case of Batama Farmers' Cooperative MarketingAssociation, Inc. v. Rosal, 4 we held: "As clearly stated in Section 2 of Rule 12 of the Rules of Court, to bepermitted to intervene in a pending action, the party must have a legal interest in the matter in litigation,or in the success of either of the parties or an interest against both, or he must be so situated as to beadversely affected by a distribution or other disposition of the property in the custody of the court or anofficer thereof ."To allow intervention, [a] it must be shown that the movant has legal interest in the matter in litigation, orotherwise qualified; and [b] consideration must be given as to whether the adjudication of the rights of theoriginal parties may be delayed or prejudiced, or whether the intervenor's rights may be protected in aseparate proceeding or not. Both requirements must concur as the first is not more important than thesecond. 5The interest which entitles a person to intervene in a suit between other parties must be in the matter inlitigation and of such direct and immediate character that the intervenor will either gain or lose by thedirect legal operation and effect of the judgment. Otherwise, if persons not parties of the action could beallowed to intervene, proceedings will become unnecessarily complicated, expensive and interminable.And this is not the policy of the law. 6The words "an interest in the subject" mean a direct interest in the cause of action as pleaded, and whichwould put the intervenor in a legal position to litigate a fact alleged in the complaint, without theestablishment of which plaintiff could not recover. 7Here, the interest, if it exists at all, of petitioners-movants is indirect, contingent, remote, conjectural,consequential and collateral. At the very least, their interest is purely inchoate, or in sheer expectancy of aright in the management of the corporation and to share in the profits thereof and in the properties andassets thereof on dissolution, after payment of the corporate debts and obligations.While a share of stock represents a proportionate or aliquot interest in the property of the corporation, itdoes not vest the owner thereof with any legal right or title to any of the property, his interest in thecorporate property being equitable or beneficial in nature. Shareholders are in no legal sense the owners ofcorporate property, which is owned by the corporation as a distinct legal person. 8
Petitioners further contend that the availability of other remedies, as declared by the Court of appeals, istotally immaterial to the availability of the remedy of intervention.We cannot give credit to such averment. As earlier stated, that the movant's interest may be protected in aseparate proceeding is a factor to be considered in allowing or disallowing a motion for intervention. It issignificant to note at this juncture that as per records, there are four pending cases involving the partiesherein, enumerated as follows: [1] Special Proceedings No. 122122 before the CFI of Manila, Branch XXII,entitled "Concepcion Magsaysay-Labrador, et al. v. Subic Land Corp., et al.", involving the validity of thetransfer by the late Genaro Magsaysay of one-half of his shareholdings in Subic Land Corporation; [2] CivilCase No. 2577-0 before the CFI of Zambales, Branch III, "Adelaida Rodriguez-Magsaysay v. Panganiban,etc.; Concepcion Labrador, et al. Intervenors", seeking to annul the purported Deed of Assignment in favorof SUBIC and its annotation at the back of TCT No. 3258 in the name of respondent's deceased husband;[3] SEC Case No. 001770, filed by respondent praying, among other things that she be declared in hercapacity as the surviving spouse and administratrix of the estate of Genaro Magsaysay as the solesubscriber and stockholder of SUBIC. There, petitioners, by motion, sought to intervene. Their motion toreconsider the denial of their motion to intervene was granted; [4] SP No. Q-26739 before the CFI of Rizal,Branch IV, petitioners herein filing a contingent claim pursuant to Section 5, Rule 86, Revised Rules ofCourt.9 Petitioners' interests are no doubt amply protected in these cases.Neither do we lend credence to petitioners' argument that they are more interested in the outcome of thecase than the corporation-assignee, owing to the fact that the latter is willing to compromise with widowrespondent and since a compromise involves the giving of reciprocal concessions, the only conceivableconcession the corporation may give is a total or partial relinquishment of the corporate assets. 10Such claim all the more bolsters the contingent nature of petitioners' interest in the subject of litigation.The factual findings of the trial court are clear on this point. The petitioners cannot claim the right tointervene on the strength of the transfer of shares allegedly executed by the late Senator. The corporationdid not keep books and records. 11 Perforce, no transfer was ever recorded, much less effected as toprejudice third parties. The transfer must be registered in the books of the corporation to affect thirdpersons. The law on corporations is explicit. Section 63 of the Corporation Code provides, thus: "Notransfer, however, shall be valid, except as between the parties, until the transfer is recorded in the booksof the corporation showing the names of the parties to the transaction, the date of the transfer, thenumber of the certificate or certificates and the number of shares transferred."And even assuming arguendo that there was a valid transfer, petitioners are nonetheless barred fromintervening inasmuch as their rights can be ventilated and amply protected in another proceeding.WHEREFORE, the instant petition is hereby DENIED. Costs against petitioners.SO ORDERED.Gutierrez, Jr., Bidin and Corte's, JJ., concur.Feliciano, J., is on leave.
CRUZ, J.:We gave limited due course to this petition on the question of the solidary liability of the petitioners withtheir co-defendants in the lower court 1 because of the challenge to the following paragraph in thedispositive portion of the decision of the respondent court: *1. Defendants are hereby ordered to jointly and severally pay the plaintiff the amount ofP50,000.00 for the preparation of the project study and his technical services that led to theorganization of the defendant corporation, plus P10,000.00 attorney's fees; 2The petitioners claim that this order has no support in fact and law because they had no contractwhatsoever with the private respondent regarding the above-mentioned services. Their position is that asmere subsequent investors in the corporation that was later created, they should not be held solidarilyliable with the Filipinas Orient Airways, a separate juridical entity, and with Barretto and Garcia, their codefendants in the lower court, ** who were the ones who requested the said services from the privaterespondent. 3We are not concerned here with the petitioners' co-defendants, who have not appealed the decision of therespondent court and may, for this reason, be presumed to have accepted the same. For purposes ofresolving this case before us, it is not necessary to determine whether it is the promoters of the proposedcorporation, or the corporation itself after its organization, that shall be responsible for the expensesincurred in connection with such organization.The only question we have to decide now is whether or not the petitioners themselvesare also and personally liable for such expenses and, if so, to what extent.The reasons for the said order are given by the respondent court in its decision in this wise:As to the 4th assigned error we hold that as to the remuneration due the plaintiff for thepreparation of the project study and the pre-organizational services in the amount ofP50,000.00, not only the defendant corporation but the other defendants includingdefendants Caram should be jointly and severally liable for this amount. As we above relatedit was upon the request of defendants Barretto and Garcia that plaintiff handled thepreparation of the project study which project study was presented to defendant Caram sothe latter was convinced to invest in the proposed airlines. The project study was revised forpurposes of presentation to financiers and the banks. It was on the basis of this study thatdefendant corporation was actually organized and rendered operational. Defendants Garciaand Caram, and Barretto became members of the Board and/or officers of defendantcorporation. Thus, not only the defendant corporation but all the other defendants who wereinvolved in the preparatory stages of the incorporation, who caused the preparation and/orbenefited from the project study and the technical services of plaintiff must be liable. 4It would appear from the above justification that the petitioners were not really involved in the initial stepsthat finally led to the incorporation of the Filipinas Orient Airways. Elsewhere in the decision, Barretto wasdescribed as "the moving spirit." The finding of the respondent court is that the project study was
undertaken by the private respondent at the request of Barretto and Garcia who, upon its completion,presented it to the petitioners to induce them to invest in the proposed airline. The study could have beenpresented to other prospective investors. At any rate, the airline was eventually organized on the basis ofthe project study with the petitioners as major stockholders and, together with Barretto and Garcia, asprincipal officers.The following portion of the decision in question is also worth considering:... Since defendant Barretto was the moving spirit in the pre-organization work of defendantcorporation based on his experience and expertise, hence he was logically compensated inthe amount of P200,000.00 shares of stock not as industrial partner but more for histechnical services that brought to fruition the defendant corporation. By the same token, Wefind no reason why the plaintiff should not be similarly compensated not only for havingactively participated in the preparation of the project study for several months and itssubsequent revision but also in his having been involved in the pre-organization of thedefendant corporation, in the preparation of the franchise, in inviting the interest of thefinanciers and in the training and screening of personnel. We agree that for these specialservices of the plaintiff the amount of P50,000.00 as compensation is reasonable. 5The above finding bolsters the conclusion that the petitioners were not involved in the initial stages of theorganization of the airline, which were being directed by Barretto as the main promoter. It was he who wasputting all the pieces together, so to speak. The petitioners were merely among the financiers whoseinterest was to be invited and who were in fact persuaded, on the strength of the project study, to invest inthe proposed airline.Significantly, there was no showing that the Filipinas Orient Airways was a fictitious corporation and did nothave a separate juridical personality, to justify making the petitioners, as principal stockholders thereof,responsible for its obligations. As a bona fide corporation, the Filipinas Orient Airways should alone beliable for its corporate acts as duly authorized by its officers and directors.In the light of these circumstances, we hold that the petitioners cannot be held personally liable for thecompensation claimed by the private respondent for the services performed by him in the organization ofthe corporation. To repeat, the petitioners did not contract such services. It was only the results of suchservices that Barretto and Garcia presented to them and which persuaded them to invest in the proposedairline. The most that can be said is that they benefited from such services, but that surely is nojustification to hold them personally liable therefor. Otherwise, all the other stockholders of thecorporation, including those who came in later, and regardless of the amount of their share holdings, wouldbe equally and personally liable also with the petitioners for the claims of the private respondent.The petition is rather hazy and seems to be flawed by an ambiguous ambivalence. Our impression is that itis opposed to the imposition of solidary responsibility upon the Carams but seems to be willing, in a vague,unexpressed offer of compromise, to accept joint liability. While it is true that it does here and theredisclaim total liability, the thrust of the petition seems to be against the imposition of solidary liability onlyrather than against any liability at all, which is what it should have categorically argued.Categorically, the Court holds that the petitioners are not liable at all, jointly or jointly and severally, underthe first paragraph of the dispositive portion of the challenged decision. So holding, we find it unnecessaryto examine at this time the rules on solidary obligations, which the parties-needlessly, as it turns out havebelabored unto death.WHEREFORE, the petition is granted. The petitioners are declared not liable under the challenged decision,which is hereby modified accordingly. It is so ordered.
MELENCIO-HERRERA, J.:The Resolution, dated May 2, 1980, issued by Presidential Executive Assistant Jacobo Clave in O.P. Case No.1459, directing petitioners Palay, Inc. and Alberto Onstott jointly and severally, to refund to privaterespondent, Nazario Dumpit, the amount of P13,722.50 with 12% interest per annum, as resolved by theNational Housing Authority in its Resolution of July 10, 1979 in Case No. 2167, as well as the Resolution ofOctober 28, 1980 denying petitioners' Motion for Reconsideration of said Resolution of May 2, 1980, arebeing assailed in this petition.On March 28, 1965, petitioner Palay, Inc., through its President, Albert Onstott executed in favor of privaterespondent, Nazario Dumpit, a Contract to Sell a parcel of Land (Lot No. 8, Block IV) of the CrestviewHeights Subdivision in Antipolo, Rizal, with an area of 1,165 square meters, - covered by TCT No. 90454,and owned by said corporation. The sale price was P23,300.00 with 9% interest per annum, payable with adownpayment of P4,660.00 and monthly installments of P246.42 until fully paid. Paragraph 6 of thecontract provided for automatic extrajudicial rescission upon default in payment of any monthlyinstallment after the lapse of 90 days from the expiration of the grace period of one month, without needof notice and with forfeiture of all installments paid.Respondent Dumpit paid the downpayment and several installments amounting to P13,722.50. The lastpayment was made on December 5, 1967 for installments up to September 1967.On May 10, 1973, or almost six (6) years later, private respondent wrote petitioner offering to update allhis overdue accounts with interest, and seeking its written consent to the assignment of his rights to acertain Lourdes Dizon. He followed this up with another letter dated June 20, 1973 reiterating the samerequest. Replying petitioners informed respondent that his Contract to Sell had long been rescindedpursuant to paragraph 6 of the contract, and that the lot had already been resold.Questioning the validity of the rescission of the contract, respondent filed a letter complaint with theNational Housing Authority (NHA) for reconveyance with an altenative prayer for refund (Case No. 2167). Ina Resolution, dated July 10, 1979, the NHA, finding the rescission void in the absence of either judicial ornotarial demand, ordered Palay, Inc. and Alberto Onstott in his capacity as President of the corporation,jointly and severally, to refund immediately to Nazario Dumpit the amount of P13,722.50 with 12% interestfrom the filing of the complaint on November 8, 1974. Petitioners' Motion for Reconsideration of saidResolution was denied by the NHA in its Order dated October 23, 1979. 1On appeal to the Office of the President, upon the allegation that the NHA Resolution was contrary to law(O.P. Case No. 1459), respondent Presidential Executive Assistant, on May 2, 1980, affirmed the Resolutionof the NHA. Reconsideration sought by petitioners was denied for lack of merit. Thus, the present petitionwherein the following issues are raised:
IWhether notice or demand is not mandatory under the circumstances and, therefore, maybe dispensed with by stipulation in a contract to sell.IIWhether petitioners may be held liable for the refund of the installment payments made byrespondent Nazario M. Dumpit.IIIWhether the doctrine of piercing the veil of corporate fiction has application to the case atbar.IVWhether respondent Presidential Executive Assistant committed grave abuse of discretion inupholding the decision of respondent NHA holding petitioners solidarily liable for the refundof the installment payments made by respondent Nazario M. Dumpit thereby denyingsubstantial justice to the petitioners, particularly petitioner OnstottWe issued a Temporary Restraining Order on Feb 11, 1981 enjoining the enforcement of the questionedResolutions and of the Writ of Execution that had been issued on December 2, 1980. On October 28, 1981,we dismissed the petition but upon petitioners' motion, reconsidered the dismissal and gave due course tothe petition on March 15, 1982.On the first issue, petitioners maintain that it was justified in cancelling the contract to sell without priornotice or demand upon respondent in view of paragraph 6 thereof which provides6. That in case the BUYER falls to satisfy any monthly installment or any other paymentsherein agreed upon, the BUYER shall be granted a month of grace within which to make thepayment of the t in arrears together with the one corresponding to the said month of grace.-It shall be understood, however, that should the month of grace herein granted to theBUYER expire, without the payment & corresponding to both months having been satisfied,an interest of ten (10%) per cent per annum shall be charged on the amounts the BUYERshould have paid; it is understood further, that should a period of NINETY (90) DAYS elapseto begin from the expiration of the month of grace hereinbefore mentioned, and the BUYERshall not have paid all the amounts that the BUYER should have paid with the correspondinginterest up to the date, the SELLER shall have the right to declare this contract cancelledand of no effect without notice, and as a consequence thereof, the SELLER may dispose ofthe lot/lots covered by this Contract in favor of other persons, as if this contract had neverbeen entered into. In case of such cancellation of this Contract, all the amounts which mayhave been paid by the BUYER in accordance with the agreement, together with all theimprovements made on the premises, shall be considered as rents paid for the use andoccupation of the above mentioned premises and for liquidated damages suffered by virtueof the failure of the BUYER to fulfill his part of this agreement : and the BUYER herebyrenounces his right to demand or reclaim the return of the same and further obligatespeacefully to vacate the premises and deliver the same to the SELLER.Well settled is the rule, as held in previous jurisprudence, 2 that judicial action for the rescission of acontract is not necessary where the contract provides that it may be revoked and cancelled for violation ofany of its terms and conditions. However, even in the cited cases, there was at least a written notice sent
to the defaulter informing him of the rescission. As stressed in University of the Philippines vs. Walfrido delos Angeles 3 the act of a party in treating a contract as cancelled should be made known to the other. Wequote the pertinent excerpt:Of course, it must be understood that the act of a party in treating a contract as cancelled orresolved in account of infractions by the other contracting party must be made known to theother and is always provisional being ever subject to scrutiny and review by the propercourt. If the other party denies that rescission is justified it is free to resort to judicial actionin its own behalf, and bring the matter to court.Then, should the court, after due hearing,decide that the resolution of the contract was not warranted, the responsible party will besentenced to damages; in the contrary case, the resolution will be affirmed, and theconsequent indemnity awarded to the party prejudiced.In other words, the party who deems the contract violated may consider it resolved orrescinded, and act accordingly, without previous court action, but it proceeds at its ownrisk. For it is only the final judgment of the corresponding court that will conclusively andfinally settle whether the action taken was or was not correct in law. But the law definitelydoes not require that the contracting party who believes itself injured must first file suit andwait for a judgment before taking extrajudicial steps to protect its interest. Otherwise, theparty injured by the other's breach will have to passively sit and watch its damagesaccumulate during the pendency of the suit until the final judgment of rescission is renderedwhen the law itself requires that he should exercise due diligence to minimize its owndamages (Civil Code, Article 2203).We see no conflict between this ruling and the previous jurisprudence of this Court invokedby respondent declaring that judicial action is necessary for the resolution of a reciprocalobligation (Ocejo Perez & Co., vs. International Banking Corp., 37 Phil. 631; Republic vs.Hospital de San Juan De Dios, et al., 84 Phil 820) since in every case where the extrajudicialresolution is contested only the final award of the court of competent jurisdiction canconclusively settle whether the resolution was proper or not. It is in this sense that judicialaction win be necessary, as without it, the extrajudicial resolution will remain contestableand subject to judicial invalidation unless attack thereon should become barred byacquiescense, estoppel or prescription.Fears have been expressed that a stipulation providing for a unilateral rescission in case ofbreach of contract may render nugatory the general rule requiring judicial action (v.Footnote, Padilla Civil Law, Civil Code Anno., 1967 ed. Vol. IV, page 140) but, as alreadyobserved, in case of abuse or error by the rescinder the other party is not barred fromquestioning in court such abuse or error, the practical effect of the stipulation being merelyto transfer to the defaulter the initiative of instituting suit, instead of therescinder (Emphasis supplied).Of similar import is the ruling in Nera vs. Vacante 4, reading:A stipulation entitling one party to take possession of the land and building if the other partyviolates the contract does not ex propio vigore confer upon the former the right to takepossession thereof if objected to without judicial intervention and determination.This was reiterated in Zulueta vs. Mariano 5 where we held that extrajudicial rescission has legal effectwhere the other party does not oppose it. 6 Where it is objected to, a judicial determination of the issue isstill necessary.
In other words, resolution of reciprocal contracts may be made extrajudicially unless successfullyimpugned in Court. If the debtor impugns the declaration, it shall be subject to judicial determination.
In this case, private respondent has denied that rescission is justified and has resorted to judicial action. Itis now for the Court to determine whether resolution of the contract by petitioners was warranted.We hold that resolution by petitioners of the contract was ineffective and inoperative against privaterespondent for lack of notice of resolution, as held in the U.P. vs. Angeles case, supraPetitioner relies on Torralba vs. De los Angeles 8 where it was held that "there was no contract to rescind incourt because from the moment the petitioner defaulted in the timely payment of the installments, thecontract between the parties was deemed ipso facto rescinded." However, it should be noted that even inthat case notice in writing was made to the vendee of the cancellation and annulment of the contractalthough tookeffect on September 14, 1972, when it specifically provided:Sec. 3(b) ... the actual cancellation of the contract shall take place after thirty days fromreceipt by the buyer of the notice of cancellation or the demand for rescission of thecontract by a notarial act and upon full payment of the cash surrender value to the buyer.(Emphasis supplied).The contention that private respondent had waived his right to be notified under paragraph 6 of thecontract is neither meritorious because it was a contract of adhesion, a standard form of petitionercorporation, and private respondent had no freedom to stipulate. A waiver must be certain andunequivocal, and intelligently made; such waiver follows only where liberty of choice has been fullyaccorded. 9 Moreover, it is a matter of public policy to protect buyers of real estate on installmentpayments against onerous and oppressive conditions. Waiver of notice is one such onerous and oppressivecondition to buyers of real estate on installment payments.Regarding the second issue on refund of the installment payments made by privaterespondent. Article 1385 of the Civil Code provides:ART. 1385. Rescission creates the obligation to return the things which were the object of thecontract, together with their fruits, and the price with its interest; consequently, it can becarried out only when he who demands rescission can return whatever he may be obliged torestore.Neither sham rescission take place when the things which are the object of the contract arelegally in the possession of third persons who did not act in bad faith.In this case, indemnity for damages may be demanded from the person causing the loss.As a consequence of the resolution by petitioners, rights to the lot should be restored to privaterespondent or the same should be replaced by another acceptable lot. However, considering that theproperty had already been sold to a third person and there is no evidence on record that other lots are stillavailable, private respondent is entitled to the refund of installments paid plus interest at the legal rate of12% computed from the date of the institution of the action. 10 It would be most inequitable if petitionerswere to be allowed to retain private respondent's payments and at the same time appropriate theproceeds of the second sale to another.
We come now to the third and fourth issues regarding the personal liability of petitioner Onstott who wasmade jointly and severally liable with petitioner corporation for refund to private respondent of the totalamount the latter had paid to petitioner company. It is basic that a corporation is invested by law with apersonality separate and distinct from those of the persons composing it as wen as from that of any otherlegal entity to which it may be related. 11 As a general rule, a corporation may not be made to answer foracts or liabilities of its stockholders or those of the legal entities to which it may be connected and viceversa. However, the veil of corporate fiction may be pierced when it is used as a shield to further an endsubversive of justice 12 ; or for purposes that could not have been intended by the law that created it 13 ; orto defeat public convenience, justify wrong, protect fraud, or defend crime. 14 ; or to perpetuate fraud orconfuse legitimate issues 15 ; or to circumvent the law or perpetuate deception 16 ; or as an alter ego,adjunct or business conduit for the sole benefit of the stockholders. 17We find no badges of fraud on petitioners' part. They had literally relied, albeit mistakenly, on paragraph 6(supra) of its contract with private respondent when it rescinded the contract to sell extrajudicially and hadsold it to a third person.In this case, petitioner Onstott was made liable because he was then the President of the corporation andhe a to be the controlling stockholder. No sufficient proof exists on record that said petitioner used thecorporation to defraud private respondent. He cannot, therefore, be made personally liable just because he"appears to be the controlling stockholder". Mere ownership by a single stockholder or by anothercorporation is not of itself sufficient ground for disregarding the separate corporate personality. 18 In thisrespect then, a modification of the Resolution under review is called for.WHEREFORE, the questioned Resolution of respondent public official, dated May 2, 1980, is herebymodified. Petitioner Palay, Inc. is directed to refund to respondent Nazario M. Dumpit the amount ofP13,722.50, with interest at twelve (12%) percent per annum from November 8, 1974, the date of the filingof the Complaint. The temporary Restraining Order heretofore issued is hereby lifted.No costs.SO ORDERED.
PANGANIBAN, J.:May corporate treasurer, by herself and without any authorization from he board of directors, validly sell aparcel of land owned by the corporation?. May the veil of corporate fiction be pierced on the mere groundthat almost all of the shares of stock of the corporation are owned by said treasurer and her husband?The CaseThese questions are answered in the negative by this Court in resolving the Petition for Reviewon Certiorari before us, assailing the March 18, 1997 Decision 1 of the Court of Appeals 2 in CA GR CV No.46801 which, in turn, modified the July 18, 1994 Decision of the Regional Trial Court of Makati, MetroManila, Branch 63 3 in Civil Case No. 89-3511. The RTC dismissed both the Complaint and the Counterclaimfiled by the parties. On the other hand, the Court of Appeals ruled:WHEREFORE, premises considered, the appealed decision is AFFIRMED WITH MODIFICATIONordering defendant-appellee Nenita Lee Gruenberg to REFUND or return to plaintiff-appellantthe downpayment of P100,000.00 which she received from plaintiff-appellant. There is nopronouncement as to costs. 4The petition also challenges the June 10, 1997 CA Resolution denying reconsideration.
The FactsThe facts as found by the Court of Appeals are as follows:Plaintiff-appellant San Juan Structural and Steel Fabricators, Inc.'s amended complaintalleged that on 14 February 1989, plaintiff-appellant entered into an agreement withdefendant-appellee Motorich Sales Corporation for the transfer to it of a parcel of landidentified as Lot 30, Block 1 of the Acropolis Greens Subdivision located in the District ofMurphy, Quezon City. Metro Manila, containing an area of Four Hundred Fourteen (414)square meters, covered by TCT No. (362909) 2876: that as stipulated in the Agreement of 14February 1989, plaintiff-appellant paid the downpayment in the sum of One HundredThousand (P100,000.00) Pesos, the balance to be paid on or before March 2, 1989; that onMarch 1, 1989. Mr. Andres T. Co, president of plaintiff-appellant corporation, wrote a letter todefendant-appellee Motorich Sales Corporation requesting for a computation of the balanceto be paid: that said letter was coursed through defendant-appellee's broker. Linda Aduca,who wrote the computation of the balance: that on March 2, 1989, plaintiff-appellant wasready with the amount corresponding to the balance, covered by Metrobank Cashier's CheckNo. 004223, payable to defendant-appellee Motorich Sales Corporation; that plaintiffappellant and defendant-appellee Motorich Sales Corporation were supposed to meet in theoffice of plaintiff-appellant but defendant-appellee's treasurer, Nenita Lee Gruenberg, did notappear; that defendant-appellee Motorich Sales Corporation despite repeated demands andin utter disregard of its commitments had refused to execute the Transfer of Rights/Deed ofAssignmentthe transferor of right in favor of defendant-appellee Motorich Sales Corporation: that onApril 6, 1989, defendant ACL Development Corporation and Motorich Sales Corporationentered into a Deed of Absolute Sale whereby the former transferred to the latter the subjectproperty; that by reason of said transfer, the Registry of Deeds of Quezon City issued a newtitle in the name of Motorich Sales Corporation, represented by defendant-appellee NenitaLee Gruenberg and Reynaldo L. Gruenberg, under Transfer Certificate of Title No. 3571; thatas a result of defendants-appellees Nenita Lee Gruenberg and Motorich Sales Corporation'sbad faith in refusing to execute a formal Transfer of Rights/Deed of Assignment, plaintiffappellant suffered moral and nominal damages which may be assessed against defendantsappellees in the sum of Five Hundred Thousand (500,000.00) Pesos; that as a result ofdefendants-appellees Nenita Lee Gruenberg and Motorich Sales Corporation's unjustified andunwarranted failure to execute the required Transfer of Rights/Deed of Assignment or formaldeed of sale in favor of plaintiff-appellant, defendants-appellees should be assessedexemplary damages in the sum of One Hundred Thousand (P100,000.00) Pesos; that byreason of defendants-appellees' bad faith in refusing to execute a Transfer of Rights/Deed ofAssignment in favor of plaintiff-appellant, the latter lost the opportunity to construct aresidential building in the sum of One Hundred Thousand (P100,000.00) Pesos; and that as aconsequence of defendants-appellees Nenita Lee Gruenberg and Motorich SalesCorporation's bad faith in refusing to execute a deed of sale in favor of plaintiff-appellant, ithas been constrained to obtain the services of counsel at an agreed fee of One HundredThousand (P100,000.00) Pesos plus appearance fee for every appearance in court hearings.In its answer, defendants-appellees Motorich Sales Corporation and Nenita Lee Gruenberginterposed as affirmative defense that the President and Chairman of Motorich did not signthe agreement adverted to in par. 3 of the amended complaint; that Mrs. Gruenberg'ssignature on the agreement (ref: par. 3 of Amended Complaint) is inadequate to bindMotorich. The other signature, that of Mr. Reynaldo Gruenberg, President and Chairman ofMotorich, is required: that plaintiff knew this from the very beginning as it was presented acopy of the Transfer of Rights (Annex B of amended complaint) at the time the Agreement(Annex B of amended complaint) was signed; that plaintiff-appellant itself drafted theAgreement and insisted that Mrs. Gruenberg accept the P100,000.00 as earnest money; thatgranting, without admitting, the enforceability of the agreement, plaintiff-appellantnonetheless failed to pay in legal tender within the stipulated period (up to March 2, 1989);that it was the understanding between Mrs. Gruenberg and plaintiff-appellant that theTransfer of Rights/Deed of Assignment will be signed only upon receipt of cash payment;thus they agreed that if the payment be in check, they will meet at a bank designated byplaintiff compeldefendants to execute a deed of absolute sale in accordance with theagreement of February 14, 1989: and if so, whether plaintiff is entitled todamage.As to the first question, there is no evidence to show that defendant NenitaLee Gruenberg was indeed authorized by defendant corporation. Motorich
Sales, to dispose of that property covered by T.C.T. No. (362909) 2876. Sincethe property is clearly owned by the corporation. Motorich Sales, then itsdisposition should be governed by the requirement laid down in Sec. 40. of theCorporation Code of the Philippines, to wit:Sec. 40, Sale or other disposition of assets. Subject to theprovisions of existing laws on illegal combination andmonopolies, a corporation may by a majority vote of its board ofdirectors . . . sell, lease, exchange, mortgage, pledge orotherwise dispose of all or substantially all of its property andassets including its goodwill . . . when authorized by the vote ofthe stockholders representing at least two third (2/3) of theoutstanding capital stock . . .No such vote was obtained by defendant Nenita Lee Gruenberg for thatproposed sale[;] neither was there evidence to show that the supposedtransaction was ratified by the corporation. Plaintiff should have been on thelook out under these circumstances. More so, plaintiff himself [owns] severalcorporations (tsn dated August 16, 1993, p. 3) which makes himknowledgeable on corporation matters.Regarding the question of damages, the Court likewise, does not findsubstantial evidence to hold defendant Nenita Lee Gruenberg liableconsidering that she did not in anyway misrepresent herself to be authorizedby the corporation to sell the property to plaintiff (tsn dated September 27,1991, p. 8).In the light of the foregoing, the Court hereby renders judgment DISMISSINGthe complaint at instance for lack of merit."Defendants" counterclaim is also DISMISSED for lack of basis. (Decision, pp.7-8; Rollo, pp. 34-35)For clarity, the Agreement dated February 14, 1989 is reproduced hereunder:AGREEMENTKNOW ALL MEN BY THESE PRESENTS:This Agreement, made and entered into by and between:MOTORICH SALES CORPORATION, a corporation duly organized and existingunder and by virtue of Philippine Laws, with principal office address at 5510South Super Hi-way cor. Balderama St., Pio del Pilar. Makati, Metro Manila,represented herein by its Treasurer, NENITA LEE GRUENBERG, hereinafterreferred to as the TRANSFEROR; and SAN JUAN STRUCTURAL & STEEL FABRICATORS, a corporation duly organizedand existing under and by virtue of the laws of the Philippines, with principaloffice address at Sumulong Highway, Barrio Mambungan, Antipolo, Rizal,
6In its recourse before the Court of Appeals, petitioner insisted:1. Appellant is entitled to compel the appellees to execute a Deed of AbsoluteSale in accordance with the Agreement of February 14, 1989,2. Plaintiff is entitled to damages.
As stated earlier, the Court of Appeals debunked petitioner's arguments and affirmed the Decision of theRTC with the modification that Respondent Nenita Lee Gruenberg was ordered to refund P100,000 topetitioner, the amount remitted as "downpayment" or "earnest money." Hence, this petition before us. 8The IssuesBefore this Court, petitioner raises the following issues:I. Whether or not the doctrine of piercing the veil of corporate fiction isapplicable in the instant caseII. Whether or not the appellate court may consider matters which the partiesfailed to raise in the lower courtIII. Whether or not there is a valid and enforceable contract between thepetitioner and the respondent corporationIV. Whether or not the Court of Appeals erred in holding that there is a validcorrection/substitution of answer in the transcript of stenographic note[s].V. Whether or not respondents are liable for damages and attorney's fees
The Court synthesized the foregoing and will thus discuss them seriatim as follows:1. Was there a valid contract of sale between petitioner and Motorich?2. May the doctrine of piercing the veil of corporate fiction be applied toMotorich?3. Is the alleged alteration of Gruenberg's testimony as recorded in thetranscript of stenographic notes material to the disposition of this case?4. Are respondents liable for damages and attorney's fees?The Court's RulingThe petition is devoid of merit.First Issue: Validity of AgreementPetitioner San Juan Structural and Steel Fabricators, Inc. alleges that on February 14, 1989, it enteredthrough its president, Andres Co, into the disputed Agreement with Respondent Motorich SalesCorporation, which was in turn allegedly represented by its treasurer, Nenita Lee Gruenberg. Petitionerinsists that "[w]hen Gruenberg and Co affixed their signatures on the contract they both consented to be
bound by the terms thereof." Ergo, petitioner contends that the contract is binding on the twocorporations. We do not agree.True, Gruenberg and Co signed on February 14, 1989, the Agreement, according to which a lot owned byMotorich Sales Corporation was purportedly sold. Such contract, however, cannot bind Motorich, because itnever authorized or ratified such sale.A corporation is a juridical person separate and distinct from its stockholders or members. Accordingly, theproperty of the corporation is not the property of its stockholders or members and may not be sold by thestockholders or members without express authorization from the corporation's board ofdirectors. 10 Section 23 of BP 68, otherwise known as the Corporation Code of the Philippines, provides;Sec. 23. The Board of Directors or Trustees. Unless otherwise provided in this Code, thecorporate powers of all corporations formed under this Code shall be exercised, all businessconducted and all property of such corporations controlled and held by the board of directorsor trustees to be elected from among the holders of stocks, or where there is no stock, fromamong the members of the corporation, who shall hold office for one (1) year and until theirsuccessors are elected and qualified.Indubitably, a corporation may act only through its board of directors or, when authorized either by itsbylaws or by its board resolution, through its officers or agents in the normal course of business. Thegeneral principles of agency govern the relation between the corporation and its officers or agents, subjectto the articles of incorporation, bylaws, or relevant provisions of law. 11 Thus, this Court has held that "acorporate officer or agent may represent and bind the corporation in transactions with third persons to theextent that the authority to do so has been conferred upon him, and this includes powers which have beenintentionally conferred, and also such powers as, in the usual course of the particular business, areincidental to, or may be implied from, the powers intentionally conferred, powers added by custom andusage, as usually pertaining to the particular officer or agent, and such apparent powers as the corporationhas caused persons dealing with the officer or agent to believe that it has conferred." 12Furthermore, the Court has also recognized the rule that "persons dealing with an assumed agent, whetherthe assumed agency be a general or special one bound at their peril, if they would hold the principal liable,to ascertain not only the fact of agency but also the nature and extent of authority, and in case either iscontroverted, the burden of proof is upon them to establish it (Harry Keeler v. Rodriguez, 4 Phil.19)." 13 Unless duly authorized, a treasurer, whose powers are limited, cannot bind the corporation in asale of its assets. 14In the case at bar, Respondent Motorich categorically denies that it ever authorized Nenita Gruenberg, itstreasurer, to sell the subject parcel of land. 15 Consequently, petitioner had the burden of proving thatNenita Gruenberg was in fact authorized to represent and bind Motorich in the transaction. Petitioner failedto discharge this burden. Its offer of evidence before the trial court contained no proof of suchauthority. 16 It has not shown any provision of said respondent's articles of incorporation, bylaws or boardresolution to prove that Nenita Gruenberg possessed such power.That Nenita Gruenberg is the treasurer of Motorich does not free petitioner from the responsibility ofascertaining the extent of her authority to represent the corporation. Petitioner cannot assume that she, byvirtue of her position, was authorized to sell the property of the corporation. Selling is obviously foreign toa corporate treasurer's function, which generally has been described as "to receive and keep the funds ofthe corporation, and to disburse them in accordance with the authority given him by the board or theproperly authorized officers." 17Neither was such real estate sale shown to be a normal business activity of Motorich. The primary purposeof Motorich is marketing, distribution, export and import in relation to a general merchandising
business. 18 Unmistakably, its treasurer is not cloaked with actual or apparent authority to buy or sell realproperty, an activity which falls way beyond the scope of her general authority.Art. 1874 and 1878 of the Civil Code of the Philippines provides:Art. 1874. When a sale of a piece of land or any interest therein is through an agent, theauthority of the latter shall be in writing: otherwise, the sale shall be void.Art. 1878. Special powers of attorney are necessary in the following case:xxx xxx xxx(5) To enter any contract by which the ownership of an immovable is transmitted or acquiredeither gratuitously or for a valuable consideration;xxx xxx xxx.Petitioner further contends that Respondent Motorich has ratified said contract of sale because of its"acceptance of benefits," as evidenced by the receipt issued by Respondent Gruenberg. 19 Petitioner isclutching at straws.As a general rule, the acts of corporate officers within the scope of their authority are binding on thecorporation. But when these officers exceed their authority, their actions "cannot bind the corporation,unless it has ratified such acts or is estopped from disclaiming them." 20In this case, there is a clear absence of proof that Motorich ever authorized Nenita Gruenberg, or made itappear to any third person that she had the authority, to sell its land or to receive the earnest money.Neither was there any proof that Motorich ratified, expressly or impliedly, the contract. Petitioner rests itsargument on the receipt which, however, does not prove the fact of ratification. The document is a handwritten one, not a corporate receipt, and it bears only Nenita Gruenberg's signature. Certainly, thisdocument alone does not prove that her acts were authorized or ratified by Motorich.Art. 1318 of the Civil Code lists the requisites of a valid and perfected contract: "(1) consent of thecontracting parties; (2) object certain which is the subject matter of the contract; (3) cause of theobligation which is established." As found by the trial court 21 and affirmed by the Court of Appeals, 22 thereis no evidence that Gruenberg was authorized to enter into the contract of sale, or that the said contractwas ratified by Motorich. This factual finding of the two courts is binding on this Court. 23 As the consent ofthe seller was not obtained, no contract to bind the obligor was perfected. Therefore, there can be no validcontract of sale between petitioner and Motorich.Because Motorich had never given a written authorization to Respondent Gruenberg to sell its parcel ofland, we hold that the February 14, 1989 Agreement entered into by the latter with petitioner is void underArticle 1874 of the Civil Code. Being inexistent and void from the beginning, said contract cannot beratified. 24Second Issue:Piercing the Corporate Veil Not JustifiedPetitioner also argues that the veil of corporate fiction of Motorich should be pierced, because the latter isa close corporation. Since "Spouses Reynaldo L. Gruenberg and Nenita R. Gruenberg owned all or almostall or 99.866% to be accurate, of the subscribed capital stock" 25 of Motorich, petitioner argues thatGruenberg needed no authorization from the board to enter into the subject contract. 26 It adds that, being
solely owned by the Spouses Gruenberg, the company can treated as a close corporation which can bebound by the acts of its principal stockholder who needs no specific authority. The Court is not persuaded.First, petitioner itself concedes having raised the issue belatedly, 27 not having done so during the trial, butonly when it filed its sur-rejoinder before the Court of Appeals. 28 Thus, this Court cannot entertain saidissue at this late stage of the proceedings. It is well-settled the points of law, theories and arguments notbrought to the attention of the trial court need not be, and ordinarily will not be, considered by a reviewingcourt, as they cannot be raised for the first time on appeal. 29Allowing petitioner to change horses inmidstream, as it were, is to run roughshod over the basic principles of fair play, justice and due process.Second, even if the above mentioned argument were to be addressed at this time, the Court still finds noreason to uphold it. True, one of the advantages of a corporate form of business organization is thelimitation of an investor's liability to the amount of the investment. 30 This feature flows from the legaltheory that a corporate entity is separate and distinct from its stockholders. However, the statutorilygranted privilege of a corporate veil may be used only for legitimate purposes. 31 On equitableconsiderations, the veil can be disregarded when it is utilized as a shield to commit fraud, illegality orinequity; defeat public convenience; confuse legitimate issues; or serve as a mere alter ego or businessconduit of a person or an instrumentality, agency or adjunct of another corporation. 32Thus, the Court has consistently ruled that "[w]hen the fiction is used as a means of perpetrating a fraudor an illegal act or as vehicle for the evasion of an existing obligation, the circumvention of statutes, theachievement or perfection of a monopoly or generally the perpetration of knavery or crime, the veil withwhich the law covers and isolates the corporation from the members or stockholders who compose it willbe lifted to allow for its consideration merely as an aggregation of individuals." 33We stress that the corporate fiction should be set aside when it becomes a shield against liability for fraud,illegality or inequity committed on third persons. The question of piercing the veil of corporate fiction isessentially, then, a matter of proof. In the present case, however, the Court finds no reason to pierce thecorporate veil of Respondent Motorich. Petitioner utterly failed to establish that said corporation wasformed, or that it is operated, for the purpose of shielding any alleged fraudulent or illegal activities of itsofficers or stockholders; or that the said veil was used to conceal fraud, illegality or inequity at the expenseof third persons like petitioner.Petitioner claims that Motorich is a close corporation. We rule that it is not. Section 96 of the CorporationCode defines a close corporation as follows:Sec. 96. Definition and Applicability of Title. A close corporation, within the meaning ofthis Code, is one whose articles of incorporation provide that: (1) All of the corporation'sissued stock of all classes, exclusive of treasury shares, shall be held of record by not morethan a specified number of persons, not exceeding twenty (20); (2) All of the issued stock ofall classes shall be subject to one or more specified restrictions on transfer permitted by thisTitle; and (3) The corporation shall not list in any stock exchange or make any public offeringof any of its stock of any class. Notwithstanding the foregoing, a corporation shall bedeemed not a close corporation when at least two-thirds (2/3) of its voting stock or votingrights is owned or controlled by another corporation which is not a close corporation withinthe meaning of this Code. . . . .The articles of incorporation 34 of Motorich Sales Corporation does not contain any provision stating that (1)the number of stockholders shall not exceed 20, or (2) a preemption of shares is restricted in favor of anystockholder or of the corporation, or (3) listing its stocks in any stock exchange or making a public offeringof such stocks is prohibited. From its articles, it is clear that Respondent Motorich is not a closecorporation. 35 Motorich does not become one either, just because Spouses Reynaldo and NenitaGruenberg owned 99.866% of its subscribed capital stock. The "[m]ere ownership by a single stockholder
or by another corporation of all or capital stock of a corporation is not of itself sufficient ground fordisregarding the separate corporate personalities." 36 So, too, a narrow distribution of ownership does not,by itself, make a close corporation.Petitioner cites Manuel R. Dulay Enterprises, Inc. v. Court of Appeals 37 wherein the Court ruled that ". . .petitioner corporation is classified as a close corporation and, consequently, a board resolution authorizingthe sale or mortgage of the subject property is not necessary to bind the corporation for the action of itspresident." 38 But the factual milieu in Dulay is not on all fours with the present case. In Dulay, the sale ofreal property was contracted by the president of a close corporation with the knowledge and acquiescenceof its board of directors. 39 In the present case, Motorich is not a close corporation, as previously discussed,and the agreement was entered into by the corporate treasurer without the knowledge of the board ofdirectors.The Court is not unaware that there are exceptional cases where "an action by a director, who singly is thecontrolling stockholder, may be considered as a binding corporate act and a board action as nothing morethan a mere formality." 40 The present case, however, is not one of them.As stated by petitioner, Spouses Reynaldo and Nenita Gruenberg own "almost 99.866%" of RespondentMotorich.41 Since Nenita is not the sole controlling stockholder of Motorich, the aforementioned exceptiondoes not apply. Grantingarguendo that the corporate veil of Motorich is to be disregarded, the subjectparcel of land would then be treated as conjugal property of Spouses Gruenberg, because the same wasacquired during their marriage. There being no indication that said spouses, who appear to have beenmarried before the effectivity of the Family Code, have agreed to a different property regime, theirproperty relations would be governed by conjugal partnership of gains. 42 As a consequence, NenitaGruenberg could not have effected a sale of the subject lot because "[t]here is no co-ownership betweenthe spouses in the properties of the conjugal partnership of gains. Hence, neither spouse can alienate infavor of another his or interest in the partnership or in any property belonging to it; neither spouse can askfor a partition of the properties before the partnership has been legally dissolved." 43Assuming further, for the sake of argument, that the spouses' property regime is the absolute communityof property, the sale would still be invalid. Under this regime, "alienation of community property must havethe written consent of the other spouse or he authority of the court without which the disposition orencumbrance is void." 44 Both requirements are manifestly absent in the instant case.Third Issue: Challenged Portion of TSN ImmaterialPetitioner calls our attention to the following excerpt of the transcript of stenographic notes (TSN):Q Did you ever represent to Mr. Co that you were authorized by thecorporation to sell the property?A Yes, sir.
45
Petitioner claims that the answer "Yes" was crossed out, and, in its place was written a "No" with an initialscribbled above it.46 This, however, is insufficient to prove that Nenita Gruenberg was authorized torepresent Respondent Motorich in the sale of its immovable property. Said excerpt be understood in thecontextauthorized] alsothe president who [was] also authorized to sign on behalf of the corporation.Q You did not say that you were not authorized nor did you say that you wereauthorized?A Mr. Co was very interested to purchase the property and he offered to putup a P100,000.00 earnest money at that time. That was our first meeting. 47Clearly then, Nenita Gruenberg did not testify that Motorich had authorized her to sell its property. On theother hand, her testimony demonstrates that the president of Petitioner Corporation, in his great desire tobuy the property, threw caution to the wind by offering and paying the earnest money without firstverifying Gruenberg's authority to sell the lot.Fourth Issue:Damages and Attorney's FeesFinally, petitioner prays for damages and attorney's fees, alleging that "[i]n an utter display of malice andbad faith, respondents attempted and succeeded in impressing on the trial court and [the] Court ofAppeals that Gruenberg did not represent herself as authorized by Respondent Motorich despite thereceipt issued by the former specifically indicating that she was signing on behalf of Motorich SalesCorporation. Respondent Motorich likewise acted in bad faith when it claimed it did not authorizeRespondent Gruenberg and that the contract [was] not binding, [insofar] as it [was] concerned, despitereceipt and enjoyment of the proceeds of Gruenberg's act." 48 Assuming that Respondent Motorich was nota party to the alleged fraud, petitioner maintains that Respondent Gruenberg should be held liablebecause she "acted fraudulently and in bad faith [in] representing herself as duly authorized by[R]espondent [C]orporation." 49As already stated, we sustain the findings of both the trial and the appellate courts that the foregoingallegations lack factual bases. Hence, an award of damages or attorney's fees cannot be justified. Theamount paid as "earnest money" was not proven to have redounded to the benefit of RespondentMotorich. Petitioner claims that said amount was deposited to the account of Respondent Motorich,because "it was deposited with the account of Aren Commercial c/o Motorich SalesCorporation." 50 Respondent Gruenberg, however, disputes the allegations of petitioner. She testified asfollows:Q You voluntarily accepted the P100,000.00, as a matter of fact, that wasencashed, the check was encashed.
A Yes. sir, the check was paid in my name and I deposit[ed] it.Q In your account?A Yes, sir.
51
In any event, Gruenberg offered to return the amount to petitioner ". . . since the sale did not pushthrough." 52Moreover, we note that Andres Co is not a neophyte in the world of corporate business. He has been thepresident of Petitioner Corporation for more than ten years and has also served as chief executive of twoother corporate entities. 53 Co cannot feign ignorance of the scope of the authority of a corporate treasurersuch as Gruenberg. Neither can he be oblivious to his duty to ascertain the scope of Gruenberg'sauthorizationwith and paying an unauthorized officer of another corporation.As correctly ruled by the Court of Appeals, however, Nenita Gruenberg should be ordered to return topetitioner the amount she received as earnest money, as "no one shall enrich himself at the expense ofanother." 54 a principle embodied in Article 2154 of Civil Code. 55 Although there was no binding relationbetween them, petitioner paid Gruenberg on the mistaken belief that she had the authority to sell theproperty of Motorich. 56 Article 2155 of Civil Code provides that "[p]ayment by reason of a mistake in thecontruction or application of a difficult question of law may come within the scope of the preceding article."WHEREFORE, the petition is hereby DENIED and the assailed Decision is AFFIRMED.SO ORDERED.Davide, Jr., Bellosillo, Vitug and Quisumbing, JJ., concur.
June 6, 1991
As to [the] liability of [the] defendant Roberto A. Jacinto, it would appear that he is in factetum (sic),or, in fact, the corporation itself known as Inland Industries, Inc. Aside from the fact that he isadmittedly the President and General Manager of the corporation and a substantial stockholders(sic) thereof, it was defendant Roberto A. Jacinto who dealt entirely with the plaintiff in thosetransactions. In the Trust Receipts that he signed supposedly in behalf of Inland Industries, Inc., it isnot even mentioned that he did so in this official capacity.xxx
xxx
In this case, the Court is satisfied that Roberto A. Jacinto was practically the corporation itself, theInland industries, Inc.In a detailed fashion, the respondent Court of Appeals brushed aside the posturing of petitioner as follows:Defendant Roberto Jacinto, tried to escape liability and shift the entire blame under the trustreceipts solely and exclusively on defendant-appellant corporation. He asserted that he cannot beheld solidarily liable with the latter (defendant corporation) because he just signed said instrumentsin his official capacity as president of Inland Industries, Inc. and the latter (defendant corporation)has a juridical personality distinct and separate from its officers and stockholders. It is likewiseasserted, citing an American case, that the principle of piercing the fiction of corporate entityshould be applied with great caution and not precipitately, because a dual personality by acorporation and its stockholders would defeat the principal purpose for which a corporation isformed. Upon the other hand, plaintiff-appellee reiterated its allegation in the complaint thatdefendant corporation is just a mere alter ego of defendant Roberto Jacinto who is its President andGeneral Manager, while the wife of the latter owns a majority of its shares of stock.Defendants-appellants' assertion is plainly without legal basis. This is shown by the undisputed factthat Roberto Jacinto even admitted that he and his wife own 52% of the stocks of defendantcorporation (TSN, April 22, 1985, p. 6). We cannot accept as true the assertion of defendant Jacintothat he only acted in his official capacity as President and General Manager of Inland Industries, Inc.when he signed the aforesaid trust receipts. To Our mind the same is just a clever ruse and aconvenient ploy to thwart his personal liability therefor by taking refuge under the protectivemantle of the separate corporate personality of defendant corporation.As could be expected, Roberto Jacinto in his direct testimony presented a different corporatescenario regarding Inland Industries, Inc. and vehemently declared that it is Bienvenida Catabaswho is its President, while Aurora Heresa is its Chairman of the Board. His assertion on this point,however, is not convincing in view of his admission in the same breath, that his wife, Hedy U.Jacinto, own (sic) with him 52% of the shares of stock of said corporation. Indeed, this circumstance even if standing alone cannot but engender in the most unprejudiced mind doubt andmisgiving why Catabas and Heresa would be defendant corporation's President and Chairman of theBoard, respectively. Pertinent portion of his testimony on this point is quoted hereunder:Atty. Carlos Do you know the defendant Inland Industries, Inc.?A Yes, sir. Because I am the General Manager of this corporation.Q Aside from being the General Manager of the defendant corporation are you in any otherway connected with the same?A I am also a stockholder.Q Does your corporation have a Board of Directors?A Yes, sir.Q By the way, who are the stockholders of this corporation?
A Bienvenida Catabas, Aurora Heresa, Paz Yulo, Hedy Y. Jacinto and myself.Q Who is the President of the defendant corporation?A Bienvenida Catabas.Q Who is the Chairman of the Board?A Aurora Heresa.Q Do you have any relation with Hedy Y. Jacinto?A She is my wife.Q If you combine the stockholdings of your wife together with yours and percentage wise,how much is your equity?Atty. Dizon raised some objections. However, the Court allowed the same.A About 52 % (Ibid., pp. 3-6)Furthermore, a cursory perusal of the Stipulation of facts clearly shows that defendant RobertoJacinto acted in his capacity as President and General Manager of Inland Industries, Inc. when hesigned said trust receipts. Pertinent portion of his testimony are quoted below:(d) All the goods covered by the three (3) Letters of Credit (Annexes "A", "B" & "C") and paidfor under the Bills of Exchange (Annexes "D", "E" & "F") were delivered to and received bydefendant Inland Industries, Inc. through its co-defendant Roberto A. Jacinto, its Presidentand General Manager, who signed for and in behalf of defendant Inland and agreed to theterms and conditions of three (3) separate trust receipts covering the same and hereinidentified as follows: . . . (p. 3 of Stipulations of Facts and Formulation of Issues [p. 95,Records]).The conflicting statements by defendant Jacinto place in extreme doubt his credibility anent hisalleged participation in said transactions and We are thus persuaded to agree with the findings ofthe lower court that the latter (Roberto Jacinto) was practically the corporation itself. Indeed, apainstaking examination of the records show that there is no clear-cut delimitation between thepersonality of Roberto Jacinto as an individual and the personality of Inland Industries, Inc. as acorporation.The circumstances aforestated lead Us to conclude that the corporate veil that en-shroudsdefendant Inland Industries, Inc. could be validly pierced, and a host of cases decided by our HighCourt is supportive of this view. Thus it held that "when the veil of corporate fiction is made as ashield to perpetuate fraud and/or confuse legitimate issues, the same should be pierced." (Republicvs. Razon, 20 SCRA 234; A.D. Santos, Inc. vs. Vasquez, 22 SCRA 1156; Emilio Cano Enterprises, Inc.vs. Court of Appeals, 13 SCRA 290). Almost in the same vein is the dictum enunciated by the samecourt in the case of Commissioner of Internal Revenue vs. Norton & Harrison Co., (11 SCRA 714),that "Where a corporation is merely an adjunct, business conduit or alter ego, the fiction ofseparate and distinct corporate entity should be disregarded."In its resolution of 29 September 1987, the respondent Court of Appeals, on the contention again ofpetitioner that the finding that defendant corporation is his mere alter ego is not supported by theevidence and has no legal justification, ruled that:The contention . . . is nothing but an empty assertion. A cursory perusal of the decision would atonce readily show on pages 11-13 of the same that said factual findings of the court is wellgrounded as the same in fact even include a portion of the very testimony of said defendantappellant admitting that he and his wife own 52% of the stocks of defendant corporation. The
stipulation of facts also show (sic) that appellant Roberto Jacinto acted in his capacity asPresident/General Manager of defendant corporation and that "all the goods covered by the three(3) Letters of Credit (Annexes "A", "B" & "C") and paid for under the Bills of Exchange (Annexes "D","E" & "F") were delivered to and received by defendant Inland Industries, Inc. through its codefendant Roberto A. Jacinto, its President and General Manager, who signed for and in behalf ofdefendant Inland and agreed to the terms and conditions of three (3) separate trust receiptscovering the same.Petitioner, however, faults the courts below for piercing the veil of corporate fiction despite the absence ofany allegation in the complaint questioning the separate identity and existence of Inland Industries, Inc.This is not accurate.1wphi1 While on the face of the complaint there is no specific allegation that thecorporation is a mere alter ego of petitioner, subsequent developments, from the stipulation of facts up tothe presentation of evidence and the examination of witnesses, unequivocally show that respondentMetropolitan Bank and Trust Company sought to prove that petitioner and the corporation are one or thathe is the corporation. No serious objection was heard from petitioner. Section 5 of Rule 10 of the Rules ofCourt provides:Sec. 5. Amendment to conform to or authorize presentation of evidence. When issues not raisedby the pleadings are tried by express or implied consent of the parties, they shall be treated in allrespects, as if they had been raised in the pleadings. Such amendment of the pleadings as may benecessary to cause them to conform to the evidence and to raise these issues may be made uponmotion of any party at any time, even after judgment; but failure so to amend does not affect thetrial of these issues. If the evidence is objected to at the time of trial on the ground that it is notwithin the issues made by the pleadings, the court may allow the pleadings to be amended andshall do so freely when the presentation of the merits of the action will be subserved thereby andthe objecting party fails to satisfy the court that the admission of such evidence would prejudicehim in maintaining his action or defense upon the merits. The court may grant continuance toenable the objecting party to meet such evidence.Pursuant thereto, "when evidence is presented by one party, with the express or implied consent of theadverse party, as to issues not alleged in the pleadings, judgment may be rendered validly as regardsthose issues, which shall be considered as if they have been raised in the pleadings. There is impliedconsent to the evidence thus presented when the adverse party fails to object thereto. 12WHEREFORE, for lack of merit, the Petition is DISMISSED with costs against petitioner.SO ORDERED.Fernan, C.J., Gutierrez, Jr., Feliciano and Bidin, JJ., concur.
Government's 87.6% equity share in PHILSECO. The provisions of the ASBR were explained to theinterested bidders who were notified that the bidding would be held on December 2, 1993. A portion of theASBR reads:1.0 The subject of this Asset Privatization Trust (APT) sale through public bidding is the NationalGovernment's equity in PHILSECO consisting of 896,869,942 shares of stock (representing 87.67% ofPHILSECO's outstanding capital stock), which will be sold as a whole block in accordance with the rulesherein enumerated.xxx xxx xxx2.0 The highest bid, as well as the buyer, shall be subject to the final approval of both the APT Board ofTrustees and the Committee on Privatization (COP).2.1 APT reserves the right in its sole discretion, to reject any or all bids.3.0 This public bidding shall be on an Indicative Price Bidding basis. The Indicative price set for theNational Government's 87.67% equity in PHILSECO is PESOS: ONE BILLION THREE HUNDRED MILLION(P1,300,000,000.00).xxx xxx xxx6.0 The highest qualified bid will be submitted to the APT Board of Trustees at its regular meeting followingthe bidding, for the purpose of determining whether or not it should be endorsed by the APT Board ofTrustees to the COP, and the latter approves the same. The APT shall advise Kawasaki Heavy Industries,Inc. and/or its nominee, [PHILYARDS] Holdings, Inc., that the highest bid is acceptable to the NationalGovernment. Kawasaki Heavy Industries, Inc. and/or [PHILYARDS] Holdings, Inc. shall then have a period ofthirty (30) calendar days from the date of receipt of such advice from APT within which to exercise their"Option to Top the Highest Bid" by offering a bid equivalent to the highest bid plus five (5%) percentthereof.6.1 Should Kawasaki Heavy Industries, Inc. and/or [PHILYARDS] Holdings, Inc. exercise their "Option to Topthe Highest Bid," they shall so notify the APT about such exercise of their option and deposit with APT theamount equivalent to ten percent (10%) of the highest bid plus five percent (5%) thereof within the thirty(30)-day period mentioned in paragraph 6.0 above. APT will then serve notice upon Kawasaki HeavyIndustries, Inc. and/or [PHILYARDS] Holdings, Inc. declaring them as the preferred bidder and they shallhave a period of ninety (90) days from the receipt of the APT's notice within which to pay the balance oftheir bid price.6.2 Should Kawasaki Heavy Industries, Inc. and/or [PHILYARDS] Holdings, Inc. fail to exercise their "Optionto Top the Highest Bid" within the thirty (30)-day period, APT will declare the highest bidder as the winningbidder.xxx xxx xxx12.0 The bidder shall be solely responsible for examining with appropriate care these rules, the official bidforms, including any addenda or amendments thereto issued during the bidding period. The bidder shalllikewise be responsible for informing itself with respect to any and all conditions concerning the PHILSECOShares which may, in any manner, affect the bidder's proposal. Failure on the part of the bidder to soexamine and inform itself shall be its sole risk and no relief for error or omission will be given by APT orCOP. . . .
At the public bidding on the said date, petitioner J.G. Summit Holdings, Inc. 2 submitted a bid of Two Billionand Thirty Million Pesos (P2,030,000,000.00) with an acknowledgment of KAWASAKI/[PHILYARDS'] right totop, viz:4. I/We understand that the Committee on Privatization (COP) has up to thirty (30) days to act on APT'srecommendation based on the result of this bidding. Should the COP approve the highest bid, APT shalladvise Kawasaki Heavy Industries, Inc. and/or its nominee, [PHILYARDS] Holdings, Inc. that the highest bidis acceptable to the National Government. Kawasaki Heavy Industries, Inc. and/or [PHILYARDS] Holdings,Inc. shall then have a period of thirty (30) calendar days from the date of receipt of such advice from APTwithin which to exercise their "Option to Top the Highest Bid" by offering a bid equivalent to the highest bidplus five (5%) percent thereof.As petitioner was declared the highest bidder, the COP approved the sale on December 3, 1993 "subject tothe right of Kawasaki Heavy Industries, Inc./[PHILYARDS] Holdings, Inc. to top JGSMI's bid by 5% asspecified in the bidding rules."On December 29, 1993, petitioner informed APT that it was protesting the offer of PHI to top its bid on thegrounds that: (a) the KAWASAKI/PHI consortium composed of KAWASAKI, [PHILYARDS], Mitsui, Keppel, SMGroup, ICTSI and Insular Life violated the ASBR because the last four (4) companies were the losing biddersthereby circumventing the law and prejudicing the weak winning bidder; (b) only KAWASAKI could exercisethe right to top; (c) giving the same option to top to PHI constituted unwarranted benefit to a third party;(d) no right of first refusal can be exercised in a public bidding or auction sale; and (e) the JG Summitconsortium was not estopped from questioning the proceedings.On February 2, 1994, petitioner was notified that PHI had fully paid the balance of the purchase price ofthe subject bidding. On February 7, 1994, the APT notified petitioner that PHI had exercised its option totop the highest bid and that the COP had approved the same on January 6, 1994. On February 24, 1994,the APT and PHI executed a Stock Purchase Agreement. Consequently, petitioner filed with this Court aPetition for Mandamus under G.R. No. 114057. On May 11, 1994, said petition was referred to the Court ofAppeals. On July 18, 1995, the Court of Appeals denied the same for lack of merit. It ruled that the petitionfor mandamus was not the proper remedy to question the constitutionality or legality of the right of firstrefusal and the right to top that was exercised by KAWASAKI/PHI, and that the matter must be brought "bythe proper party in the proper forum at the proper time and threshed out in a full blown trial." The Court ofAppeals further ruled that the right of first refusal and the right to top are prima facie legal and that thepetitioner, "by participating in the public bidding, with full knowledge of the right to top granted toKAWASAKI/[PHILYARDS] isestopped from questioning the validity of the award given to [PHILYARDS] afterthe latter exercised the right to top and had paid in full the purchase price of the subject shares, pursuantto the ASBR." Petitioner filed a Motion for Reconsideration of said Decision which was denied on March 15,1996. Petitioner thus filed a Petition for Certiorari with this Court alleging grave abuse of discretion on thepart of the appellate court.On November 20, 2000, this Court rendered x x x [a] Decision ruling among others that the Court ofAppeals erred when it dismissed the petition on the sole ground of the impropriety of the special civilaction of mandamus because the petition was also one of certiorari. It further ruled that a shipyard likePHILSECO is a public utility whose capitalization must be sixty percent (60%) Filipino-owned. Consequently,the right to top granted to KAWASAKI under the Asset Specific Bidding Rules (ASBR) drafted for the sale ofthe 87.67% equity of the National Government in PHILSECO is illegal not only because it violates therules on competitive bidding but more so, because it allows foreign corporations to own more than 40%equity in the shipyard. It also held that "although the petitioner had the opportunity to examine the ASBRbefore it participated in the bidding, it cannot be estopped from questioning the unconstitutional, illegaland inequitable provisions thereof." Thus, this Court voided the transfer of the national government's87.67% share in PHILSECO to Philyard[s] Holdings, Inc., and upheld the right of JG Summit, as the highestbidder, to take title to the said shares, viz:
WHEREFORE, the instant petition for review on certiorari is GRANTED. The assailed Decision and Resolutionof the Court of Appeals are REVERSED and SET ASIDE. Petitioner is ordered to pay to APT its bid price ofTwo Billion Thirty Million Pesos (P2,030,000,000.00), less its bid deposit plus interests upon the finality ofthisPHILSECO's total capitalization;(d) return to private respondent PHGI the amount of Two Billion One Hundred Thirty-One Million FiveHundredof first refusal only up to 40% of the total capitalization of PHILSECO; and (3) Whether the right to topgrantednature, a shipyard is not a public utility4 and that no law declares a shipyard to be a public utility. 5 On thesecond issue, we found nothing in the 1977 Joint Venture Agreement (JVA) which prevents Kawasaki HeavyIndustries, Ltd. of Kobe, Japan (KAWASAKI) from acquiring more than 40% of PHILSECOs totalcapitalization.6 On the final issue, we held that the right to top granted to KAWASAKI in exchange for itsright of first refusal did not violate the principles of competitive bidding. 7On October 20, 2003, the petitioner filed a Motion for Reconsideration 8 and a Motion to Elevate This Caseto the Court En Banc.9 Public respondents Committee on Privatization (COP) and Asset Privatization Trust(APT), and private respondent Philyards Holdings, Inc. (PHILYARDS) filed their Comments on J.G. SummitHoldings, Inc.s (JG Summits) Motion for Reconsideration and Motion to Elevate This Case to the Court EnBanc on January 29, 2004 and February 3, 2004, respectively.II. IssuesBased areconsideration of this Courts Resolution of September 24, 2003.Motion to Elevate this Case to theCourt En BancThe petitioner prays for the elevation of the case to the Court en banc on the following grounds:
1. The main issue of the propriety of the bidding process involved in the present case has beenconfused with the policy issue of the supposed fate of the shipping industry which has never beenan issue that is determinative of this case.102. The present case may be considered under the Supreme Court Resolution dated February 23,1984 which included among en banc cases those involving a novel question of law and those wherea doctrine or principle laid down by the Court en banc or in division may be modified or reversed.113. There was clear executive interference in the judicial functions of the Court when the HonorableJose Isidro Camacho, Secretary of Finance, forwarded to Chief Justice Davide, a memorandum datedNovember 5, 2001, attaching a copy of the Foreign Chambers Report dated October 17, 2001,which matter was placed in the agenda of the Court and noted by it in a formal resolution datedNovember 28, 2001.12Opposing J.G. Summits motion to elevate the case en banc, PHILYARDS points out the petitionersinconsistency in previously opposing PHILYARDS Motion to Refer the Case to the Court EnBanc. PHILYARDS contends that J.G. Summit should now be estopped from asking that the case be referredto the Court en banc. PHILYARDS further contends that the Supreme Court en banc is not an appellatecourt to which decisions or resolutions of its divisions may be appealed citing Supreme Court Circular No.2-89 dated February 7, 1989.13 PHILYARDS also alleges that there is no novel question of law involved inthe present case as the assailed Resolution was based on well-settled jurisprudence. Likewise, PHILYARDSstresses that the Resolution was merely an outcome of the motions for reconsideration filed by it and theCOP and APT and is "consistent with the inherent power of courts to amend and control its process andorders so as to make them conformable to law and justice. (Rule 135, sec. 5)" 14Private respondent belittlesthe petitioners allegations regarding the change in ponente and the alleged executive interference asshown by former Secretary of Finance Jose Isidro Camachos memorandum dated November 5, 2001arguing that these do not justify a referral of the present case to the Court en banc.In insisting that its Motion to Elevate This Case to the Court En Banc should be granted, J.G. Summit furtherargued that: its Opposition to the Office of the Solicitor Generals Motion to Refer is different from its ownMotion to Elevate; different grounds are invoked by the two motions; there was unwarranted "executiveinterference"; and the change in ponente is merely noted in asserting that this case should be decided bythe Court en banc.15We find no merit in petitioners contention that the propriety of the bidding process involved in the presentcase has been confused with the policy issue of the fate of the shipping industry which, petitionermaintains, has never been an issue that is determinative of this case. The Courts Resolution of September24, 2003 reveals a clear and definitive ruling on the propriety of the bidding process. In discussing whetherthe right to top granted to KAWASAKI in exchange for its right of first refusal violates the principles ofcompetitive bidding, we made an exhaustive discourse on the rules and principles of public bidding andwhether they were complied with in the case at bar. 16This Court categorically ruled on the petitionersargument that PHILSECO, as a shipyard, is a public utility which should maintain a 60%-40% Filipinoforeign equity ratio, as it was a pivotal issue. In doing so, we recognized the impact of our ruling on theshipbuilding industry which was beyond avoidance.17We reject petitioners argument that the present case may be considered under the Supreme CourtResolution dated February 23, 1984 which included among en banc cases those involving a novel questionof law and those where a doctrine or principle laid down by the court en banc or in division may bemodified or reversed. The case was resolved based on basic principles of the right of first refusal incommercial law and estoppel in civil law. Contractual obligations arising from rights of first refusal are notnew in this jurisdiction and have been recognized in numerous cases. 18 Estoppel is too known a civil lawconcept to require an elongated discussion. Fundamental principles on public bidding were likewise used toresolve the issues raised by the petitioner. To be sure, petitioner leans on the right to top in a public
bidding in arguing that the case at bar involves a novel issue. We are not swayed. The right to top wasmerely a condition or a reservation made in the bidding rules which was fully disclosed to all biddingparties. In Bureau Veritas, represented by Theodor H. Hunermann v. Office of the President, etal., 19 we dealt with this conditionality, viz:x x x It must be stressed, as held in the case of A.C. Esguerra & Sons v. Aytona, et al., (L-18751, 28 April1962, 4 SCRA 1245), that in an "invitation to bid, there is a condition imposed upon the bidders tothe effect that the bidding shall be subject to the right of the government to reject any and allbids subject to its discretion. In the case at bar, the government has made its choice andunless an unfairness or injustice is shown, the losing bidders have no cause to complain norright to dispute that choice. This is a well-settled doctrine in this jurisdiction and elsewhere."The discretion to accept or reject a bid and award contracts is vested in the Government agenciesentrusted with that function. The discretion given to the authorities on this matter is of such wide latitudethat the Courts will not interfere therewith, unless it is apparent that it is used as a shield to a fraudulentaward (Jalandoni v. NARRA, 108 Phil. 486 [1960]). x x x The exercise of this discretion is a policy decisionthat necessitates prior inquiry, investigation, comparison, evaluation, and deliberation. This task can bestbe discharged by the Government agencies concerned, not by the Courts. The role of the Courts is toascertain whether a branch or instrumentality of the Government has transgressed its constitutionalboundaries. But the Courts will not interfere with executive or legislative discretion exercised within thoseboundaries. Otherwise, it strays into the realm of policy decision-making.It is only upon a clear showing of grave abuse of discretion that the Courts will set aside the award of acontract made by a government entity. Grave abuse of discretion implies a capricious, arbitrary andwhimsical exercise of power (Filinvest Credit Corp. v. Intermediate Appellate Court, No. 65935, 30September 1988, 166 SCRA 155). The abuse of discretion must be so patent and gross as to amount to anevasion of positive duty or to a virtual refusal to perform a duty enjoined by law, as to act at all incontemplation of law, where the power is exercised in an arbitrary and despotic manner by reason ofpassion or hostility (Litton Mills, Inc. v. Galleon Trader, Inc., et al[.], L-40867, 26 July 1988, 163 SCRA 489).The facts in this case do not indicate any such grave abuse of discretion on the part of public respondentswhenan offer most advantageous to the Government." It is a well-settled rule that where suchreservation is made in an Invitation to Bid, the highest or lowest bidder, as the case may be, isnot entitled to an award as a matter of right (C & C Commercial Corp. v. Menor, L-28360, 27 January1983, 120 SCRA 112). Even the lowest Bid or any Bid may be rejected or, in the exercise of sounddiscretion, the award may be made to another than the lowest bidder (A.C. Esguerra & Sons v. Aytona,supra, citing 43 Am. Jur., 788). (emphases supplied)1awphi1.ntLike the condition in the Bureau Veritas case, the right to top was a condition imposed by thegovernment in the bidding rules which was made known to all parties. It was a condition imposed onall bidders equally, based on the APTs exercise of its discretion in deciding on how best toprivatize the governments shares in PHILSECO. It was not a whimsical or arbitrary condition pluckedfrom the ether and inserted in the bidding rules but a condition which the APT approved as the best waythe government could comply with its contractual obligations to KAWASAKI under the JVA and its mandateof getting the most advantageous deal for the government. The right to top had its history in the mutualright of first refusal in the JVA and was reached by agreement of the government and KAWASAKI.Further, there is no "executive interference" in the functions of this Court by the mere filing of amemorandum by Secretary of Finance Jose Isidro Camacho. The memorandum was merely "noted" toacknowledge its filing. It had no further legal significance. Notably too, the assailed Resolution dated
September 24, 2003 was decided unanimously by the Special First Division in favor of therespondents.Again, we emphasize that a decision or resolution of a Division is that of the Supreme Court 20 and theCourt en banc is not an appellate court to which decisions or resolutions of a Division may be appealed. 21For all the foregoing reasons, we find no basis to elevate this case to the Court en banc.Motion for ReconsiderationThree principal arguments were raised in the petitioners Motion for Reconsideration. First, that a fairresolution of the case should be based on contract law, not on policy considerations; the contracts do notauthorize the right to top to be derived from the right of first refusal. 22 Second, that neither the right of firstrefusal nor the right to top can be legally exercised by the consortium which is not the proper partygranted such right under either the JVA or the Asset Specific Bidding Rules (ASBR). 23 Third, that themaintenance of the 60%-40% relationship between the National Investment and Development Corporation(NIDC) and KAWASAKI arises from contract and from the Constitution because PHILSECO is a landholdingcorporation and need not be a public utility to be bound by the 60%-40% constitutional limitation. 24On the other hand, private respondent PHILYARDS asserts that J.G. Summit has not been able to showcompelling reasons to warrant a reconsideration of the Decision of the Court. 25 PHILYARDS denies that theDecision is based mainly on policy considerations and points out that it is premised on principles governingobligations and contracts and corporate law such as the rule requiring respect for contractual stipulations,upholding rights of first refusal, and recognizing the assignable nature of contracts rights. 26 Also, the rulingthat shipyards are not public utilities relies on established case law and fundamental rules of statutoryconstruction. PHILYARDS stresses that KAWASAKIs right of first refusal or even the right to top is notlimited to the 40% equity of the latter.27 On the landholding issue raised by J.G. Summit, PHILYARDSemphasizes that this is a non-issue and even involves a question of fact. Even assuming that this Court cantake cognizance of such question of fact even without the benefit of a trial, PHILYARDS opines thatlandholding by PHILSECO at the time of the bidding is irrelevant because what is essential is thatultimately a qualified entity would eventually hold PHILSECOs real estate properties. 28 Further, given theassignable nature of the right of first refusal, any applicable nationality restrictions, including landholdinglimitations, would not affect the right of first refusal itself, but only the manner of its exercise. 29 Also,PHILYARDS argues that if this Court takes cognizance of J.G. Summits allegations of fact regardingPHILSECOs landholding, it must also recognize PHILYARDS assertions that PHILSECOs landholdings weresold to another corporation.30 As regards the right of first refusal, private respondent explains thatKAWASAKIs reduced shareholdings (from 40% to 2.59%) did not translate to a deprivation or loss of itscontractually granted right of first refusal.31 Also, the bidding was valid because PHILYARDS exercised theright to top and it was of no moment that losing bidders later joined PHILYARDS in raising the purchaseprice.32In cadence with the private respondent PHILYARDS, public respondents COP and APT contend:1. The conversion of the right of first refusal into a right to top by 5% does not violate any provisionin the JVA between NIDC and KAWASAKI.2. PHILSECO is not a public utility and therefore not governed by the constitutional restriction onforeign ownership.3. The petitioner is legally estopped from assailing the validity of the proceedings of the publicbidding as it voluntarily submitted itself to the terms of the ASBR which included the provision onthe right to top.
4. The right to top was exercised by PHILYARDS as the nominee of KAWASAKI and the fact thatPHILYARDS formed a consortium to raise the required amount to exercise the right to top thehighest bid by 5% does not violate the JVA or the ASBR.5. The 60%-40% Filipino-foreign constitutional requirement for the acquisition of lands does notapply to PHILSECO because as admitted by petitioner itself, PHILSECO no longer owns real property.6. Petitioners motion to elevate the case to the Court en banc is baseless and would only delay thetermination of this case.33In a Consolidated Comment dated March 8, 2004, J.G. Summit countered the arguments of the public andprivate respondents in this wise:1. The award by the APT of 87.67% shares of PHILSECO to PHILYARDS with losing bidders throughthe exercise of a right to top, which is contrary to law and the constitution is null and void for beingviolative of substantive due process and the abuse of right provision in the Civil Code.a. The bidders[] right to top was actually exercised by losing bidders.b. The right to top or the right of first refusal cannot co-exist with a genuine competitivebidding.c. The benefits derived from the right to top were unwarranted.2. The landholding issue has been a legitimate issue since the start of this case but is shamelesslyignored by the respondents.a. The landholding issue is not a non-issue.b. The landholding issue does not pose questions of fact.c. That PHILSECO owned land at the time that the right of first refusal was agreed upon andat the time of the bidding are most relevant.d. Whether a shipyard is a public utility is not the core issue in this case.3. Fraud and bad faith attend the alleged conversion of an inexistent right of first refusal to the rightto top.a. The history behind the birth of the right to top shows fraud and bad faith.b. The right of first refusal was, indeed, "effectively useless."4. Petitioner is not legally estopped to challenge the right to top in this case.a. Estoppel is unavailing as it would stamp validity to an act that is prohibited by law oragainst public policy.b. Deception was patent; the right to top was an attractive nuisance.c. The 10% bid deposit was placed in escrow.
J.G. Summits insistence that the right to top cannot be sourced from the right of first refusal is not newand we have already ruled on the issue in our Resolution of September 24, 2003. We upheld the mutualright of first refusal in the JVA.34 We also ruled that nothing in the JVA prevents KAWASAKI from acquiringmore than 40% of PHILSECOs total capitalization. 35 Likewise, nothing in the JVA or ASBR bars theconversion of the right of first refusal to the right to top. In sum, nothing new and of significance in thepetitioners pleading warrants a reconsideration of our ruling.Likewise, we already disposed of the argument that neither the right of first refusal nor the right to top canlegally be exercised by the consortium which is not the proper party granted such right under either theJthe right to top is not contrary to law, public policy or public morals. There is nothing in the ASBR that barsthe losing bidders from joining either the winning bidder (should the right to top is not exercised) orKAWASAKI/PHI (should it exercise its right to top as it did), to raise the purchase price. The petitioner didnot allege, nor was it shown by competent evidence, that the participation of the losing bidders in thepublic bidding was done with fraudulent intent. Absent any proof of fraud, the formation by [PHILYARDS] ofa consortium is legitimate in a free enterprise system. The appellate court is thus correct in holding thepetitioner estopped from questioning the validity of the transfer of the National Government's shares inPHILSECO to respondent.36Further, we see no inherent illegality on PHILYARDS act in seeking funding from parties who were losingbidders. This is a purely commercial decision over which the State should not interfere absent any legalinfirmity. It is emphasized that the case at bar involves the disposition of shares in a corporation which thegovernment sought to privatize. As such, the persons with whom PHILYARDS desired to enter into businesswith in order to raise funds to purchase the shares are basically its business. This is in contrast to a caseinvolving a contract for the operation of or construction of a government infrastructure where the identityof the buyer/bidder or financier constitutes an important consideration. In such cases, the governmentwould have to take utmost precaution to protect public interest by ensuring that the parties with which it iscontracting have the ability to satisfactorily construct or operate the infrastructure.On the landholding issue, J.G. Summit submits that since PHILSECO is a landholding company, KAWASAKIcould exercise its right of first refusal only up to 40% of the shares of PHILSECO due to the constitutionalprohibition on landholding by corporations with more than 40% foreign-owned equity. It further argues thatsince KAWASAKI already held at least 40% equity in PHILSECO, the right of first refusal was inutile and asslandholdings.39 It contends, however, that even if PHILSECO owned land, this would not affect the right offirst refusal but only the exercise thereof. If the land is retained, the right of first refusal, being a propertyright, could be assigned to a qualified party. In the alternative, the land could be divested before theexercise of the right of first refusal. In the case at bar, respondents assert that since the right of firstrefusal was validly converted into a right to top, which was exercised not by KAWASAKI, but by PHILYARDSwhich is a Filipino corporation (i.e., 60% of its shares are owned by Filipinos), then there is no violation ofthe Constitution.40 At first, it would seem that questions of fact beyond cognizance by this Court wereinvolved in the issue. However, the records show that PHILYARDS admits it had owned land up untilthe time of the bidding.41 Hence, the only issue is whether KAWASAKI had a valid right of firstrefusal over PHILSECO shares under the JVA considering that PHILSECO owned land until thetime of the bidding and KAWASAKI already held 40% of PHILSECOs equity.We uphold the validity of the mutual rights of first refusal under the JVA between KAWASAKI and NIDC. Firstof all, the right of first refusal is a property right of PHILSECO shareholders, KAWASAKI and NIDC, under the
terms of their JVA. This right allows them to purchase the shares of their co-shareholder before they areoffered to a third party. The agreement of co-shareholders to mutually grant this right to eachother, by itself, does not constitute a violation of the provisions of the Constitution limitingland ownership to Filipinos and Filipino corporations. As PHILYARDS correctly puts it, if PHILSECOstill owns land, the right of first refusal can be validly assigned to a qualified Filipino entity in order tomaintain the 60%-40% ratio. This transfer, by itself, does not amount to a violation of the Anti-DummyLaws, absent proof of any fraudulent intent. The transfer could be made either to a nominee or such otherparty which the holder of the right of first refusal feels it can comfortably do business with. Alternatively,PHILSECO may divest of its landholdings, in which case KAWASAKI, in exercising its right of first refusal, canexceed 40% of PHILSECOs equity. In fact, it can even be said that if the foreign shareholdings of alandholding corporation exceeds 40%, it is not the foreign stockholders ownership of theshares which is adversely affected but the capacity of the corporation to own land that is, thecorporation becomes disqualified to own land. This finds support under the basic corporate law principlethat the corporation and its stockholders are separate juridical entities. In this vein, the right of first refusalover shares pertains to the shareholders whereas the capacity to own land pertains to the corporation.Hence, the fact that PHILSECO owns land cannot deprive stockholders of their right of first refusal. No lawdisqualifies a person from purchasing shares in a landholding corporation even if the latter willexceed the allowed foreign equity, what the law disqualifies is the corporation from owningland. This is the clear import of the following provisions in the Constitution:Section 2. All lands of the public domain, waters, minerals, coal, petroleum, and other mineral oils, allforces of potential energy, fisheries, forests or timber, wildlife, flora and fauna, and other natural resourcesare owned by the State. With the exception of agricultural lands, all other natural resources shall not bealienated. The exploration, development, and utilization of natural resources shall be under the full controland supervision of the State. The State may directly undertake such activities, or it may enter into coproduction, joint venture, or production-sharing agreements with Filipino citizens, or corporations orassociations at least sixty per centum of whose capital is owned by such citizens. Suchagreements may be for a period not exceeding twenty-five years, renewable for not more than twenty-fiveyears, and under such terms and conditions as may be provided by law. In cases of water rights forirrigation, water supply, fisheries, or industrial uses other than the development of water power, beneficialuse may be the measure and limit of the grant.xxx xxx xxxSection 7. Save in cases of hereditary succession, no private lands shall be transferred or conveyedexcept to individuals, corporations, or associations qualified to acquire or hold lands of thepublic domain.42(emphases supplied)The petitioner further argues that "an option to buy land is void in itself (Philippine Banking Corporation v.Lui She, 21 SCRA 52 [1967]). The right of first refusal granted to KAWASAKI, a Japanese corporation, issimilarly void. Hence, the right to top, sourced from the right of first refusal, is also void." 43 Contrary to thecontention of petitioner, the case of Lui She did not that say "an option to buy land is void in itself," for weruled as follows:x x x To be sure, a lease to an alien for a reasonable period is valid. So is an option giving analien the right to buy real property on condition that he is granted Philippine citizenship. Asthis Court said in Krivenko vs. Register of Deeds:[A]liens are not completely excluded by the Constitution from the use of lands for residential purposes.Since their residence in the Philippines is temporary, they may be granted temporary rights such as alease contract which is not forbidden by the Constitution. Should they desire to remain here forever andshare our fortunes and misfortunes, Filipino citizenship is not impossible to acquire.
But if an alien is given not only a lease of, but also an option to buy, a piece of land, by virtueof which the Filipino owner cannot sell or otherwise dispose of his property, this to last for 50years, then it becomes clear that the arrangement is a virtual transfer of ownership wherebythe owner divests himself in stages not only of the right to enjoy the land (jus possidendi, jusutendi, jus fruendi and jus abutendi) but also of the right to dispose of it (jus disponendi) rights the sum total of which make up ownership. It is just as if today the possession istransferred, tomorrow, the use, the next day, the disposition, and so on, until ultimately all therights of which ownership is made up are consolidated in an alien. And yet this is just exactly what theparties in this case did within this pace of one year, with the result that Justina Santos'[s] ownership of herproperty was reduced to a hollow concept. If this can be done, then the Constitutional ban against alienlandholding in the Philippines, as announced in Krivenko vs. Register of Deeds, is indeed in graveperil.44 (emphases supplied; Citations omitted)In Lui She, the option to buy was invalidated because it amounted to a virtual transfer of ownership as theowner could not sell or dispose of his properties. The contract in Lui She prohibited the owner of the landfrom selling, donating, mortgaging, or encumbering the property during the 50-year period of the option tobuy. This is not so in the case at bar where the mutual right of first refusal in favor of NIDC and KAWASAKIdoes not amount to a virtual transfer of land to a non-Filipino. In fact, the case at bar involves a right offirst refusal over shares of stock while the Lui She case involves an option to buy the land itself.As discussed earlier, there is a distinction between the shareholders ownership of shares and thecorporations ownership of land arising from the separate juridical personalities of the corporation and itsshareholders.We note that in its Motion for Reconsideration, J.G. Summit alleges that PHILSECO continues to violate theConstitution as its foreign equity is above 40% and yet owns long-term leasehold rights which arereal rights.45It cites Article 415 of the Civil Code which includes in the definition of immovable property,"contracts for public works, and servitudes and other real rights over immovable property." 46 Any existinglandholding, however, is denied by PHILYARDS citing its recent financial statements. 47 First, these arequestions of fact, the veracity of which would require introduction of evidence. The Court needs to validatethese factual allegations based on competent and reliable evidence. As such, the Court cannot resolve thequestions they pose. Second, J.G. Summit misreads the provisions of the Constitution cited in its ownpleadings, to wit:29.2 Petitioner has consistently pointed out in the past that private respondent is not a 60%-40%corporation, and this violates the Constitution x x x The violation continues to this day because under thelaw, it continues to own real propertyxxx xxx xxx32. To review the constitutional provisions involved, Section 14, Article XIV of the 1973 Constitution (theJVA was signed in 1977), provided:"Save in cases of hereditary succession, no private lands shall be transferred or conveyed except toindividuals, corporations, or associations qualified to acquire or hold lands of the public domain."32.1 This provision is the same as Section 7, Article XII of the 1987 Constitution.32.2 Under the Public Land Act, corporations qualified to acquire or hold lands of the public domain arecorporations at least 60% of which is owned by Filipino citizens (Sec. 22, Commonwealth Act 141, asamended). (emphases supplied)As correctly observed by the public respondents, the prohibition in the Constitution applies only toownership of land.48 It does not extend to immovable or real property as defined under Article
415 of the Civil Code.Otherwise, we would have a strange situation where the ownership of immovableproperty such as trees, plants and growing fruit attached to the land 49 would be limited to Filipinos andFilipino corporations only.III.WHEREFORE, in view of the foregoing, the petitioners Motion for Reconsideration is DENIED WITHFINALITY and the decision appealed from is AFFIRMED. The Motion to Elevate This Case to the Court EnBanc is likewise DENIED for lack of merit.SO ORDERED.
in favor of the vendee Corporation to operate the service therein involved. 1 On May 19, 1959, the PSCgranted the provisional permit prayed for, upon the condition that "it may be modified or revoked by theCommission at any time, shall be subject to whatever action that may be taken on the basic applicationand shall be valid only during the pendency of said application." Before the PSC could take final action onsaid application for approval of sale, however, the Sheriff of Manila, on July 7, 1959, levied on two of thefive certificates of public convenience involved therein, namely, those issued under PSC cases Nos. 59494and 63780, pursuant to a writ of execution issued by the Court of First Instance of Pangasinan in Civil CaseNo. 13798, in favor of Eusebio Ferrer, plaintiff, judgment creditor, against Valentin Fernando, defendant,judgment debtor. The Sheriff made and entered the levy in the records of the PSC. On July 16, 1959, apublic sale was conducted by the Sheriff of the said two certificates of public convenience. Ferrer was thehighest bidder, and a certificate of sale was issued in his name.Thereafter, Ferrer sold the two certificates of public convenience to Pantranco, and jointly submitted forapproval their corresponding contract of sale to the PSC.2 Pantranco therein prayed that it be authorizedprovisionally to operate the service involved in the said two certificates.The applications for approval of sale, filed before the PSC, by Fernando and the Corporation, Case No.124057, and that of Ferrer and Pantranco, Case No. 126278, were scheduled for a joint hearing. In themeantime, to wit, on July 22, 1959, the PSC issued an order disposing that during the pendency of thecases and before a final resolution on the aforesaid applications, the Pantranco shall be the one to operateprovisionally the service under the twocertificates embraced in the contract between Ferrer and Pantranco.The Corporation took issue with this particular ruling of the PSC and elevated the matter to the SupremeCourt,3 which decreed, after deliberation, that until the issue on the ownership of the disputed certificatesshall have been finally settled by the proper court, the Corporation should be the one to operate the linesprovisionally.On November 4, 1959, the Corporation filed in the Court of First Instance of Manila, a complaint for theannulment of the sheriff's sale of the aforesaid two certificates of public convenience (PSC Cases Nos.59494 and 63780) in favor of the defendant Ferrer, and the subsequent sale thereof by the latter toPantranco, against Ferrer, Pantranco and the PSC. The plaintiff Corporation prayed therein that all theorders of the PSC relative to the parties' dispute over the said certificates be annulled.In separate answers, the defendants Ferrer and Pantranco averred that the plaintiff Corporation had novalid title to the certificates in question because the contract pursuant to which it acquired them fromFernando was subject to a suspensive condition the approval of the PSC which has not yet beenfulfilled, and, therefore, the Sheriff's levy and the consequent sale at public auction of the certificatesreferred to, as well as the sale of the same by Ferrer to Pantranco, were valid and regular, and vested untoPantranco, a superior right thereto.Pantranco, on its part, filed a third-party complaint against Jose M. Villarama, alleging that Villarama andthe Corporation, are one and the same; that Villarama and/or the Corporation was disqualified fromoperating the two certificates in question by virtue of the aforementioned agreement between saidVillarama and Pantranco, which stipulated that Villarama "shall not for a period of 10 years from the dateof this sale, apply for any TPU service identical or competing with the buyer."Upon the joinder of the issues in both the complaint and third-party complaint, the case was tried, andthereafter decision was rendered in the terms, as above stated.As stated at the beginning, all the parties involved have appealed from the decision. They submitted ajoint record on appeal.Pantranco disputes the correctness of the decision insofar as it holds that Villa Rey Transit, Inc.(Corporation) is a distinct and separate entity from Jose M. Villarama; that the restriction clause in the
contract of January 8, 1959 between Pantranco and Villarama is null and void; that the Sheriff's sale of July16, 1959, is likewise null and void; and the failure to award damages in its favor and against Villarama.Ferrer, for his part, challenges the decision insofar as it holds that the sheriff's sale is null and void; and thesale of the two certificates in question by Valentin Fernando to the Corporation, is valid. He also assails theaward of P5,000.00 as attorney's fees in favor of the Corporation, and the failure to award moral damagesto him as prayed for in his counterclaim.The Corporation, on the other hand, prays for a review of that portion of the decision awarding onlyP5,000.00 as attorney's fees, and insisting that it is entitled to an award of P100,000.00 by way ofexemplary damages.After a careful study of the facts obtaining in the case, the vital issues to be resolved are: (1) Does thestipulation between Villarama and Pantranco, as contained in the deed of sale, that the former "SHALL NOTFOR A PERIOD OF 10 YEARS FROM THE DATE OF THIS SALE, APPLY FOR ANY TPU SERVICE IDENTICAL ORCOMPETING WITH THE BUYER," apply to new lines only or does it include existing lines?; (2) Assuming thatsaid stipulation covers all kinds of lines, is such stipulation valid and enforceable?; (3) In the affirmative,that said stipulation is valid, did it bind the Corporation?For convenience, We propose to discuss the foregoing issues by starting with the last proposition.The evidence has disclosed that Villarama, albeit was not an incorporator or stockholder of theCorporation, alleging that he did not become such, because he did not have sufficient funds to invest, hiswife, however, was an incorporator with the least subscribed number of shares, and was elected treasurerof the Corporation. The finances of the Corporation which, under all concepts in the law, are supposed tobe under the control and administration of the treasurer keeping them as trust fund for the Corporation,were, nonetheless, manipulated and disbursed as if they were the private funds of Villarama, in such a wayand extent that Villarama appeared to be the actual owner-treasurer of the business without regard to therights of the stockholders. The following testimony of Villarama, 4together with the other evidence onrecord, attests to that effect:Q.Doctor, I want to go back again to the incorporation of the Villa Rey Transit, Inc. You heardthe testimony presented here by the bank regarding the initial opening deposit of ONE HUNDREDFIVE THOUSAND PESOS, of which amount Eighty-Five Thousand Pesos was a check drawn byyourself personally. In the direct examination you told the Court that the reason you drew a checkfor Eighty-Five Thousand Pesos was because you and your wife, or your wife, had spent the moneyof the stockholders given to her for incorporation. Will you please tell the Honorable Court if youknew at the time your wife was spending the money to pay debts, you personally knew she wasspending the money of the incorporators?A.
You know my money and my wife's money are one. We never talk about those things.
Q.Doctor, your answer then is that since your money and your wife's money are one moneyand you did not know when your wife was paying debts with the incorporator's money?A.Because sometimes she uses my money, and sometimes the money given to her she gives tome and I deposit the money.Q.Actually, aside from your wife, you were also the custodian of some of the incorporators here,in the beginning?A.Not necessarily, they give to my wife and when my wife hands to me I did not know itbelonged to the incorporators.
Q.It supposes then your wife gives you some of the money received by her in her capacity astreasurer of the corporation?A.
Maybe.
Q.
A.
Deposit in my account.
Of all the money given to your wife, she did not receive any check?
I do not remember.
Is it usual for you, Doctor, to be given Fifty Thousand Pesos without even asking what is this?xxx
JUDGE:
Q.The subscription of your brother-in-law, Mr. Reyes, is Fifty-Two Thousand Pesos, did your wifegive you Fifty-two Thousand Pesos?A.I have testified before that sometimes my wife gives me money and I do not know exactly forwhat.The evidence further shows that the initial cash capitalization of the corporation of P105,000.00 wasmostly financed by Villarama. Of the P105,000.00 deposited in the First National City Bank of New York,representing the initial paid-up capital of the Corporation, P85,000.00 was covered by Villarama's personalcheck. The deposit slip for the said amount of P105,000.00 was admitted in evidence as Exh. 23, whichshows on its face that P20,000.00 was paid in cash and P85,000.00 thereof was covered by Check No. F50271 of the First National City Bank of New York. The testimonies of Alfonso Sancho 5 and JoaquinAmansec,6 both employees of said bank, have proved that the drawer of the check was Jose Villaramahimself.Another witness, Celso Rivera, accountant of the Corporation, testified that while in the books of thecorporation there appears an entry that the treasurer received P95,000.00 as second installment of thepaid-in subscriptions, and, subsequently, also P100,000.00 as the first installment of the offer for secondsubscriptions worth P200,000.00 from the original subscribers, yet Villarama directed him (Rivera) to makevouchers liquidating the sums.7 Thus, it was made to appear that the P95,000.00 was delivered toVillarama in payment for equipment purchased from him, and the P100,000.00 was loaned as advances tothe stockholders. The said accountant, however, testified that he was not aware of any amount of moneythat had actually passed hands among the parties involved, 8 and actually the only money of thecorporation was the P105,000.00 covered by the deposit slip Exh. 23, of which as mentioned above,P85,000.00 was paid by Villarama's personal check.Further, the evidence shows that when the Corporation was in its initial months of operation, Villaramapurchased and paid with his personal checks Ford trucks for the Corporation. Exhibits 20 and 21 disclosethat the said purchases were paid by Philippine Bank of Commerce Checks Nos. 992618-B and 993621-B,respectively. These checks have been sufficiently established by Fausto Abad, Assistant Accountant ofManila Trading & Supply Co., from which the trucks were purchased 9 and Aristedes Solano, an employee ofthe Philippine Bank of Commerce,10as having been drawn by Villarama.
Exhibits 6 to 19 and Exh. 22, which are photostatic copies of ledger entries and vouchers showing thatVillarama had co-mingled his personal funds and transactions with those made in the name of theCorporation, are very illuminating evidence. Villarama has assailed the admissibility of these exhibits,contending that no evidentiary value whatsoever should be given to them since "they were merelyphotostatic copies of the originals, the best evidence being the originals themselves." According to him, atthe time Pantranco offered the said exhibits, it was the most likely possessor of the originals thereofbecause they were stolen from the files of the Corporation and only Pantranco was able to produce thealleged photostat copies thereof.Section 5 of Rule 130 of the Rules of Court provides for the requisites for the admissibility of secondaryevidence when the original is in the custody of the adverse party, thus: (1) opponent's possession of theoriginal; (2) reasonable notice to opponent to produce the original; (3) satisfactory proof of its existence;and (4) failure or refusal of opponent to produce the original in court. 11 Villarama has practically admittedthe second and fourth requisites.12As to the third, he admitted their previous existence in the files of theCorporation and also that he had seen some of them.13 Regarding the first element, Villarama's theory isthat since even at the time of the issuance of thesubpoena duces tecum, the originals were alreadymissing, therefore, the Corporation was no longer in possession of the same. However, it is not necessaryfor a party seeking to introduce secondary evidence to show that the original is in the actual possession ofhis adversary. It is enough that the circumstances are such as to indicate that the writing is in hispossession or under his control. Neither is it required that the party entitled to the custody of theinstrument should, on being notified to produce it, admit having it in his possession. 14 Hence, secondaryevidence is admissible where he denies having it in his possession. The party calling for such evidencemay introduce a copy thereof as in the case of loss. For, among the exceptions to the best evidence rule is"when the original has been lost, destroyed, or cannot be produced in court." 15 The originals of thevouchers in question must be deemed to have been lost, as even the Corporation admits such loss. Viewedupon this light, there can be no doubt as to the admissibility in evidence of Exhibits 6 to 19 and 22.Taking account of the foregoing evidence, together with Celso Rivera's testimony, 16 it would appear that:Villarama supplied the organization expenses and the assets of the Corporation, such as trucks andequipment;17 there was no actual payment by the original subscribers of the amounts of P95,000.00 andP100,000.00 as appearing in the books;18 Villarama made use of the money of the Corporation anddeposited them to his private accounts;19 and the Corporation paid his personal accounts.20Villarama himself admitted that he mingled the corporate funds with his own money. 21 He also admittedthat gasoline purchases of the Corporation were made in his name 22 because "he had existing account withStanvac which was properly secured and he wanted the Corporation to benefit from the rebates that hereceived."23The foregoing circumstances are strong persuasive evidence showing that Villarama has been too muchinvolved in the affairs of the Corporation to altogether negative the claim that he was only a part-timegeneral manager. They show beyond doubt that the Corporation is his alter ego.It is significant that not a single one of the acts enumerated above as proof of Villarama's oneness with theCorporation has been denied by him. On the contrary, he has admitted them with offered excuses.Villarama has admitted, for instance, having paid P85,000.00 of the initial capital of the Corporation withthe lame excuse that "his wife had requested him to reimburse the amount entrusted to her by theincorporators and which she had used to pay the obligations of Dr. Villarama (her husband) incurred whilehe was still the owner of Villa Rey Transit, a single proprietorship." But with his admission that he hadreceived P350,000.00 from Pantranco for the sale of the two certificates and one unit,24 it becomes difficultto accept Villarama's explanation that he and his wife, after consultation, 25 spent the money of theirrelatives (the stockholders) when they were supposed to have their own money. Even if Pantranco paid theP350,000.00 in check to him, as claimed, it could have been easy for Villarama to have deposited said
check in his account and issued his own check to pay his obligations. And there is no evidence adducedthat the said amount of P350,000.00 was all spent or was insufficient to settle his prior obligations in hisbusiness, and in the light of the stipulation in the deed of sale between Villarama and Pantranco thatP50,000.00 of the selling price was earmarked for the payments of accounts due to his creditors, theexcuse appears unbelievable.On his having paid for purchases by the Corporation of trucks from the Manila Trading & Supply Co. withhis personal checks, his reason was that he was only sharing with the Corporation his credit with somecompanies. And his main reason for mingling his funds with that of the Corporation and for the latter'spaying his private bills is that it would be more convenient that he kept the money to be used in payingthe registration fees on time, and since he had loaned money to the Corporation, this would be set off bythe latter's paying his bills. Villarama admitted, however, that the corporate funds in his possession werenot only for registration fees but for other important obligations which were not specified. 26Indeed, while Villarama was not the Treasurer of the Corporation but was, allegedly, only a part-timemanager,27 he admitted not only having held the corporate money but that he advanced and lent funds forthe Corporation, and yet there was no Board Resolution allowing it. 28Villarama's explanation on the matter of his involvement with the corporate affairs of the Corporation onlyrenders more credible Pantranco's claim that his control over the corporation, especially in themanagement and disposition of its funds, was so extensive and intimate that it is impossible to segregateand identify which money belonged to whom. The interference of Villarama in the complex affairs of thecorporation, and particularly its finances, are much too inconsistent with the ends and purposes of theCorporation law, which, precisely, seeks to separate personal responsibilities from corporate undertakings.It is the very essence of incorporation that the acts and conduct of the corporation be carried out in its owncorporate name because it has its own personality.The doctrine that a corporation is a legal entity distinct and separate from the members and stockholderswho compose it is recognized and respected in all cases which are within reason and the law. 29 When thefiction is urged as a means of perpetrating a fraud or an illegal act or as a vehicle for the evasion of anexisting obligation, the circumvention of statutes, the achievement or perfection of a monopoly orgenerally the perpetration of knavery or crime,30 the veil with which the law covers and isolates thecorporation from the members or stockholders who compose it will be lifted to allow for its considerationmerely as an aggregation of individuals.Upon the foregoing considerations, We are of the opinion, and so hold, that the preponderance of evidencehave shown that the Villa Rey Transit, Inc. is an alter ego of Jose M. Villarama, and that the restrictiveclause in the contract entered into by the latter and Pantranco is also enforceable and binding against thesaid Corporation. For the rule is that a seller or promisor may not make use of a corporate entity as ameans of evading the obligation of his covenant.31 Where the Corporation is substantially the alter ego ofthe covenantor to the restrictive agreement, it can be enjoined from competing with the covenantee. 32The Corporation contends that even on the supposition that Villa Rey Transit, Inc. and Villarama are oneand the same, the restrictive clause in the contract between Villarama and Pantranco does not include thepurchase of existing lines but it only applies to application for the new lines. The clause in dispute readsthus:(4) The SELLER shall not, for a period of ten (10) years from the date of this sale apply for any TPUservice identical or competing with the BUYER. (Emphasis supplied)As We read the disputed clause, it is evident from the context thereof that the intention of the parties wasto eliminate the seller as a competitor of the buyer for ten years along the lines of operation covered bythe certificates of public convenience subject of their transaction. The word "apply" as broadly used has for
frame of reference, a service by the seller on lines or routes that would compete with the buyer along theroutes acquired by the latter. In this jurisdiction, prior authorization is needed before anyone can operate aTPU service,33whether the service consists in a new line or an old one acquired from a previous operator.The clear intention of the parties was to prevent the seller from conducting any competitive line for 10years since, anyway, he has bound himself not to apply for authorization to operate along such lines forthe duration of such period.34If the prohibition is to be applied only to the acquisition of new certificates of public convenience thru anapplication with the Public Service Commission, this would, in effect, allow the seller just the same tocompete with the buyer as long as his authority to operate is only acquired thru transfer or sale from aprevious operator, thus defeating the intention of the parties. For what would prevent the seller, under thecircumstances, from having a representative or dummy apply in the latter's name and then later ontransferring the same by sale to the seller? Since stipulations in a contract is the law between thecontracting parties,Every person must, in the exercise of his rights and in the performance of his duties, act withjustice, give everyone his due, and observe honesty and good faith. (Art. 19, New Civil Code.)We are not impressed of Villarama's contention that the re-wording of the two previous drafts of thecontract of sale between Villarama and Pantranco is significant in that as it now appears, the partiesintended to effect the least restriction. We are persuaded, after an examination of the supposed drafts,that the scope of the final stipulation, while not as long and prolix as those in the drafts, is just as broadand comprehensive. At most, it can be said that the re-wording was done merely for brevity and simplicity.The evident intention behind the restriction was to eliminate the sellers as a competitor, and this must be,considering such factors as the good will35 that the seller had already gained from the riding public and hisadeptness and proficiency in the trade. On this matter, Corbin, an authority on Contracts has this to say. 36When one buys the business of another as a going concern, he usually wishes to keep it going; hewishes to get the location, the building, the stock in trade, and the customers. He wishes to stepinto the seller's shoes and to enjoy the same business relations with other men. He is willing to paymuch more if he can get the "good will" of the business, meaning by this the good will of thecustomers, that they may continue to tread the old footpath to his door and maintain with him thebusiness relations enjoyed by the seller.... In order to be well assured of this, he obtains and pays for the seller's promise not to reopenbusiness in competition with the business sold.As to whether or not such a stipulation in restraint of trade is valid, our jurisprudence on the matter 37says:The law concerning contracts which tend to restrain business or trade has gone through a longseries of changes from time to time with the changing condition of trade and commerce. Withtrifling exceptions, said changes have been a continuous development of a general rule. The earlycases show plainly a disposition to avoid and annul all contract which prohibited or restrained anyone from using a lawful trade "at any time or at any place," as being against the benefit of thestate. Later, however, the rule became well established that if the restraint was limited to "a certaintime" and within "a certain place," such contracts were valid and not "against the benefit of thestate." Later cases, and we think the rule is now well established, have held that a contract inrestraint of trade is valid providing there is a limitation upon either time or place. A contract,however, which restrains a man from entering into business or trade without either a limitation asto time or place, will be held invalid.
The public welfare of course must always be considered and if it be not involved and the restraintupon one party is not greater than protection to the other requires, contracts like the one we arediscussing will be sustained. The general tendency, we believe, of modern authority, is to make thetest whether the restraint is reasonably necessary for the protection of the contracting parties. Ifthe contract is reasonably necessary to protect the interest of the parties, it will be upheld.(Emphasis supplied.)Analyzing the characteristics of the questioned stipulation, We find that although it is in the nature of anagreement suppressing competition, it is, however, merely ancillary or incidental to the main agreementwhich is that of sale. The suppression or restraint is only partial or limited: first, in scope, it refers only toapplication for TPU by the seller in competition with the lines sold to the buyer; second, in duration, it isonly for ten (10) years; and third, with respect to situs or territory, the restraint is only along the linescovered by the certificates sold. In view of these limitations, coupled with the consideration of P350,000.00for just two certificates of public convenience, and considering, furthermore, that the disputed stipulationis only incidental to a main agreement, the same is reasonable and it is not harmful nor obnoxious topublic service.38 It does not appear that the ultimate result of the clause or stipulation would be to leavesolely to Pantranco the right to operate along the lines in question, thereby establishing monopoly orpredominance approximating thereto. We believe the main purpose of the restraint was to protect for alimited time the business of the buyer.Indeed, the evils of monopoly are farfetched here. There can be no danger of price controls or deteriorationof the service because of the close supervision of the Public Service Commission. 39 This Court had statedlong ago,40that "when one devotes his property to a use in which the public has an interest, he virtuallygrants to the public an interest in that use and submits it to such public use under reasonable rules andregulations to be fixed by the Public Utility Commission."Regarding that aspect of the clause that it is merely ancillary or incidental to a lawful agreement, theunderlying reason sustaining its validity is well explained in 36 Am. Jur. 537-539, to wit:... Numerous authorities hold that a covenant which is incidental to the sale and transfer of a tradeor business, and which purports to bind the seller not to engage in the same business incompetition with the purchaser, is lawful and enforceable. While such covenants are designed toprevent competition on the part of the seller, it is ordinarily neither their purpose nor effect to stiflecompetition generally in the locality, nor to prevent it at all in a way or to an extent injurious to thepublic. The business in the hands of the purchaser is carried on just as it was in the hands of theseller; the former merely takes the place of the latter; the commodities of the trade are as open tothe public as they were before; the same competition exists as existed before; there is the sameemployment furnished to others after as before; the profits of the business go as they did before toswell the sum of public wealth; the public has the same opportunities of purchasing, if it is amercantile business; and production is not lessened if it is a manufacturing plant.The reliance by the lower court on tile case of Red Line Transportation Co. v. Bachrach41 and finding thatthe stipulation is illegal and void seems misplaced. In the said Red Line case, the agreement thereinsought to be enforced was virtually a division of territory between two operators, each company imposingupon itself an obligation not to operate in any territory covered by the routes of the other. Restraints of thistype, among common carriers have always been covered by the general rule invalidating agreements inrestraint of trade. 42Neither are the other cases relied upon by the plaintiff-appellee applicable to the instant case.In Pampanga Bus Co., Inc. v. Enriquez,43the undertaking of the applicant therein not to apply for the liftingof restrictions imposed on his certificates of public convenience was not an ancillary or incidentalagreement. The restraint was the principal objective. On the other hand, in Red Line Transportation Co.,Inc. v. Gonzaga,44 the restraint there in question not to ask for extension of the line, or trips, or increase of
equipment was not an agreement between the parties but a condition imposed in the certificate ofpublic convenience itself.Upon the foregoing considerations, Our conclusion is that the stipulation prohibiting Villarama for a periodof 10 years to "apply" for TPU service along the lines covered by the certificates of public convenience soldby him to Pantranco is valid and reasonable. Having arrived at this conclusion, and considering that thepreponderance of the evidence have shown that Villa Rey Transit, Inc. is itself the alter ego of Villarama,We hold, as prayed for in Pantranco's third party complaint, that the said Corporation should, until theexpiration of the 1-year period abovementioned, be enjoined from operating the line subject of theprohibition.To avoid any misunderstanding, it is here to be emphasized that the 10-year prohibition upon Villarama isnot against his application for, or purchase of, certificates of public convenience, but merely the operationof TPU along the lines covered by the certificates sold by him to Pantranco. Consequently, the salebetween Fernando and the Corporation is valid, such that the rightful ownership of the disputed certificatesstill belongs to the plaintiff being the prior purchaser in good faith and for value thereof. In view of theancient rule of caveat emptor prevailing in this jurisdiction, what was acquired by Ferrer in the sheriff's salewas only the right which Fernando, judgment debtor, had in the certificates of public convenience on theday of the sale.45Accordingly, by the "Notice of Levy Upon Personalty" the Commissioner of Public Service was notified that"by virtue of an Order of Execution issued by the Court of First Instance of Pangasinan, the rights, interests,or participation which the defendant, VALENTIN A. FERNANDO in the above entitled case may have inthe following realty/personalty is attached or levied upon, to wit: The rights, interests and participation onthe Certificates of Public Convenience issued to Valentin A. Fernando, in Cases Nos. 59494, etc. ... Lines Manila to Lingayen, Dagupan, etc. vice versa." Such notice of levy only shows that Ferrer, the vendee atauction of said certificates, merely stepped into the shoes of the judgment debtor. Of the same principle isthe provision of Article 1544 of the Civil Code, that "If the same thing should have been sold to differentvendees, the ownership shall be transferred to the person who may have first taken possession thereof ingood faith, if it should be movable property."There is no merit in Pantranco and Ferrer's theory that the sale of the certificates of public convenience inquestion, between the Corporation and Fernando, was not consummated, it being only a conditional salesubject to the suspensive condition of its approval by the Public Service Commission. While section 20(g)of the Public Service Act provides that "subject to established limitation and exceptions and savingprovisions to the contrary, it shall be unlawful for any public service or for the owner, lessee or operatorthereof, without the approval and authorization of the Commission previously had ... to sell, alienate,mortgage, encumber or lease its property, franchise, certificates, privileges, or rights or any partthereof, ...," the same section also provides:... Provided, however, That nothing herein contained shall be construed to prevent the transactionfrom being negotiated or completed before its approval or to prevent the sale, alienation, or leaseby any public service of any of its property in the ordinary course of its business.It is clear, therefore, that the requisite approval of the PSC is not a condition precedent for the validity andconsummation of the sale.Anent the question of damages allegedly suffered by the parties, each of the appellants has its or his ownversion to allege.Villa Rey Transit, Inc. claims that by virtue of the "tortious acts" of defendants (Pantranco and Ferrer) inacquiring the certificates of public convenience in question, despite constructive and actual knowledge ontheir part of a prior sale executed by Fernando in favor of the said corporation, which necessitated the
latter to file the action to annul the sheriff's sale to Ferrer and the subsequent transfer to Pantranco, it isentitled to collect actual and compensatory damages, and attorney's fees in the amount of P25,000.00.The evidence on record, however, does not clearly show that said defendants acted in bad faith in theiracquisition of the certificates in question. They believed that because the bill of sale has yet to beapproved by the Public Service Commission, the transaction was not a consummated sale, and, therefore,the title to or ownership of the certificates was still with the seller. The award by the lower court ofattorney's fees of P5,000.00 in favor of Villa Rey Transit, Inc. is, therefore, without basis and should be setaside.Eusebio Ferrer's charge that by reason of the filing of the action to annul the sheriff's sale, he had sufferedand should be awarded moral, exemplary damages and attorney's fees, cannot be entertained, in view ofthe conclusion herein reached that the sale by Fernando to the Corporation was valid.Pantranco, on the other hand, justifies its claim for damages with the allegation that when it purchasedViIlarama's business for P350,000.00, it intended to build up the traffic along the lines covered by thecertificates but it was rot afforded an opportunity to do so since barely three months had elapsed when thecontract was violated by Villarama operating along the same lines in the name of Villa Rey Transit, Inc. It isfurther claimed by Pantranco that the underhanded manner in which Villarama violated the contract ispertinent in establishing punitive or moral damages. Its contention as to the proper measure of damages isthat it should be the purchase price of P350,000.00 that it paid to Villarama. While We are fully in accordwith Pantranco's claim of entitlement to damages it suffered as a result of Villarama's breach of hiscontract with it, the record does not sufficiently supply the necessary evidentiary materials upon which tobase the award and there is need for further proceedings in the lower court to ascertain the properamount.PREMISES CONSIDERED, the judgment appealed from is hereby modified as follows:1. The sale of the two certificates of public convenience in question by Valentin Fernando to Villa ReyTransit, Inc. is declared preferred over that made by the Sheriff at public auction of the aforesaid certificateof public convenience in favor of Eusebio Ferrer;2. Reversed, insofar as it dismisses the third-party complaint filed by Pangasinan Transportation Co.against Jose M. Villarama, holding that Villa Rey Transit, Inc. is an entity distinct and separate from thepersonality of Jose M. Villarama, and insofar as it awards the sum of P5,000.00 as attorney's fees in favorof Villa Rey Transit, Inc.;3. The case is remanded to the trial court for the reception of evidence in consonance with the abovefindings as regards the amount of damages suffered by Pantranco; and4. On equitable considerations, without costs. So ordered.Concepcion, C. J., Reyes, J.B.L., Dizon, Makalintal, Castro and Fernando, JJ., concur.Sanchez and Capistrano, JJ., took no part.Zaldivar, J., is on leave.
Maria B.Castro
250shares
P250,000.00
Amado A.Yatco
100
" 100,000.00
Santiago Tan
Jose T. Lopez
90
"
90,000.00
BenitaLamagna
C.S. Gonzales
80
80,000.00
MariaCristobal
70
70,000.00
SegundoEsguerra, Sr.
75
75,000.00
RamonSangalang
MaximoCristobal
55
55,000.00
AntonioCristobal
45,000.00
P1,025,000.00
Maria B Castro was elected President and Maximo Cristobal, Secretary-Treasurer (Exhibit A).The Wise Building was purchased on September 4, 1946, the purchase being made in the name of DoloresTrinidad, wife of Amado A. Yatco (Exhibit V), and the Aguinaldo Building, on January 17, 1947, in the nameof Segundo Esguerra, Sr. (Exhibit M). Both building were purchased for P1,800,000, but as the corporationhad only P1,025,000, the balance of the purchase price was obtained as loans from the Insular LifeAssurance Co., Ltd. and the Philippine Guaranty Co., Inc. (Exhibit C).Of the incorporators of the Marvel Building Corporation, Maximo Cristobal and Antonio Cristobal are halfbrothers of Maria B. Castro, Maria Cristobal is a half-sister, and Segundo Esguerra, Sr. a brother-in-law,husband of Maria Cristobal, Maria B. Castro's half-sister. Maximo B. Cristobal did not file any income taxreturns before the year 1946, except for three years 1939 and 1940, but in these years he was exemptedfrom the tax. He has not filed any war profits tax return (Exhibit 54). Antonio Cristobal, Segundo Esguerra,Sr. and Jose T. Lopez did not file any income tax returns for the years prior to 1946, and neither did theyfile any war profits tax returns (Exhibit 52). Maria Cristobal filed income tax returns for the year 1929 to1942, but they were exempt from the tax (Exhibit 53). Benita A. Lamagna did not file any income taxreturns prior to 1945, except for 1942 which was exempt. She did not file any was profits tax (Exhibit 55).Ramon M. Sangalang did not file income tax returns up to 1945 except for the years 1936, 1937, 1938,1939 and 1940. He has not filed any war profits tax return (Exhibit 57). Amada A. Yatco did not file incometax returns prior to 1945, except for the years 1937, 1938, 1939, 1941 and 1942, but these were exempt.He did not file any war profits tax return (Exhibit 58).
Antonio Cristobal's income in 1946 is P15,630, and in 1947, P4,550 (Exhibits 59-60); Maximo B. Cristobal'sincome in 1946 is P19,759.10, in 1947, P9,773.47 (Exhibits 61-62); Segundo Esquerra's income in 1946 isP5,500, in 1947, P7,754.32 (Exhibits 63-64); Jose T. Lopez's income in 1946 is P20,785, in 1947,P14,302.77 (Exhibits 69-70); Benita A. Lamagna's income in 1945 is P1,559, in 1946, P6,463.36, in 1947,P6,189.79 and her husband's income in 1947 is P10,825.53 (Exhibits 65-68); Ramon M. Sangalang'sincome in 1945 is P5,500, in 1946, P18,300.00 (Exhibits 71-72); Santiago Tan's income in 1945 is P456, in1947 is P9,167.95, and in 1947, P7,620.11 (Exhibits 73-75); and Amado Yatco's income in 1945 is P12,600,in 1946, P23,960, and in 1947, P11,160 (Exhibits 76-78).In October, 1945 Maria B. Castro, Nicasio Yatco, Maxima Cristobal de Esquerra, Maria Cristobal Lopez andMaximo Cristobal organized the Maria B. Castro, Inc. with capital stock of P100,000, of which Maria B.Castro subscribed for P99,600 and all others for P100 each. This was increased in 1950 to P500,000 andMaria B. Castro subscribed P76,000 and the others P1,000 each (Exhibit 126).It does not appear that the stockholders or the board of directors of the Marvel Building Corporation haveever held a business meeting, for no books thereof or minutes meeting were ever mentioned by theofficers thereof or presented by them at the trial. The by-laws of the corporation, if any had ever beenapproved, has not been presented. Neither does it appear that any report of the affairs of the corporationhas been made, either of its transactions or accounts.From the book of accounts of the corporation, advances to the Marvel Building Corporation of P125,000were made by Maria B. Castro in 1947, P102,916.05 in 1948 and P102,916.05 in 1948, and P160,910.96 in1949 (Exhibit 118).The main issue involved in these proceedings is: Is Maria B. Castro the owner of all the shares of stocks ofMarvel Building Corporation and the other stockholders mere dummies of hers?The most important evidence presented by the Collector of Internal Revenue to prove his claim that MariaB. Castro is the sole and exclusive owner of the shares of stock of the Marvel Building Corporation issupposed endorsement in blank of the shares of stock issued in the name of the other incorporators, andthe possession thereof by Maria B. Castro. The existence of said endorsed certificates was testified to bywitnesses Felipe Aquino, internal revenue examiner, Antonio Mariano, examiner, and Crispin Llamado,Under Secretary of Finance, who declared as follows: Towards the end of the year 1948 and about thebeginning of the year 1949, while Aquino and Mariano were examining the books and papers werefurnished by its secretary, Maximo Cristobal, they came across an envelope containing eleven stockcertificates, bound together by an Acco fastener, which (certificates) corresponded in number and inamount on their face to the subscriptions of the stockholders that all the certificates, except that in thename of Maria B. Castro, were endorsed in the bank by the subscribers; that as the two revenue agentscould not agree what to do with the certificates, Aquino brought them to Under-Secretary of FinanceLlamado, who thereupon suggested that photostatic copies thereof be taken; that this was done, and thephotostatic copies taken are (Exhibits 4, 5, 6, 7, 8, 9, 10, 11, 12 and 13; and in that July, 1950, copy-catcopies of the above photostats were taken, and said copy-cat copies are Exhibits 40-49.Julio Llamado, bookkeeper of the Marvel Building Corporation from 1947 to May, 1948, also testified thathe was the one who had prepared the original certificates, putting therein the number of shares in words inhandprint; that the originals were given to him by Maria B. Castro for comparison with the articles ofincorporation; that they were not yet signed by the President and by the Secretary-Treasurer when he hadthe certificates; and that after the checking he returned all of them to Mrs. Castro. He recognized thephotostats, Exhibit 4 to 13 as photostats of the said originals. He also declared that he also prepared a setof stock certificates, similar to the certificates which were copied in the photostats, the number of shares,and the date issue, and that the certificates he had prepared are Exhibits H, H-1 to H-7 and J (Exhibits 3038). This set of certificates was made by him first and the set of which photostats were taken, a few dayslater.The plaintiffs offered a half-hearted denial of the existence of the endorsed blank certificates, MaximoCristobal, secretary of the corporation, saying that no investigation was ever made by Aquino and Marianoin which said certificates were discovered by the latter. They, however, vigorously attack the credibility ofthe witnesses for the defendant, imputing to the Llamados, enmity against Maria B. Castro, and to Aquinoand Mariano, a very doubtful conduct in not divulging the existence of the certificates either Lobrin, ChiefIncome Tax Examiner, or to the Collector of Internal Revenue, both their immediate chiefs. Reliance is also
placed on a certificate, Exhibit W, wherein Aquino and others declare that the certificates (Exhibits 30 to38, or H, H-1 to H-7 and J) were regular and were not endorsed when the same were examined. Inconnection with this certificate, Exhibit W, we note that it states that the certificates examined wereExhibits 30 to 38, the existence or character of which are not disputed. But the statement contains nothingto the effect that the above certificates were the only one existence, according to their knowledge. Againthe certificate was issued for an examination on September 1949, not by Aquino and Mariano at the end of1948 or the beginning of 1949. The certificate, therefore, neither denies the existence of the endorsedcertificates, nor that Aquino and Mariano had made an examination of the papers of the corporation at theend of the year 1948. It ca not, therefore, discredit the testimonies of the defendant's witnesses.As to the supposed enmity of the Llamados towards the plaintiff Maria B. Castro, we note that, supposingthat there really was such enmity, it does not appear that it was of such magnitude or force as could haveinduced the Llamados and Maria B. Castro were close friends way back in 1947 and up to 1949; but that atthe time of the trial the friendship had been marred by misunderstandings. We believe that in 1948 and1949 the Llamados were trusted friends of Maria B. Castro, and this explains why they had knowledge ofher secret transactions. The younger Llamado even made advances for the hand of Maria B. Castro'sdaughter, and this at the time when as a bookkeeper he was entrusted with checking up the certificates ofstock. When the older Llamado kept secret the existence of the endorsed certificates, the friendshipbetween the two families was yet intact; hence, the existence of the endorsed certificates must have beenkept to himself by the older Llamado. All the above circumstances reinforce our belief that the Llamadoshad personal knowledge of the facts they testify to, and the existence of this knowledge in turn rendersimprobable plaintiffs' claim that their testimonies were biased.Attempt was also made by the plaintiffs to show by expert evidence that the endorsement could havebeen superimposed, i.e., that the signatures made on other papers and these were pasted and thereafterthe documents photographed. Judicial experience is to the effect that the expert witnesses can always beobtained for both sides of an issue, most likely because expert witnesses are no longer impermeable to theinfluence of fees (II Wigmore, Sec. 563(2), p. 646). And if parties are capable of paying fees, expert opinionshould be received with caution. In the case at bar, the opinion on the supposed superimposition wasmerely a possibility, and we note various circumstances which proved that the signatures were notsuperimposed and corroborate defendant's claim that they were genuine. In the first place,, the printedendorsement contains a very heavy line at the bottom for the signature of the endorsee. This line in almostall the endorsements is as clear as the printed letters above it, and at the points where the letters of thesignature extend down and transversed it (the line), there is no indication that the line is covered by asuperimposed paper. Again in these places both the signatures and the lines are clear and distinct wherethey cross one another. Had there been superimpositions the above features could not have been possible.In the second place, Maria B. Castro admitted having signed 25 stock certificates, but only eleven wereissued (t. s. n., p. 662). No explanation is given by her why she had to sign as many as 25 forms whenthere were only eleven subscribers and eleven forms to be filed. This circumstances corroborate the youngLlamado's declaration that two sets of certificates had been prepared. The nineteen issue must be ExhibitsH, H-1 to H-7 and J, or Nos. 30 to 38, and the stock certificates endorsed whose photostatic copies areExhibits 4 to 13. It is to be remembered also, that it is a common practice among unscrupulous merchantsto carry two sets of books, one set for themselves and another to be shown to tax collectors. This practicecould not have been unknown to Maria B. Castro, who apparently had been able to evade the payment ofher war profits taxes. These circumstances, coupled with the testimony of Julio Llamado that two sets ofcertificates were given to him for checking, show to an impartial mind the existence of the set ofcertificates endorsed in blank, thus confirming the testimonies of the defendant's witnesses, Aquino,Mariano and Crispin Llamado, and thus discrediting the obviously partial testimony of the expert presentedby plaintiffs. The genuineness of the signatures on the endorsements is not disputed. How could thedefendant have secured these genuine signatures? Plaintiffs offer no explanation for this, although they donot question them. It follows that the genuine signatures must have been made on the stock certificatesthemselves.Next in importance among the evidence submitted by the defendant collector to prove his contention thatMaria B. Castro is the sole owner of the shares of stock of the Marvel Building Corporation, is the fact thatthe other stockholders did not have incomes in such amounts, during the time of the organization of thecorporation in 1947, or immediately thereto, as to enable them to pay in full for their supposedsubscriptions. This fact is proved by their income tax returns, or the absence thereof. Let us take Amado A.Yatco as an example. Before 1945 his returns were exempt from the tax, in 1945 he had P12,600 and in1946, P23,000. He has four children. How could he have paid P100,000 in 1945 and 1946? Santiago Tanwho also contributed P100,000 had no appreciable income before 1946, and this year an income of only
P9,167.95. Jose T. Lopez also did not file any income tax returns before 1940 and 1946 he had an incomeof only P20,785, whereas he is supposed to have subscribed P90,000 worth of stock early in 1947. BenitaLamagna had no returns either up to 1945, except in 1942, which was exempt and in 1945 she had anincome of P1,550 and in 1946, P6,463.36. In the same situation are all the others, and besides, brothersand sisters and brother-in-law of Maria B. Castro. On the other hand, Maria B. Castro had been found tohave made enormous gains or profits in her business such that the taxes thereon were assessed at aroundP3,000,000. There was, therefore, a prima facie case out by the defendant collector that Maria B. Castrohad furnished (& all the money that the Marvel Building Corporation had.In order the meet the above evidence only three of the plaintiffs testified, namely, Maximo Cristobal, thecorporation's secretary, who made the general assertion on the witness stand that the other stockholderspaid for their shares in full, Maria B. Castro, who stated that payments for the subscription were made toher, and C.S. Gonzales, who admitted that Maria B. Castro, paid for his subscription. After a careful study ofthe above testimonies, however, we find them subject to various objections. Maximo Cristobal declaredthat he issued provincial receipts for the subscriptions supposedly paid to him in 1946; but none of thesupposed receipts were presented. If the subscriptions were really received by him, big as the amountswere, he would have been able to tell specifically, by dates and in fix amounts, when and how thepayments were made. The general assertion of alleged payments, without the concrete days and amountsof payments, are, according to our experience, positive identifications of untruthfulness, for when awitness testified to a fact that actually occurs, the act is concretely stated and no generalization is made.With respect to Maria B. Castro's testimony, we find it to be as untruthful as that of Cristobal. She declaredthat payments of the subscriptions took place between July and December, 1946, and that first paymentswere first deposited by her in the National City Bank of New York. A study of her account in said bank(Exhibit 82), however, fails to show the alleged deposit of the subscriptions during the year 1946 (SeeExhibits 83-112). This fact completely belies her assertion. As to the testimony of C.S. Gonzales that MariaB. Castro advanced his subscription, there is nothing in the evidence to corroborate it, and thecircumstances show otherwise. If he had really been a stockholder and Maria B. Castro advanced hissubscription, the agreement between him and Castro should have been put in writing, the amountadvanced being quite considerable (P80,000), and it appearing further that Gonzales is no close relative orconfidant of Castro.Lastly, it is significant that the plaintiffs, the supposed subscribers, who should have come to court toassert that they actually paid for their subscriptions, and are not mere dummies, did not do so. They couldnot have afforded such a costly indifference, valued at from P70,000 to P100,000 each, if they were notactual dummies. This failure on their part to take the witness stand to deny or refute the charge that theywere mere dummies is to us of utmost significance. What could have been easier to disprove the chargethat they were dummies, than for them to come to court and show their receipts and testify on thepayments they have paid on their subscriptions? This they, however refused to do so. They had it in theirpower to rebut the charges, but they chose to keep silent. The non-production of evidence that wouldnaturally have been produced by an honest and therefore fearless claimant permits the inference that itstenor is unfavorable to the party's cause (II Wigmore, Sec. 285, p.162). A party's silence to adversetestimony is equivalent to an admission of its truth (Ibid, Sec. 289, p. 175).Our consideration of the evidence submitted on both sides leads us to a conclusion exactly opposite thatarrived at by the trial court. In general the evidence offered by the plaintiffs is testimonial and directevidence, easy of fabrication; that offered by defendant, documentary and circumstantial, not only difficultof fabrication but in most cases found in the possession of plaintiffs. There is very little room for choice asbetween the two. The circumstantial evidence is not only convincing; it is conclusive. The existence ofendorsed certificates, discovered by the internal revenue agents between 1948 and 1949 in the possessionof the Secretary-Treasurer, the fact that twenty-five certificates were signed by the president of thecorporation, for no justifiable reason, the fact that two sets of certificates were issued, the undisputed factthat Maria B. Castro had made enormous profits and, therefore, had a motive to hide them to evade thepayment of taxes, the fact that the other subscribers had no incomes of sufficient magnitude to justifytheir big subscriptions, the fact that the subscriptions were not receipted for and deposited by thetreasurer in the name of the corporation but were kept by Maria B. Castro herself, the fact that thestockholders or the directors never appeared to have ever met to discuss the business of the corporation,the fact that Maria B. Castro advanced big sums of money to the corporation without any previousarrangement or accounting, and the fact that the books of accounts were kept as if they belonged to MariaB. Castro alone these facts are of patent and potent significance. What are their necessary implications?
Maria B. Castro would not have asked them to endorse their stock certificates, or be keeping these in herpossession, if they were really the owners. They never would have consented that Maria B. Castro keep thefunds without receipts or accounting, nor that she manages the business without their knowledge orconcurrence, were they owners of the stocks in their own rights. Each and every one of the facts all setforth above, in the same manner, is inconsistent with the claim that the stockholders, other than Maria B.Castro, own their shares in their own right. On the other hand, each and every one of them, and all ofthem, can point to no other conclusion than that Maria B. Castro was the sole and exclusive owner of theshares and that they were only her dummies.In our opinion, the facts and circumstances duly set forth above, all of which have been proved to oursatisfaction, prove conclusively and beyond reasonable doubt (section 89, Rule 123 of the Rules of Courtand section 42 of the Provisional law for the application of the Penal Code) that Maria B. Castro is the soleand exclusive owner of all the shares of stock of the Marvel Building Corporation and that the otherpartners are her dummies.Wherefore, the judgment appealed from should be, as it hereby is, reversed and the action filed byplaintiffs-appellees, dismissed, with costs against plaintiffs-appellees. So ordered.Paras, C.J., Pablo, Bengzon, Padilla, Montemayor, Jugo and Bautista Angelo, JJ., concur.
CONCEPT BUILDERS, INC., petitioner, vs. THE NATIONAL LABOR RELATIONS COMMISSION, (FirstDivision); and Norberto Marabe, Rodolfo Raquel, Cristobal Riego, Manuel Gillego,Palcronio Giducos, Pedro Aboigar, Norberto Comendador, Rogello Salut, Emilio Garcia, Jr.,Mariano Rio, Paulina Basea, Aifredo Albera, Paquito Salut, Domingo Guarino, RomeoGalve, Dominador Sabina, Felipe Radiana, Gavino Sualibio, Moreno Escares, FerdinandTorres, Felipe Basilan, and Ruben Robalos, respondents.DECISIONHERMOSISIMA, JR., J.:The corporate mask may be lifted and the corporate veil may be pierced when a corporation is just butthe alter ego of a person or of another corporation. Where badges of fraud exist; where public convenienceis defeated; where a wrong is sought to be justified thereby, the corporate fiction or the notion of legalentity should come to naught. The law in these instances will regard the corporation as a mere associationof persons and, in case of two corporations, merge them into one.Thus, where a sister corporation is used as a shield to evade a corporations subsidiary liability fordamages, the corporation may not be heard to say that it has a personality separate and distinct from theother corporation. The piercing of the corporate veil comes into play.This special civil action ostensibly raises the question of whether the National Labor RelationsCommission committed grave abuse of discretion when it issued a break-open order to the sheriff to beenforced against personal property found in the premises of petitioners sister company.Petitioner Concept Builders, Inc., a domestic corporation, with principal office at 355 Maysan Road,Valenzuela, Metro Manila, is engaged in the construction business. Private respondents were employed bysaid company as laborers, carpenters and riggers.On November, 1981, private respondents were served individual written notices of termination ofemployment by petitioner, effective on November 30, 1981. It was stated in the individual notices thattheir contracts of employment had expired and the project in which they were hired had been completed.Public respondent found it to be, the fact, however, that at the time of the termination of privaterespondents employment, the project in which they were hired had not yet been finished andcompleted. Petitioner had to engage the services of sub-contractors whose workers performed thefunctions of private respondents.Aggrieved, private respondents filed a complaint for illegal dismissal, unfair labor practice and nonpayment of their legal holiday pay, overtime pay and thirteenth-month pay against petitioner.On December 19, 1984, the Labor Arbiter rendered judgment 1 ordering petitioner to reinstate privaterespondents and to pay them back wages equivalent to one year or three hundred working days.On November 27, 1985, the National Labor Relations Commission (NLRC) dismissed the motion forreconsideration filed by petitioner on the ground that the said decision had already become final andexecutory.2On October 16, 1986, the NLRC Research and Information Department made the finding that privaterespondents backwages amounted to P199,800.00.3
On October 29, 1986, the Labor Arbiter issued a writ of execution directing the sheriff to execute theDecision, dated December 19, 1984. The writ was partially satisfied through garnishment of sums frompetitioners debtor, the Metropolitan Waterworks and Sewerage Authority, in the amount ofP81,385.34. Said amount was turned over to the cashier of the NLRC.On February 1, 1989, an Alias Writ of Execution was issued by the Labor Arbiter directing the sheriff tocollect from herein petitioner the sum of P117,414.76, representing the balance of the judgment award,and to reinstate private respondents to their former positions.On July 13, 1989, the sheriff issued a report stating that he tried to serve the alias writ of execution onpetitioner through the security guard on duty but the service was refused on the ground that petitioner nolonger occupied the premises.On September 26, 1986, upon motion of private respondents, the Labor Arbiter issued a second aliaswrit of execution.The said writ had not been enforced by the special sheriff because, as stated in his progress report,dated November 2, 1989:1. All the employees inside petitioners premises at 355 Maysan Road, Valenzuela, Metro Manila, claimedthat they were employees of Hydro Pipes Philippines, Inc. (HPPI) and not by respondent;2. Levy was made upon personal properties he found in the premises;3. Security guards with high-powered guns prevented him from removing the properties he had leviedupon.4The said special sheriff recommended that a break-open order be issued to enable him to enterpetitioners premises so that he could proceed with the public auction sale of the aforesaid personalproperties on November 7, 1989.On November 6, 1989, a certain Dennis Cuyegkeng filed a third-party claim with the Labor Arbiteralleging that the properties sought to be levied upon by the sheriff were owned by Hydro (Phils.), Inc.(HPPI) of which he is the Vice-President.On November 23, 1989, private respondents filed a Motion for Issuance of a Break-Open Order,alleging that HPPI and petitioner corporation were owned by the same incorporator! stockholders. Theyalso alleged that petitioner temporarily suspended its business operations in order to evade its legalobligations to them and that private respondents were willing to post an indemnity bond to answer for anydamages which petitioner and HPPI may suffer because of the issuance of the break-open order.In support of their claim against HPPI, private respondents presented duly certified copies of theGeneral Informations Sheet, dated May 15, 1987, submitted by petitioner to the Securities and ExchangeCommission (SEC) and the General Information Sheet, dated May 15, 1987, submitted by HPPI to theSecurities and Exchange Commission.The General Information Sheet submitted by the petitioner1 revealed the following:1. Breakdown of Subscribed CapitalName of Stockholder Amount SubscribedHPPI P6,999,500.00
separate from petitioners construction business. Hence, it is of no consequence that petitioner and HPPIshared the same premises, the same President and the same set of officers and subscribers. 7We find petitioners contention to be unmeritorious.It is a fundamental principle of corporation law that a corporation is an entity separate and distinctfrom its stockholders and from other corporations to which it may be connected. 8 But, this separate anddistinct personality of a corporation is merely a fiction created by law for convenience and to promotejustice.9 So, when the notion of separate juridical personality is used to defeat public convenience, justifywrong, protect fraud or defend crime, or is used as a device to defeat the labor laws, 10 this separatepersonality of the corporation may be disregarded or the veil of corporate fiction pierced. 11 This is truelikewise when the corporation is merely an adjunct, a business conduit or an alter ego of anothercorporation.12The conditions under which the juridical entity may be disregarded vary according to the peculiar factsand circumstances of each case. No hard and fast rule can be accurately laid down, but certainly, there aresome probative factors of identity that will justify the application of the doctrine of piercing the corporateveil, to wit:1. Stock ownership by one or common ownership of both corporations.2. Identity of directors and officers.3. The manner of keeping corporate books and records.4. Methods of conducting the business.13The SEC en banc explained the instrumentality rule which the courts have applied in disregarding theseparate juridical personality of corporations as follows:Where one corporation is so organized and controlled and its affairs are conducted so that it is, in fact, amere instrumentality or adjunct of the other, the fiction of the corporate entity of the instrumentality maybe disregarded. The control necessary to invoke the rule is not majority or even complete stock control butsuch domination of finances, policies and practices that the controlled corporation has, so to speak, noseparate mind, will or existence of its own, and is but a conduit for its principal. It must be kept in mindthat the control must be shown to have been exercised at the time the acts complained of tookplace. Moreover, the control and breach of duty must proximately cause the injury or unjust loss for whichthe complaint is made.The test in determining the applicability of the doctrine of piercing the veil of corporate fiction is asfollows:1. Control, not mere majority or complete stock control, but complete domination, not only of finances butof policy and business practice in respect to the transaction attacked so that the corporate entity as to thistransaction3. The aforesaid control and breach of duty must proximately cause the injury or unjust loss complainedof.
The absence of any one of these elements prevents piercing the corporate veil. in applying theinstrumentality or alter ego doctrine, the courts are concerned with reality and not form, with how thecorporation operated and the individual defendants relationship to that operation. 14Thus, the question of whether a corporation is a mere alter ego, a mere sheet or paper corporation, asham or a subterfuge is purely one of fact.15In this case, the NLRC noted that, while petitioner claimed that it ceased its business operationson April 29, 1986, it filed an Information Sheet with the Securities and Exchange Commission on May 15,1987, stating that its office address is at 355 Maysan Road, Valenzuela, Metro Manila. On the other hand,HPPI, the third-party claimant, submitted on the same day, a similar information sheet stating that itsoffice address is at 355 Maysan Road, Valenzuela, Metro Manila.Furthermore, the NLRC stated that:Both information sheets were filed by the same Virgilio O. Casino as the corporate secretary of bothcorporations. It would also not be amiss to note that both corporations had the same president, the sameboard of directors, the same corporate officers, and substantially the same subscribers.From the foregoing, it appears that, among other things, the respondent (herein petitioner) and the thirdparty claimant shared the same address and/or premises. Under this circumstances, (sic) it cannot be saidthat the property levied upon by the sheriff were not of respondents. 16Clearly, petitioner ceased its business operations in order to evade the payment to privaterespondents of backwages and to bar their reinstatement to their former positions. HPPI is obviously abusiness conduit of petitioner corporation and its emergence was skillfully orchestrated to avoid thefinancial liability that already attached to petitioner corporation.The facts in this case are analogous to Claparols v. Court of Industrial Relations17 where we had theoccasion to rule:Respondent courts petitioner. it is veryclear that the latter corporation was a continuation and successor of the first entity x x x. Bothpredecessors and successor were owned and controlled by petitioner Eduardo Claparols and there was nobreak in the succession and continuity of the same business. This avoiding-the-liability scheme is verypatent, considering that 90% of the subscribed shares of stock of the Claparols Steel Corporation (thesecond corporation) was owned by respondent x x x Claparols himself, and all the assets of the dissolvedClaparols Steel and Nail Plant were turned over to the emerging Claparols Steel Corporation.It is very obvious that the second corporation seeks the protective shield of a corporate fiction whoseveil in the present case could, and should, be pierced as it was deliberately and maliciously designed toevade its financial obligation to its employees.In view of the failure of the sheriff, in the case at bar, to effect a levy upon the property subject of theexecution, private respondents had no other recourse but to apply for a break-open order after the thirdparty claim of HPPI was dismissed for lack of merit by the NLRC. This is in consonance with Section 3, RuleVII of the NLRC Manual of Execution of Judgment which provides that:Should the losing party, his agent or representative, refuse or prohibit the Sheriff or his representativeentry to the place where the property subject of execution is located or kept, the judgment creditor mayapply to the Commission or Labor Arbiter concerned for a break-open order.
Furthermore, our perusal of the records shows that the twin requirements of due notice and hearingwere complied with. Petitioner and the third-party claimant were given the opportunity to submit evidencein support of their claim.Hence, the NLRC did not commit any grave abuse of discretion when it affirmed the break-open orderissued by the Labor Arbiter.Finally, we do not find any reason to disturb the rule that factual findings of quasi-judicial agenciessupported by substantial evidence are binding on this Court and are entitled to great respect, in theabsence of showing of grave abuse of a discretion.18WHEREFORE, the petition is DISMISSED and the assailed resolutions of the NLRC, dated April 23,1992 and December 3, 1992, are AFFIRMED.SO ORDERED
MAKASIAR, J.:A petition for certiorari to set aside the order of respondent Court of Industrial Relations dated May 30,1969 directing petitioners to pay back wages and bonuses to private respondents as well as its resolutionof July 5, 1969 denying the motion for reconsideration of said order in Case No. 32-ULP-Iloilo entitled "AlliedWorkers' Association, et. al., versus Eduardo Claparols, et. al.."It appears that on August 6, 1957, a complaint for unfair labor practice was filed by herein privaterespondent Allied Workers' Association, respondent Demetrio Garlitos and ten (10) respondent workersagainst herein petitioners on account of the dismissal of respondent workers from petitioner ClaparolsSteel and Nail Plant.On September 16, 1963, respondent Court rendered its decision finding "Mr. Claparols guilty of unionbusting and" of having "dismissed said complainants because of their union activities," and orderingrespondents "(1) To cease and desist from committing unfair labor practices against their employees andlaborers; (2) To reinstate said complainants to their former or equivalent jobs, as soon as possible, withbackfor execution of respondent Court's September 16, 1963 decision.On May 14, 1964, respondent Court, in its order of September 16, 1963, granted execution and directedherein petitionersto reinstate the above complainants to their former or equivalent jobs within five (5) daysafter receipt of a copy of this order. In order to implement the award of back wages, theChief of the Examining Division or any of his assistants is hereby directed to proceed to theoffice of the respondents at Matab-ang, Talisay, Negros Occidental, and examine its payrollsand other pertinent records and compute the back wages of the complainants in accordancewith the decision dated September 16, 1963, and, upon termination, to submit his report assoon as possible for further disposition (p. 7, Brief for Respondents, p. 113, rec.).which was reiterated by respondent Court in a subsequent order dated November 10, 1964 (pp. 7-8, Brieffor Respondents, p. 113, rec.).
On December 14, 1964, respondent workers were accompanied by the Chief of Police of Talisay, NegrosOccidental to the compound of herein petitioner company to report for reinstatement per order of thecourt. Respondent workers were, however, refused reinstatement by company accountant Francisco Cusifor he had no order from plant owner Eduardo Claparols nor from his lawyer Atty. Plaridel Katalbas, toreinstate respondent workers.Again, on December 15, 1964, respondent workers were accompanied by a police officer to the companycompound,up to and including December 7, 1962, when the corporation stopped operations, while thethird is only up to June 30, 1957 when the Claparols Steel and Nail Plant ceased to operate(Annex B, Petition for Review on Certiorari, p. 14, Brief for appellees, p. 113, rec.).with the explanation thatengulfing the company, petitioner Claparols could not personally reinstate respondent workers; thatassuming the workers are entitled to back wages, the same should only be limited to three monthspursuant to the court ruling in the case of Sta. Cecilia Sawmills vs. CIR (L-19273-74, February 20, 1964);and that since Claparols Steel Corporation ceased to operate on December 7, 1962, re-employment ofrespondent workers cannot go beyond December 7, 1962.A reply to petitioner's opposition was filed by respondent workers, alleging among others, that ClaparolsSteel and Nail Plant and Claparols Steel and Nail Corporation are one and the same corporation controlledby petitioner Claparols, with the latter corporation succeeding the former.On November 28, 1966, after conducting a series of hearings on the report of the examiner, respondentCourt issued an order, the dispositive portion of which reads:WHEREFORE, the Report of the. Examiner filed on January 15, 1965, is hereby approvedsubject to the foregoing findings and dispositions. Consequently, the Corporation AuditingExaminer is directed to recompute the back wages of complainants Demetrio Garlitos andAlfredo Ongsuco on the basis of P200.00 and P270.00 a month, respectively; to computethose of complainant Ignacio Quioyo as aforesaid; to compute the deductible earnings ofcomplainants Ongsuco, Jorge Semillano and Garlitos, as found in the body of this order; andto compute the bonuses of each and every complainant, except Honorato Quioyo.Thereafter, as soon as possible, the Examiner should submit a report in compliance herewithof the Court's further disposition (p. 24, Brief for Respondents, p. 113, rec.).On December 7, 1966, a motion for reconsideration was filed by petitioner, assailing respondent Court'sruling that (1) the ruling in the case of Sta. Cecilia Sawmills Inc. CIR, et. al, does not apply in the case atbar; and (2) that bonus should be included in the recoverable wages.
On December 14, 1966, a counter-opposition was filed by private respondents alleging that petitioners'motion for reconsideration was pro forma, it not making express reference to the testimony ordocumentary evidence or to the provision of law alleged to be contrary to such findings or conclusions ofrespondent Court.On February 8, 1967, respondent Court of Industrial Relations dismissed petitioners' motion forreconsideration for being pro forma.Whereupon, petitioners filed a petition for certiorari with this COURT in G.R. No. L-27272 to set aside theNovember 28, 1966 order of respondent Court, as well as its February 8, 1967 resolution. Petitionersassigned therein as errors of law the very same assignment of errors it raises in the present case, to wit:ITHE RESPONDENT COURT ERRED AND/OR ACTED WITH GRAVE ABUSE OF DISCRETION,AMOUNTING TO LACK OF JURISDICTION, IN HOLDING IN THE ORDER UNDER REVIEW THATBONUSES SHOULD BE PAID TO THE RESPONDENT WORKERS DESPITE THE FACT THAT THESAME WAS NOT ADJUDICATED IN ITS ORIGINAL DECISION.IITHE RESPONDENT COURT ERRED AND/OR ACTED WITH GRAVE ABUSE OF DISCRETION,AMOUNTING TO LACK OF JURISDICTION, IN NOT APPLYING THE DOCTRINE LAID DOWN BYTHIS. Amotion to the same end was reiterated by private respondents on June 14, 1967.On July 13, 1967, respondent Court directed a recomputation of the back wages of respondent workers inaccordance with its order dated November 28, 1966. The said order in part reads:WHEREFORE, the Chief Auditing Examiner of the Court or any of his assistants, is herebydirected to recompute the back wages of the workers involved in this case in accordancewith the Order of November 28, 1966 within 20 days from receipt of a copy of this Order (p.28, Brief for Respondents, p. 113, rec.).Then on March 21, 1968, the Chief Examiner came out with his report, the disputed portion of which(regarding bonuses) reads:xxx xxx xxx4. The yearly bonuses of the employees and laborers of respondent corporation are given onthe following basis:Basic Additional:a. For every dependent 1% of monthly salary
complainants (respondents herein) ... (p. 35, Brief for Respondents; p. 113, rec.; emphasissupplied).1wph1.tOn June 7, 1969, petitioners filed a motion for reconsideration on practically the same grounds previouslyraised by them.On June 30, 1969, respondents filed an opposition to petitioners' motion for reconsideration, with thefollowing allegations:1. The issues raised, namely, whether bonuses should be included in the award for backwagesfinal issue.2. Petitioners' motion for reconsideration is merely a rehash of previous arguments, effete27272], dismissing said case, wherein said petitioners invoked the applicability of the doctrine in Sta.Cecilia Sawmills, Inc. vs. CIR, et. al. (L-19273-74, Feb. 29, 1964, 10 SCRA 433) and impugned the illegalityof the order of respondent Court dated November 28, 1966 directing the computation and payment of thebonuses, aside from back wages on the ground that these bonuses were not included in the decision ofSeptember 16, 1963, which had long become final.The aforesaid resolutions in G.R. No. L-27272 constitute the law of the instant case, wherein hereinpetitioners raised again practically the same issues invoked in the abovementioned case. The denial of thepetition in G.R. No. L-27272 suffices to warrant the denial of the present petition; and We need not go anyfurther.However, without lending a sympathetic ear to the obvious desire of herein petitioners of this Court to reexamine which would be an exercise in futility the final ruling in G.R. No. L-27272, which as abovestated is the law of the instant case, but solely to remind herein petitioners, We reiterate the governingprinciples.WE uniformly held that "a bonus is not a demandable and enforceable obligation, except when it is a partofJustice Labrador, held:Whether or not bonus forms part of wages depends upon the condition or circumstance forits payment.If it is an additional compensation WHICH THE EMPLOYER PROMISED ANDAGREED to give without any condition imposed for its payment ... then it is part of the wage.(Emphasis supplied).1wph1.tIn Altomonte vs. Philippine American Drug Co. (106 Phil. 137), the Supreme Court held that an employee isnot entitled to bonus where there is no showing that it had been granted by the employer to its employeesperiodically or regularly as to become part of their wages or salaries. The clear implication is that bonus is
recoverable as part of the wage or salary where the employer regularly or periodically gives it toemployees.American jurisprudence equally regards bonuses as part of compensation or recoverable wages.Thus, it was held that "... it follows that in determining the regular rate of pay, a bonus which in factconstitutes PART OF AN EMPLOYEE'S compensation, rather than a true gift or gratuity, has to be taken intoconsideration." (48 Am. Jur. 2d, Labor and Labor Relations, No. 1555, citing the cases of Triple "AAA" Co. vs.Wirtz and Haber vs. Americana Corporation; Emphasis supplied). It was further held that "... the regularrate includes incentive bonuses paid to the employees in addition to the guaranteed base rates regardlessof any contract provision to the contrary and even though such bonuses could not be determined or paiduntil such time after the pay day" (48 Am. Jur. 2d, Labor and Labor Relations, No. 1555, citing the case ofWalling vs. Harnischfeger Corp., 325 US 427, 89 L Ed 1711, 65 S Ct. 1246; Emphasis supplied).1wph1.tPetitioners in the present case do not dispute that as a matter of tradition, the company has been dolingout bonuses to employees. In fact, the company balance sheets for the years 1956 to 1962 containedbonus and pension computations which were never repudiated or questioned by petitioners. As such,bonus for a given year earmarked as a matter of tradition for distribution to employees has formed part oftheir recoverable wages from the company. Moreover, with greater reason, should recovery of bonuses aspart of back wages be observed in the present case since the company, in the light of the very admissionof company accountant Francisco Cusi, distributes bonuses to its employees even if the company hassuffered losses. Specifically, petitioner company has done this in 1962 (t.s.n., p. 149, Sept. 20, 1965).Since bonuses are part of back wages of private respondents, the order of May 30, 1969, directing thepayment of their bonuses, did not amend the decision of September 16, 1963 of respondent Courtdirecting payment of their wages, which has long become final and executory, in the same way that theprevious order of May 14, 1964 granting execution of said decision of September 16, 1963 also directedthe computation of the wages to be paid to private respondents as decreed by the decision of September16, 1963. All the orders of May 30, 1969, November 28, 1966 and May 14, 1964 merely implement thealready final and executory decision of September 16, 1963.Petitioners insist that We adopt the ruling in the Sta. Cecilia Sawmills case wherein the recoverable backwages were limited to only three (3) months; because as in the Sta. Cecilia Sawmills case, the ClaparolsSteel and Nail Plant ceased operations due to enormous business reverses.Respondent Court's petitioners. It is veryclear that the latter corporation was a continuation and successor of the first entity, and its emergencewas skillfully timed to avoid the financial liability that already attached to its predecessor, the ClaparolsSteel and Nail Plant. Both predecessors and successor were owned and controlled by the petitionerEduardo Claparols and there was no break in the succession and continuity of the same business. This"avoiding-the-liability" scheme is very patent, considering that 90% of the subscribed shares of stocks ofthe Claparols Steel Corporation (the second corporation) was owned by respondent (herein petitioner)Claparols himself, and all the assets of the dissolved Claparols Steel and Nail Plant were turned over to theemerging Claparols Steel Corporation.It is very obvious that the second corporation seeks the protective shield of a corporate fiction whose veilin the present case could, and should, be pierced as it was deliberately and maliciously designed to evadeitspersons, or, in the case of two corporations, will merge them into one.In Liddel & Company, Inc. vs. Collector of Internal Revenue (L-9687, June 30, 1961, 2 SCRA 632), this Courtlikewise held that where a corporation is a dummy and serves no business purpose and is intended only asa blind, the corporate fiction may be ignored.In Commissioner of Internal Revenue vs. Norton and Harrison Company (L-17618, Aug. 31, 1964, 11 SCRA714), We ruled that where a corporation is merely an adjunct, business conduit or alter ego of anothercorporation, the fiction of separate and distinct corporate entities should be disregarded.To the same uniform effect are the decisions in the cases of Republic vs. Razon (L-17462, May 29, 1967, 20SCRA 234) and A.D. Santos, Inc. vs. Vasquez (L-23586, March 20, 1968, 22 SCRA 1156).WE agree with respondent Court of Industrial Relations, therefore, that the amount of back wagesrecoverable by respondent workers from petitioners should be the amount accruing up to December 7,1962 when the Claparols Steel Corporation ceased operations.WHEREFORE, PETITION IS HEREBY DENIED WITH TREBLE COSTS AGAINST PETITIONERS TO BE PAID BYTHEIR COUNSEL.Castro (Chairman), Esguerra, Muoz Palma and Martin, JJ., concur.Teehankee, J., is on leave.THIRD DIVISION[G.R. No. 159121. February 3, 2005]PAMPLONA PLANTATION COMPANY, INC. and/or JOSE LUIS BONDOC, petitioners, vs. RODELTINGHIL, MARYGLENN SABIHON, ESTANISLAO BOBON, CARLITO TINGHIL, BONIFACIOTINGHIL, NOLI TINGHIL, EDGAR TINGHIL, ERNESTO ESTOMANTE, SALLY TOROY, BENIGNOTINGHIL JR., ROSE ANN NAPAO, DIOSDADO TINGHIL, ALBERTO TINGHIL, ANALIE TINGHIL,and ANTONIO ESTOMANTE, respondents.DECISIONPANGANIBAN, J.:To protect the rights of labor, two corporations with identical directors, management, office and payrollshould be treated as one entity only. A suit by the employees against one corporation should be deemedas a suit against the other. Also, the rights and claims of workers should not be prejudiced by the acts ofthe employer that tend to confuse them about its corporate identity. The corporate fiction must yield totruth and justice.The CaseBefore us is a Petition for Review[1] under Rule 45 of the Rules of Court, seeking to annul the January31, 2003 Decision[2] and the June 17, 2003 Resolution[3] of the Court of Appeals (CA) in CA-GR SP No.62813. The assailed Decision disposed as follows:WHEREFORE, in view of the foregoing, the petition is GRANTED. The assailed decision of publicrespondent NLRC dated 19 July 2000 [is] REVERSED and SET ASIDE and a new one
entered DIRECTINGprivate respondents to reinstate petitioners, except Rufino Bacubac, Felix Torres andAntonio Canolas, to their former positions without loss of seniority rights plus payment of full backwages.However, if reinstatement is no longer feasible, a one-month salary for every year of service shall be paidthe petitioners as ordered by the Labor Arbiter in his decision dated 31 August 1998 plus payment of fullbackwages computed from date of illegal dismissal to the finality of this decision. [4]The Decision[5] of the National Labor Relations Commission (NLRC), [6] reversed by the CA, disposed asfollows:WHEREFORE, premises considered, the decision appealed from is hereby REVERSED, and another oneentered DISMISSING the complaint.[7]The June 17, 2003 Resolution denied petitioners Motion for Reconsideration.The FactsThe CA summarized the antecedents as follows:Sometime in 1993, [Petitioner] Pamplona Plantations Company, Inc. (company for brevity) was organizedfor the purpose of taking over the operations of the coconut and sugar plantation of Hacienda Pamplonalocated in Pamplona, Negros Oriental. It appears that Hacienda Pamplona was formerly owned by a certainMr. Bower who had in his employ several agricultural workers.When the company took over the operation of Hacienda Pamplona in 1993, it did not absorb all theworkers of Hacienda Pamplona. Some, however, were hired by the company during harvest season ascoconut hookers or sakador, coconut filers, coconut haulers, coconut scoopers or lugiteros, and charcoalmakers.Sometime in 1995, Pamplona Plantation Leisure Corporation was established for the purpose of engagingin the business of operating tourist resorts, hotels, and inns, with complementary facilities, such asrestaurants, bars, boutiques, service shops, entertainment, golf courses, tennis courts, and other land andaquatic sports and leisure facilities.On 15 December 1996, the Pamplona Plantation Labor Independent Union (PAPLIU) conducted anorganizational meeting wherein several [respondents] who are either union members or officersparticipated in said meeting.Upon learning that some of the [respondents] attended the said meeting, [Petitioner] Jose Luis Bondoc,manager of the company, did not allow [respondents] to work anymore in the plantation.Thereafter, on various dates, [respondents] filed their respective complaints with the NLRC, Sub-RegionalArbitration Branch No. VII, Dumaguete City against [petitioners] for unfair labor practice, illegal dismissal,underpayment, overtime pay, premium pay for rest day and holidays, service incentive leave pay,damages, attorneys fees and 13th month pay.On 09 October 1997, [respondent] Carlito Tinghil amended his complaint to implead Pamplona PlantationLeisure Corporation x x x.On 31 August 1998, Labor Arbiter Jose G. Gutierrez rendered a decision finding [respondents], exceptRufino Bacubac, Antonio Caolas and Felix Torres who were complainants in another case, to be entitled toseparation pay.xxxxxxxxx
[Petitioners] appealed the Labor Arbiters decision to [the] NLRC. In the assailed decision dated 19 July2000, the NLRCs Fourth Division reversed the Labor Arbiter, ruling that [respondents], except CarlitoTinghil, failed to implead Pamplona Plantation Leisure Corporation, an indispensable party and that thereexist no employer-employee relation between the parties.xxxxxxxxx[Respondents] filed a motion for reconsideration which was denied by [the] NLRC in a Resolution dated 06December 2000.[8]Respondents elevated the case to the CA via a Petition for Certiorari under Rule 65 of the Rules ofCourt.Ruling of the Court of AppealsGuided by the fourfold test for determining the existence of an employer-employee relationship, theCA held that respondents were employees of petitioner-company. Finding there was a power to hire, theappellate court considered the admission of petitioners in their Comment that they had hired respondentsas coconut filers, coconut scoopers, charcoal makers, or as pieceworkers. The fact that respondents werepaid by piecework did not mean that they were not employees of the company. Further, the CA ruled thatpetitioners necessarily exercised control over the work they performed, since the latter were workingwithin the premises of the plantation. According to the CA, the mere existence -- not necessarily the actualexercise -- of the right to control the manner of doing work sufficed to meet the fourth element of anemployer-employee relation.The appellate court also held that respondents were regular employees, because the tasks theyperformed were necessary and indispensable to the operation of the company. Since there was nocompliance with the twin requirements of a valid and/or authorized cause and of procedural due process,their dismissal was illegal.Hence, this Petition.[9]IssuesIn their Memorandum, petitioners submit the following issues for our consideration:1. Whether or not the finding of the Court of Appeals that herein respondents are employees ofPetitioner Pamplona Plantation Company, Inc. is contrary to the admissions of the respondentsthemselves.2. Whether or not the Court of Appeals has decided in a way not in accord with law and jurisprudence,and with grave abuse of discretion, in not dismissing the respondents complaint for failure toimplead Pamplona Plantation Leisure Corp., which is an indispensable party to this case.3. Whether or not the Court of Appeals has decided in a way not in accord with law and jurisprudence,and with grave abuse of discretion in ordering reinstatement or payment of separation pay andbackwages to the respondents, considering the lack of employer-employee relationship betweenpetitioner and respondents.[10]The main issue raised is whether the case should be dismissed for the non-joinder of the PamplonaPlantation Leisure Corporation. The other issues will be taken up in the discussion of the main question.The Courts Ruling
The principle requiring the piercing of the corporate veil mandates courts to see through the protectiveshroud that distinguishes one corporation from a seemingly separate one. [23] The corporate mask may beremoved and the corporate veil pierced when a corporation is the mere alter ego of another. [24] Wherebadges of fraud exist, where public convenience is defeated, where a wrong is sought to be justifiedthereby, or where a separate corporate identity is used to evade financial obligations to employees or tothird parties,[25] the notion of separate legal entity should be set aside [26] and the factual truth upheld.When that happens, the corporate character is not necessarily abrogated. [27] It continues for otherlegitimate objectives. However, it may be pierced in any of the instances cited in order to promotesubstantial justice.In the present case, the corporations have basically the same incorporators and directors and areheaded by the same official. Both use only one office and one payroll and are under one management. Intheir individual Affidavits, respondents allege that they worked under the supervision and control ofPetitioner Bondoc -- the common managing director of both the petitioner-company and the leisurecorporation. Some of the laborers of the plantation also work in the golf course. [28] Thus, the attempt tomake the two corporations appear as two separate entities, insofar as the workers are concerned, shouldbe viewed as a devious but obvious means to defeat the ends of the law. Such a ploy should not bepermitted to cloud the truth and perpetrate an injustice.We note that this defense of separate corporate identity was not raised during the proceedings beforethe labor arbiter. The main argument therein raised by petitioners was their alleged lack of employeremployee relationship with, and power of control over, the means and methods of work of respondentsbecause of the seasonal nature of the latters work.[29]Neither was the issue of non-joinder of indispensable parties raised in petitioners appeal before theNLRC.[30] Nevertheless, in its Decision[31] dated July 19, 2000, the Commission concluded that the plantationcompany and the leisure corporation were two separate and distinct corporations, and that the latter wasan indispensable party that should have been impleaded. We quote below pertinent portions of thatDecision:Respondent posits that it is engaged in operating and maintaining sugar and coconut plantation. Thepositions of complainants could only be determined through their individual complaints. Yet allcomplainants alleged in their affidavits x x x that they were working at the golf course. Worthy to note thatonly Carlito Tinghil amended his complaint to include Pamplona Leisure Corporation, which respondentsmaintain is a separate corporation established in 1995. Thus, xxx Pamplona Plantation Co., Inc. andPamplona Leisure Corporation are two separate and distinct corporations. Except for Carlito Tinghil thecomplainants have the wrong party respondent. Pamplona Leisure Corporation is an indispensable partywithout which there could be no final determination of the case. [32]Indeed, it was only after this NLRC Decision was issued that the petitioners harped on the separatepersonality of the Pamplona Plantation Co., Inc., vis--vis the Pamplona Plantation Leisure Corporation.As cited above, the NLRC dismissed the Complaints because of the alleged admission of respondentsin their Affidavits that they had been working at the golf course. However, it failed to appreciate the rest oftheir averments. Just because they worked at the golf course did not necessarily mean that they were notemployed to do other tasks, especially since the golf course was merely a portion of the coconutplantation. Even petitioners admitted that respondents had been hired as coconut filers, coconut scoopersor charcoal makers.[33] Consequently, NLRCs conclusion derived from the Affidavits of respondents statingthat they were employees of the Pamplona Plantation Leisure Corporation alone was the result of animproper selective appreciation of the entire evidence.Furthermore, we note that, contrary to the NLRCs findings, some respondents indicated that theiremployer was the Pamplona Plantation Leisure Corporation, while others said that it was the Pamplona
Plantation Co., Inc. But in all these Affidavits, both the leisure corporation and petitioner-company wereidentified or described as entities engaged in the development and operation of sugar and coconutplantations, as well as recreational facilities such as a golf course. These allegations reveal that petitionersuccessfully confused the workers as to who their true and real employer was. All things considered, theirfaulty belief that the plantation company and the leisure corporation were one and the same can beattributed solely to petitioners. It would certainly be unjust to prejudice the claims of the workers becauseof the misleading actions of their employer.Non-Joinder of PartiesGranting for the sake of argument that the Pamplona Plantation Leisure Corporation is anindispensable party that should be impleaded, NLRCs outright dismissal of the Complaints was stillerroneous.The non-joinder of indispensable parties is not a ground for the dismissal of an action. [34] At any stageof a judicial proceeding and/or at such times as are just, parties may be added on the motion of a party oron the initiative of the tribunal concerned.[35] If the plaintiff refuses to implead an indispensable partydespite the order of the court, that court may dismiss the complaint for the plaintiffs failure to comply withthe order. The remedy is to implead the non-party claimed to be indispensable. [36] In this case, the NLRCdid not require respondents to implead the Pamplona Plantation Leisure Corporation as respondent;instead, the Commission summarily dismissed the Complaints.In any event, there is no need to implead the leisure corporation because, insofar as respondents areconcerned, the leisure corporation and petitioner-company are one and the same entity.Salvador v. Courtof Appeals[37] has held that this Court has full powers, apart from that power and authority which isinherent, to amend the processes, pleadings, proceedings and decisions by substituting as party-plaintiffthe real party-in-interest.In Alonso v. Villamor,[38] we had the occasion to state thus:There is nothing sacred about processes or pleadings, their forms or contents. Their sole purpose is tofacilitate the application of justice to the rival claims of contending parties. They were created, not tohinder and delay, but to facilitate and promote, the administration of justice. They do not constitute thething itself, which courts are always striving to secure to litigants. They are designed as the means bestadapted to obtain that thing. In other words, they are a means to an end. When they lose the character ofthe one and become the other, the administration of justice is at fault and courts are correspondinglyremiss in the performance of their obvious duty.The controlling principle in the interpretation of procedural rules is liberality, so that they may promotetheir object and assist the parties in obtaining just, speedy and inexpensive determination of every actionand proceeding.[39] When the rules are applied to labor cases, this liberal interpretation must be upheldwith even greater vigor.[40] Without in any way depriving the employer of its legal rights, the thrust ofstatutes and rules governing labor cases has been to benefit workers and avoid subjecting them to greatdelays and hardships. This intent holds especially in this case, in which the plaintiffs are poor laborers.Employer-Employee RelationshipPetitioners insist that respondents are not their employees, because the former exercised no controlover the latters work hours and method of performing tasks. Thus, petitioners contend that under thecontrol test, the workers were independent contractors.We disagree. As shown by the evidence on record, petitioners hired respondents, who performed tasksassigned by their respective officers-in-charge, who in turn were all under the direct supervision and
control of Petitioner Bondoc. These allegations are contained in the workers Affidavits, which were neverdisputed by petitioners. Also uncontroverted are the payrolls bearing the name of the plantation companyand signed by Petitioner Bondoc. Some of these payrolls include the time records of the employees. Thesedocuments prove that petitioner-company exercised control and supervision over them.To operate against the employer, the power of control need not have been actually exercised. Proof ofthe existence of such power is enough. [41] Certainly, petitioners wielded that power to hire or dismiss, aswell as to check on the progress and the quality of work of the laborers.Jurisprudence provides other equally important considerations [42] that support the conclusion thatrespondents were not independent contractors. First, they cannot be said to have carried on anindependent business or occupation. [43] They are not engaged in the business of filing, scooping andhauling coconuts and/or operating and maintaining a plantation and a golf course. Second, they do nothave substantial capital or investment in the form of tools, equipment, machinery, work premises, andother implements needed to perform the job, work or service under their own account or responsibility.[44]Third, they have been working exclusively for petitioners for several years. Fourth, there is no disputethat petitioners are in the business of growing coconut trees for commercial purposes. There is noquestion, either, that a portion of the plantation was converted into a golf course and other recreationalfacilities. Clearly, respondents performed usual, regular and necessary services for petitioners business.WHEREFORE, the Petition is DENIED, and the assailed Decision AFFIRMED. Costs against thepetitioners.SO ORDERED.Sandoval-Gutierrez, Corona, Carpio-Morales, and Garcia, JJ., concur.
MELO, J.:Before us is a petition for certiorari assailing the decision of public respondent National Labor RelationsCommission (NLRC) promulgated on August 25, 1993 in the cases of Fernando Duran, et al. vs. TanduayDistillery, Inc.,docketed as NLRC NCR Case No. 00-04-01737-88, and Rodrigo Santos vs. Tanduay Distillery,Inc., docketed as NLRC NCR Case No. 00-06-02546-88.The relevant antecedent facts as gathered from the record are as follows:Private respondents-employees Fernando Duran, Eduardo Paliwan, Roque Estoce, and Rodrigo Santos wereemployees of respondent corporation Tanduay Distillery, Inc, (TDI).On March 29, 1988, 22 employees of TDI, including private respondents employees, received amemorandum from TDI terminating their services. for reasons of retrenchment, effective 30 days fromreceipt thereof or not later than the close of business hours on April 28, 1988.On April 26, 1988, all 22 employees of TDI filed an application for the issuance of a temporary restrainingorder against their retrenchment. The labor arbiter issued the restraining order the following day. However,due to the 20-day lifetime of the temporary restraining order, and because of the on-going negotiations forthe sale of TDI the retrenchment pushed through. Parenthetically, it should be mentioned that although all22 employees were retrenched, the instant petition involves only the 4 individual respondents herein,namely, Fernando Duran, Eduardo Paliwan, Roque Estoce, and Rodrigo Santos.On June 14, 1988, the First Pacific Metro Corporation moved that it be dropped as a party to the case onthe ground that its projected purchase of the assets of TDI was not consummated. The participation of FirstPacific was later in effect held to be irrelevant (decision dated May 24, 1989; Annex G, pp. 50-58, Rollo).On June 1, 1988, or after respondents-employees had ceased as such employees, a new buyer of TDI'sassets, Twin Ace Holdings, Inc. took over the business. Twin Ace assumed the business name TanduayDistillers.On August 8, 1988, the employees filed a motion to implead herein petitioners James Yu and Wilson Young,doing business under the name and style of Tanduay Distillers, as party respondents in said cases.Petitioners filed an opposition thereto, asserting that they are representatives of Tanduay Distillers anentity distinct and separate from TDI, the previous owner, and that there is no employer-employeerelationship between Tanduay Distillers and private respondents. Respondents-employees filed a reply tothe opposition stating that petitioner James Yu as officer-in-charge of Tanduay Distillers had informed thepresident of TDI labor union of Tanduay Distillers' decision to hire everybody with a clean slate on aprobation basis.On November 16, 1988, private respondents filed a motion for leave to file an amended complaintimpleading petitioners as respondents. Petitioners filed an opposition thereto reiterating the grounds theyrelied upon in their opposition to private respondents' motion to implead. A reply was filed by privaterespondents, and a rejoinder was then filed by petitioners. In turn, private respondents filed a subrejoinder.Subsequently, an amended complaint was filed by private respondents against TDI and petitioners Yu andYoung "doing business under the name and style of Tanduay Distillers".In her decision dated May 24, 1989, Labor Arbiter Daisy Cauton-Barcelona held:
In treating the motion to implead a motion to admit amended complaint with leave, thesame [is] hereby given due course and all pleadings filed by respondents James Yu andWilson Young are hereby treated as their responsive pleadings in the light of speedydisposition of justice and the basic rule that administrative fora, such as this office, are notgoverned by technical rules of proceedings.(p. 52, Rollo).In the same decision, it was disposed:WHEREFORE, judgment is hereby rendered and declaring that the retrenchment is illegalthereby ordering respondent Tanduay Distillery, Inc., to reinstate the complainants to theirformer position with backwages up to the time of change of ownership, if one has takenplace.That in the event of change in management it (Tanduay Distillery, Inc.,) is hereby ordered topay the complainants their respective separation benefits computed.)Only TDI appealed said decision to the National Labor Relations Commission, but on June 18, 1991, saidcommission promulgated an affirmance decision (p. 102, Rollo). TDI filed a motion for reconsideration, butthe same was denied on August 15, 1991.Thereupon, private respondents-employees on September 16, 1991 filed a motion for execution (Annex Q,pp. 103-106, Rollo) praying that NLRC through the labor arbiter, "[i]ssue the necessary writ for theexecution of the entire decision dated May 24, 1989, including the actual reinstatement of thecomplainants to their former position without loss of seniority and benefits against Tanduay Distillery, Inc.,and/or Tanduay Distillers, James Yu and Wilson Young."On September 24, 1993, petitioners filed an opposition (Annex R, pp. 108-110, Rollo) to the motion forexecution on the ground that "the Motion for Execution is without any basis in so far as it prays for theissuance of a writ of execution against respondent Tanduay Distillers, which is an entity separate anddistinct from respondent Tanduay Distillery, Inc., and respondents James Yu and Wilson Young."Respondents-employees filed their reply thereto (Annex S, pp. 111-115, Rollo), and in turn petitioners filedtheir rejoinder (Annex T, pp. 116-118, Rollo), to which private respondents filed their sur-rejoinder (AnnexU, pp. 119-122, Rollo). On December 18, 1991, respondent TDI filed its comment on the motion forexecution (Annex V, pp. 124-129, Rollo), while petitioners on January 10, 1992, filed a joint comment(Annex W, pp. 130-132, Rollo) to private respondents' sur-rejoinder as well to the comment filed byrespondent TDI.Subsequently, TDI filed a manifestation dated April 24, 1992 (Annex X, pp. 133-135, Rollo), stating 2. At the hearing held on March 23, 1992, individual complainants, assisted by their counsel,Atty. Noel Cruz, agreed to be paid the total amount of P86,049.83, in full satisfaction of theCompany's liability as stated in the dispositive portion of Labor Arbiter Barcelona's decisionpromulgated on May 24, 1989 and affirmed by the Second Division of the NLRC on June 18,1991, which reads as follows:WHEREFORE, judgment is hereby rendered declaring that the retrenchment isillegal thereby ordering respondent Tanduay Distillery, Inc. to reinstate thecomplainants to their former position with backwages up to the time of thechange of ownership, if one has taken place.That in the event of change in management it (Tanduay Distillery, Inc.( ishereby ordered to pay the complainants their respective separation benefits
computed at the rate of one (1) month of every year of service. This is withoutprejudice to the letter of Mr. James Yu as officer-in-charge of Tanduay Distillersdated June 17, 1988 to the President of the Tanduay Distillery, Inc., LaborUnion.No Costs.SO ORDERED.1. In accordance with the aforequoted decision, complainants shall be paid the amountsappearing opposite their respective names:
Rodrigo F.Santos
P20,282.03
RoqueEstoce
20,092.50
EduardoDaliwan
19,973.40
Fernando A. 25,702.0Duran0
Total P86,049.83
=========
4. The foregoing amounts shall be satisfied out of the cash bond deposited by the Companywith the Cashier of the NLRC. The excess amounting to P7,076.44 must revert to theCompany.(pp. 134-135, Rollo.)On November 17, 1992, respondent NLRC, through Labor Arbiter Daniel C. Cueto, issued an order (AnnexZ, pp. 139-145, Rollo), resolving the motion for execution as follows:Based on the foregoing considerations, this Branch finds the Motion for Writ of Executionfiled by the complainants meritorious and in order. Accordingly, let a Writ of Execution beissued against Tanduay Distiller, Inc., Wilson Young and James Yu to immediately reinstatecomplainants Fernando Duran, Rodrigo Santos, Roque Estoce and Eduardo Daliwan to theirrespective positions.
(p 145, Rollo.)Consequently, a writ of execution was issued by Labor Arbiter Cueto on December 16, 1992.To stop the implementation of the writ of execution, petitioners filed a petition for certiorari (Annex AA, pp.146-158,Rollo before respondent NLRC, praying that 1. Immediately upon filing of the instant case, a temporary restraining order he issued, towit.a) Enjoining and restraining the respondents from implementing the Orderdated November 17, 1992;b.) Commanding the public respondent to desist from acting on the Order,c.) Commanding the respondents to desist from committing any other actjudicial to the petitioners/appellants.2. After the appropriate proceedings, a writ of preliminary injunction be issued so enjoiningthe respondents;3. After hearing on the merits, the Order dated November 17, 1992 be set aside and aninjunction be issued permanently enjoining the respondents from committing the aforesaidacts and to comply strictly with terms of the Decision and the NLRC;4. Ordering the respondents, jointly and severally, to pay petitioner's fees in the amount ofP100,000.00 and to pay the cost of suit.On August 25, 1993, respondent NLRC promulgated its decision, the dispositive portion of which reads:In view of the foregoing premises, the petition/appeal with prayer for preliminary injunctionis hereby dismissed for lack of merit.The petitioners respondents are hereby directed to re re-employ/re-hire respondentscomplainants immediately upon receipt of this decision.(p. 36, Rollo.)Thus, the present petition where petitioners pray that 1. Immediately upon filing of the instant case, a temporary restraining order be issued, towit:a) Restraining and prohibiting the respondents form implementing the ORDERdated November 17, 1992 and the NLRC Certiorari Decision.b) Commanding the respondents to desist from committing any other actprejudicial to the petitioners.2. After the appropriate proceedings, a writ of preliminary injunction be issued so enjoiningthe respondents;3. After appropriate proceedings, the ORDER dated November 17, 1992 and theNLRC CertiorariDecision be set aside and a injunction be issued permanently enjoining therespondents from committing the aforesaid acts and to comply strictly with the terms of theArbiter Decision and the NLRC Decision;
4. Ordering the respondents, jointly and severally, to pay petitioners' attorney's fees in theamount of P100,000.00 and to pay the costs of suit.(pp. 26-27, Rollo.)The issue posed by the present petition is whether respondent NLRC committed grave abuse of discretionin holding petitioners Yu and Young liable under the decision dated May 24, 1989 which decreed that:WHEREFORE, judgment is hereby rendered declaring that the retrenchment is illegal therebyordering respondent Tanduay Distillery Inc., to reinstate the complainants to their formerposition with backwages up to the time of the change ownership, if one has taken place.That in the event of change in management it (Tanduay Distillery, Inc.) is hereby ordered topay the complainants their respective separation benefits corrupted.)We hold that petitioners, for a number of reasons which we shall discuss below, may not be heldanswerable and liable under the final judgment of Labor Arbiter Cauton-Barcelona.1. Admittedly, the decision dated May 24, 1989 is now final and executory, as only respondent TDIappealed said decision and its appeal was later dismissed by respondent NLRC. It is fundamental that afinal and executory decision cannot be amended or corrected (First Integrated Bonding and InsuranceCompany, Inc, vs. Hernando, 199 SCRA 796 [1991]) except for clerical errors or mistakes (Maramba vs.Lozano, 20 SCRA 474 [1967]); Reyes vs. Court of Appeals, 189 SCRA 46 [1990]). A definitive judgment is nolonger subject to change, revision, amendment, or reversal (Miranda vs. Court of Appeals, 71 SCRA 295[1976], and the court loses jurisdiction over it, except to order its execution (PY Eng Chong vs. Herrera, 70SCRA 130 (1976]).An examination of the aforequoted dispositive portion of the decision shows that the same does not in anymanner obligate Tanduay Distillers, or even petitioners Yu and Young for that matter, to reinstaterespondents. Only TDI was held liable to reinstate respondents up to the time of change of ownership, andfor separation benefits.However, Labor Arbiter Cueto went beyond what was disposed by the decision and issued an order datedNovember 17, 1992 (Annex Z, Petition, pp. 139-145, Rollo) which required. . . Tanduay Distillers, Inc., Wilson Young and James Yu to immediately reinstatecomplainants Fernando Duran, Rodrigo Santos, Roque Estoce and Eduardo Daliwan to heirrespective positions.(p. 145, Rollo.)Subsequently, a writ of execution was issued on December 16, 1992 pursuant to the order of November17, 1992.The order of execution dated November 17, 1992 in effect amended the decision dated May 24, 1989 forthe former orders petitioners and Tanduay Distillers to reinstate private respondents employees whereasthe decision dated May 24, 1989, as we have discussed above, does not so decree, This cannot be done. Itis beyond the power and competence of Labor Arbiter Cueto to amend a final decision, The writ ofexecution must not go beyond the scope of the judgment.As Chief Justice Moran opined: "The writ of execution must conform to the judgment which isto be executed as it may not vary the terms of the judgment it seeks to enforce. Nor may itgo beyond the terms of the judgment, sought to be executed. Where the execution is not in
harmony with the judgment which gives it life and exceeds it, it has pro tanto no validity. Tomaintain otherwise would be to ignore the constitutional provision against depriving aperson of his property without due process of law" (Moran, Comments on the Rules of Court,Vol. I 1952 Ed., p. 809; cited in Villoria vs. Piccio,supra).(Gamboa's Incorporated vs. Court ofAppeals, 72 SCRA 131, 137-138 [1976])The order of execution and the writ of execution ordering petitioners and Tanduay Distillers to reinstateprivate respondents employees are, therefore, null and void.2. Neither may be said that petitioners and Tanduay Distillers are one and the same as TDI, as seems to bethe impression of respondents when they impleaded petitioners as party respondents in their compliant forunfair labor practice, illegal lay off, and separation benefits.Such a stance is not supported by the facts. The name of the company for whom the petitioners areworking is Twin Ace Holdings Corporation, As stated by the Solicitor General, Twin Ace is part of the AlliedBank Group although it conducts the rum business under the name of Tanduay Distillers. The use of asimilar sounding or almost identical name is an obvious device to capitalize on the goodwill which TanduayRum has built over the years. Twin Ace or Tanduay Distillers, on one hand, and Tanduay Distillery Inc. (TDI),on the other, are distinct and separate corporations. There is nothing to suggest that the owners of TDI,have any common relationship as to identify it with Allied Bank Group which runs Tanduay Distillers. Thedissertation of the Court in Diatagon Labor Federation Local 110 of the ULGWP vs. Ople, et al. (101 SCRA534 [1980]) is worthy of restatement, thusly:We hold that the director of labor Relations acted with grave abuse of discretion in treatingthe two companies as a single bargaining unit. The ruling is arbitrary and untenable becausethe two companies are indubitably distinct entities with separate juridical personalities.The fact that their businesses are related and that the 236 employees of Georgia PacificInternational Corporation were originally employees of Lianga Bay Logging Co., Inc, is not ajustification for disregarding their separate personalities. Hence, the 236 employees, whoare now attached to Georgia Pacific International should not be allowed to vote in thecertification election at the Lianga Bay Logging Co., Inc. They should vote at a separatecertification election to determine the collective bargaining representative of the employeesof Georgia Pacific International Corporation.(at pp. 540-541.)It is basic that a corporation is invested by law with a personality separate and distinct from those of thepersons composing it as well as from that of any other legal entity to which it may be related (Palay, Inc. etal. vs. Clave, et al., 124 SCRA 641 [1983]).The genuine nature of the sale to Twin Ace is evidenced by the fact that Twin Ace was only a subsequentinterested buyer. At the time when termination notices were sent to its employees, TDI was negotiatingwith the First Pacific Metro Corporation for the sale of its assets. Only after First Pacific gave up its efforts toacquire the assets did Twin Ace or Tanduay Distillers come into the picture. Respondents-employees havenot presented any proof as to communality of ownership and management to support their contention thatthe two companies are one firm or closely related. The doctrine of piercing the veil of corporate entityapplies when the corporate fiction is used to defeat public convenience, justify wrong, protect fraud, ordefend crime or where a corporation is the mere alter ego or business conduit of a person (Indophil TextileMill Workers Union vs. Calica, 205 SCRA 697, 703 (1992]). To disregard the separate juridical personality ofa corporation, the wrong-doing must be clearly and convincingly established. It cannot be presumed (DelRosario vs. NLRC, 187 SCRA 777, 7809 [1990]).The complaint for unfair labor practice, illegal lay off, and separation benefits was filed against TDI. Onlylater when the manufacture and sale of Tanduay products was taken over by Twin Ace or Tanduay Distillerswere James Yu and Wilson Young impleaded.
The corporation itself Twin Ace or Tanduay Distillers was never made a party to the case.Another factor to consider is that TDI as a corporation or its shares of stock were not purchased by TwinAce. The buyer limited itself to purchasing most of the assets, equipment, and machinery of TDI. Thus,Twin Ace or Tanduay Distillers did not take over the corporate personality of DTI although they manufacturethe same product at the same plant with the same equipment and machinery. Obviously, the trade name"Tanduay" went with the sale because the new firm does business as Tanduay Distillers and its mainproduct of rum is sold as Tanduay Rum. There is no showing, however, that TDI itself was absorbed by TwinAce or that it ceased to exist as a separate corporation, In point of fact TDI is now herein a partyrespondent represented by its own counsel.Significantly, TDI in the petition at hand has taken the side of its former employees and argues againstTanduay Distillers. In its memorandum filed on January 9, 1995, TDI argues that it was not alone its liabilitywhich arbiter recognized "but also of James Yu and Wilson Young representatives of Twin Ace and/or theAllied Bank Group doing business under the name "TANDUAY DISTILLERS," to whom the business andassets of TDI were sold." If TDI and Tanduay, Distillers are one and the same group or one is a continuationof the other, the two would not be fighting each other in this case. TDI would not argue strongly "that thepetition for certiorari filed by James Yu and Wilson Young be dismissed for lack of merit." It is obvious thatthe second corporation, Twin Ace or Tanduay Distillers, is an entity separate and distinct, from the firstcorporation, TDI. The circumstances of this case are different from the earlier decisions of the Court inlabor cases where the veil of corporate fiction was pierced.In La Campana Coffee Factory. Inc. vs. Kaisahan ng Mangagawa sa La Campana (KKM), (93 Phil, 160[1953]), La Campana Coffee Factory, Inc. and La Campana Gaugau Packing were substantially owned bythe same person. They had one office, one management, and a single payroll for both businesses. Thelaborers of the gaugau factory and the coffee factory were also interchangeable, the workers in one factoryworked also in the other factory.In Claparols vs. Court of Industrial Relations (65 SCRA 613 (1975]), the Claparols Steel and Nail Plant,which was ordered to pay its workers backwages, ceased operations on June 30, 1956 and wassucceeded on the very next day, July 1, 1957, by the Claparols Steel Corporation. Both corporations weresubstantially owned and controlled by the same person and there was no break or cessation in operations.Moreover, all the assets of the steel and nail plant were transferred to the new corporation.In fine, the fiction of separate and distinct corporate entities cannot, in the instant case, be disregardedand brushed aside, there being not the least indication that the second corporation is a dummy or servesas a client of the first corporate entity.In the case at bench, since TDI and Twin Ace or Tanduay Distillers are two separate and distinct entities,the order for Tanduay Distillers (and petitioners) to reinstate respondents-employees is obviously withoutlegal and factual basis.3. Nor could the order and writ to reinstate be anchored on the vague and seemingly uncalled foralternative disposition in the Barcelona decision that . . . This is without prejudice to the letter of Mr. James Yu as officer-in-charge of TanduayDistillers dated June 16, 1988 to the President of the Tanduay Distillery, Inc. labor Union.The June 11, 1988 letter referred to was addressed to Benjamin C. Agaloos, president of the TanduayDistillery Labor Union by James Yu in his capacity as officer-in-charge of Tanduay Distillers.It pertinently reads:Please be informed that our company stands firm on its decision to hire everybody with aclean slate effective June 1, 1988 on a probationary basis while those currently casual orcontractual employees shall retain the same employment status. In the same manner thatthe new company stood firm on its decision to grant a 10% across-the-board increase to allemployees, which in fact has been received by employees concerned.
MEDIALDEA, J.:This is a petition for certiorari seeking the nullification of the award issued by the respondent VoluntaryArbitrator Teodorico P. Calica dated December 8, 1990 finding that Section 1 (c), Article I of the CollectiveBargaining Agreement between Indophil Textile Mills, Inc. and Indophil Textile Mill Workers Union-PTGWOdoes not extend to the employees of Indophil Acrylic Manufacturing Corporation as an extension orexpansion of Indophil Textile Mills, Incorporated.The antecedent facts are as follows:Petitioner Indophil Textile Mill Workers Union-PTGWO is a legitimate labor organization duly registered withthe Department of Labor and Employment and the exclusive bargaining agent of all the rank-and-fileemployees of Indophil Textile Mills, Incorporated. Respondent Teodorico P. Calica is impleaded in his officialcapacity as the Voluntary Arbitrator of the National Conciliation and Mediation Board of the Department ofLabor and Employment, while private respondent Indophil Textile Mills, Inc. is a corporation engaged in themanufacture, sale and export of yarns of various counts and kinds and of materials of kindred characterand has its plants at Barrio Lambakin. Marilao, Bulacan.In April, 1987, petitioner Indophil Textile Mill Workers Union-PTGWO and private respondent Indophil TextileMills, Inc. executed a collective bargaining agreement effective from April 1, 1987 to March 31, 1990.On November 3, 1967 Indophil Acrylic Manufacturing Corporation was formed and registered with theSecurities and Exchange Commission. Subsequently, Acrylic applied for registration with the Board ofInvestments for incentives under the 1987 Omnibus Investments Code. The application was approved on apreferred non-pioneer status.In 1988, Acrylic became operational and hired workers according to its own criteria and standards.Sometime in July, 1989, the workers of Acrylic unionized and a duly certified collective bargainingagreement was executed.In 1990 or a year after the workers of Acrylic have been unionized and a CBA executed, the petitionerunion claimed that the plant facilities built and set up by Acrylic should be considered as an extension orexpansion of the facilities of private respondent Company pursuant to Section 1(c), Article I of the CBA, towit,.c) This Agreement shall apply to the Company's plant facilities andinstallations and to any extension and expansion thereat. (Rollo, p.4)In other words, it is the petitioner's contention that Acrylic is part of the Indophil bargaining unit.The petitioner's contention was opposed by private respondent which submits that it is a juridical entityseparate and distinct from Acrylic.The existing impasse led the petitioner and private respondent to enter into a submission agreement onSeptember 6, 1990. The parties jointly requested the public respondent to act as voluntary arbitrator in theresolution of the pending labor dispute pertaining to the proper interpretation of the CBA provision.
After the parties submitted their respective position papers and replies, the public respondent VoluntaryArbitrator rendered its award on December 8, 1990, the dispositive portion of which provides as follows:PREMISES CONSIDERED, it would be a strained interpretation and application of thequestioned CBA provision if we would extend to the employees of Acrylic the coverageclause of Indophil Textile Mills CBA. Wherefore, an award is made to the effect that theproper interpretation and application of Sec. l, (c), Art. I, of the 1987 CBA do (sic) not extendto the employees of Acrylic as an extension or expansion of Indophil Textile Mills, Inc. (Rollo,p.21)Hence, this petition raising four (4) issues, to wit:1. WHETHER OR NOT THE RESPONDENT ARBITRATOR ERRED IN INTERPRETINGSECTION 1(c), ART I OF THE CBA BETWEEN PETITIONER UNION ANDRESPONDENT COMPANY.2. WHETHER OR NOT INDOPHIL ACRYLIC IS A SEPARATE AND DISTINCT ENTITYFROM RESPONDENT COMPANY FOR PURPOSES OF UNION REPRESENTATION.3. WHETHER OR NOT THE RESPONDENT ARBITRATOR GRAVELY ABUSED HISDISCRETION AMOUNTING TO LACK OR IN EXCESS OF HIS JURISDICTION.4. WHETHER OR NOT THE RESPONDENT ARBITRATOR VIOLATED PETITIONERUNION'S CARDINAL PRIMARY RIGHT TO DUE PROCESS. (Rollo, pp. 6-7)The central issue submitted for arbitration is whether or not the operations in Indophil Acrylic Corporationare an extension or expansion of private respondent Company. Corollary to the aforementioned issue is thequestion of whether or not the rank-and-file employees working at Indophil Acrylic should be recognized aspart of, and/or within the scope of the bargaining unit.Petitioner maintains that public respondent Arbitrator gravely erred in interpreting Section l(c), Article I ofthe CBA in its literal meaning without taking cognizance of the facts adduced that the creation of theaforesaid Indophil Acrylic is but a devise of respondent Company to evade the application of the CBAbetween petitioner Union and respondent Company.Petitioner stresses that the articles of incorporation of the two corporations establish that the two entitiesare engaged in the same kind of business, which is the manufacture and sale of yarns of various countsand kinds and of other materials of kindred character or nature.Contrary to petitioner's assertion, the public respondent through the Solicitor General argues that theIndophil Acrylic Manufacturing Corporation is not an alter ego or an adjunct or business conduit of privaterespondent because it has a separate legitimate business purpose. In addition, the Solicitor Generalalleges that the primary purpose of private respondent is to engage in the business of manufacturing yarnsof various counts and kinds and textiles. On the other hand, the primary purpose of Indophil Acrylic is tomanufacture, buy, sell at wholesale basis, barter, import, export and otherwise deal in yarns of variouscounts and kinds. Hence, unlike private respondent, Indophil Acrylic cannot manufacture textiles whileprivate respondent cannot buy or import yarns.Furthermore, petitioner emphasizes that the two corporations have practically the same incorporators,directors and officers. In fact, of the total stock subscription of Indophil Acrylic, P1,749,970.00 whichrepresents seventy percent (70%) of the total subscription of P2,500,000.00 was subscribed to byrespondent Company.On this point, private respondent cited the case of Diatagon Labor Federation v. Ople, G.R. No. L-44493-94,December 3, 1980, 10l SCRA 534, which ruled that two corporations cannot be treated as a singlebargaining unit even if their businesses are related. It submits that the fact that there are as manybargaining units as there are companies in a conglomeration of companies is a positive proof that acorporation is endowed with a legal personality distinctly its own, independent and separate from othercorporations (see Rollo, pp. 160-161).
Petitioner notes that the foregoing evidence sufficiently establish that Acrylic is but an extension orexpansion of private respondent, to wit:(a) the two corporations have their physical plants, offices and facilitiessituated in the same compound, at Barrio Lambakin, Marilao, Bulacan;(b) many of private respondent's own machineries, such as dyeing machines,reeling, boiler, Kamitsus among others, were transferred to and are nowinstalled and being used in the Acrylic plant;(c) the services of a number of units, departments or sections of privaterespondent are provided to Acrylic; and(d) the employees of private respondent are the same persons manning andservicing the units of Acrylic. (see Rollo, pp. 12-13)Private respondent insists that the existence of a bonafide business relationship between Acrylic andprivate respondent is not a proof of being a single corporate entity because the services which aresupposedly provided by it to Acrylic are auxiliary services or activities which are not really essential in theactual production of Acrylic. It also pointed out that the essential services are discharged exclusively byAcrylic personnel under the control and supervision of Acrylic managers and supervisors.In sum, petitioner insists that the public respondent committed grave abuse of discretion amounting tolack or in excess of jurisdiction in erroneously interpreting the CBA provision and in failing to disregard thecorporate entity of Acrylic.We find the petition devoid of merit.Time and again, We stress that the decisions of voluntary arbitrators are to be given the highest respectand a certain measure of finality, but this is not a hard and fast rule, it does not preclude judicial reviewthereof where want of jurisdiction, grave abuse of discretion, violation of due process, denial of substantialjustice, or erroneous interpretation of the law were brought to our attention. (see Ocampo, et al. v. NationalLabor Relations Commission, G.R. No. 81677, 25 July 1990, First Division Minute Resolution citing OceanicBic Division (FFW) v. Romero, G.R. No. L-43890, July 16, 1984, 130 SCRA 392)It should be emphasized that in rendering the subject arbitral award, the voluntary arbitrator TeodoricoCalica, a professor of the U.P. Asian Labor Education Center, now the Institute for Industrial Relations,found that the existing law and jurisprudence on the matter, supported the private respondent'scontentions. Contrary to petitioner's assertion, public respondent cited facts and the law upon which hebased the award. Hence, public respondent did not abuse his discretionliability will attach directly to the officers and stockholders. The doctrine applies when the corporate fictionis used to defeat public convenience, justify wrong, protect fraud, or defend crime, or when it is made as ashield to confuse the legitimate issues, or where a corporation is the mere alter ego or business conduit ofa person, or where the corporation is so organized and controlled and its affairs are so conducted as tomake it merely an instrumentality, agency, conduit or adjunct of another corporation. (Umali et al. v. Courtof Appeals, G.R. No. 89561, September 13, 1990, 189 SCRA 529, 542)In the case at bar, petitioner seeks to pierce the veil of corporate entity of Acrylic, alleging that thecreation of the corporation is a devise to evade the application of the CBA between petitioner Union andprivate respondent Company. While we do not discount the possibility of the similarities of the businessesof private respondent and Acrylic, neither are we inclined to apply the doctrine invoked by petitioner ingranting the relief sought. The fact that the businesses of private respondent and Acrylic are related, thatsome of the employees of the private respondent are the same persons manning and providing forauxilliary services to the units of Acrylic, and that the physical plants, offices and facilities are situated in
the same compound, it is our considered opinion that these facts are not sufficient to justify the piercing ofthe corporate veil of Acrylic.In the same case of Umali, et al. v. Court of Appeals (supra), We already emphasized that "the legalcorporate entity is disregarded only if it is sought to hold the officers and stockholders directly liable for acorporate debt or obligation." In the instant case, petitioner does not seek to impose a claim against themembers of the Acrylic.Furthermore, We already ruled in the case of Diatagon Labor Federation Local 110 of the ULGWPv. Ople (supra) that it is grave abuse of discretion to treat two companies as a single bargaining unit whenthese companies are indubitably distinct entities with separate juridical personalities.Hence, the Acrylic not being an extension or expansion of private respondent, the rank-and-file employeesworking at Acrylic should not be recognized as part of, and/or within the scope of the petitioner, as thebargaining representative of private respondent.All premises considered, the Court is convinced that the public respondent Voluntary Arbitrator did notcommit grave abuse of discretion in its interpretation of Section l(c), Article I of the CBA that the Acrylic isnot an extension or expansion of private respondent.ACCORDINGLY, the petition is DENIED and the award of the respondent Voluntary Arbitrator are herebyAFFIRMED.SO ORDERED.Narvasa, C.J., Cruz and Grino-Aquino, JJ., concur.
REGALADO, J.:This is a petition to review the decision of respondent Court of Appeals, dated August 3, 1989, in CA-GR CVNo. 15412, entitled "Buenaflor M. Castillo Umali, et al. vs. Philippine Machinery Parts Manufacturing Co.,Inc., et al.," 1the dispositive portion whereof provides:WHEREFORE, viewed in the light of the entire record, the judgment appealed from must be,as it is hereby REVERSED. In lieu thereof, a judgment is hereby rendered1) Dismissing the complaint, with cost against plaintiffs;2) Ordering plaintiffs-appellees to vacate the subject properties; and3) Ordering plaintiffs-appellees to pay upon defendants' counterclaims:a) To defendant-appellant PM Parts: (i) damages consisting of the value of thefruits in the subject parcels of land of which they were deprived in the sum ofP26,000.00 and (ii) attorney's fees of P15,000.00b) To defendant-appellant Bormaheco: (i) expenses of litigation in the amountof P5,000.00 and (ii) attorney's fees of P15,000.00.SO ORDERED.The original complaint for annulment of title filed in the court a quo by herein petitioners included as partydefendants the Philippine Machinery Parts Manufacturing Co., Inc. (PM Parts), Insurance Corporation of thePhilippines (ICP), Bormaheco, Inc., (Bormaheco) and Santiago M. Rivera (Rivera). A Second AmendedComplaint was filed, this time impleading Santiago M. Rivera as party plaintiff.During the pre-trial conference, the parties entered into the following stipulation of facts:As between all parties: Plaintiff Buenaflor M. Castillo is the judicialadministratrix of the estate of Felipe Castillo in Special Proceeding No. 4053,pending before Branch IX, CFI of Quezon (per Exhibit A) which intestateproceedings was instituted by Mauricia Meer Vda. de Castillo, the previousadministratrix of the said proceedings prior to 1970 (per exhibits A-1 and A-2)which case was filed in Court way back in 1964;b) The four (4) parcels of land described in paragraph 3 of the Complaint wereoriginally covered by TCT No. T-42104 and Tax Dec. No. 14134 with assessedvalue of P3,100.00; TCT No. T 32227 and Tax Dec. No. 14132, with assessedvalue of P5,130,00; TCT No. T-31762 and Tax Dec. No. 14135, with assessed
value of P6,150.00; and TCT No. T-42103 with Tax Dec. No. 14133, withassessed value of P3,580.00 (per Exhibits A-2 and B, B-1 to B-3 C, C-1 -to C3c) That the above-enumerated four (4) parcels of land were the subject of theDeed of Extra-Judicial Partition executed by the heirs of Felipe Castillo (perExhibit D) and by virtue thereof the titles thereto has (sic) been cancelled andin lieu thereof, new titles in the name of Mauricia Meer Vda. de Castillo and ofher children, namely: Buenaflor, Bertilla, Victoria, Marietta and Leovina, allsurnamed Castillo has (sic) been issued, namely: TCT No. T-12113 (Exhibit E );TCT No. T-13113 (Exhibit F); TCT No. T-13116 (Exhibit G ) and TCT No. T13117(Exhibit H )d) That mentioned parcels of land were submitted as guaranty in theAgreement of Counter-Guaranty with Chattel-Real Estate Mortgage executedon 24 October 1970 between Insurance Corporation of the Philippines andSlobec Realty Corporation represented by Santiago Rivera (Exhibit 1);e) That based on the Certificate of Sale issued by the Sheriff of the Province ofQuezon in favor of Insurance Corporation of the Philippines it was able totransfer to itself the titles over the lots in question, namely: TCT No. T-23705(Exhibit M), TCT No. T 23706 (Exhibit N ), TCT No. T-23707 (Exhibit 0) and TCTNo. T 23708 (Exhibit P);f) That on 10 April 1975, the Insurance Corporation of the Philippines sold toPM Parts the immovables in question (per Exhibit 6 for PM Parts) and byreason thereof, succeeded in transferring unto itself the titles over the lots indispute, namely: per TCT No. T-24846 (Exhibit Q ), per TCT No. T-24847(Exhibit R ), TCT No. T-24848 (Exhibit), TCT No. T-24849 (Exhibit T );g) On 26 August l976, Mauricia Meer Vda. de Castillo' genther letter toModesto N. Cervantes stating that she and her children refused to comply withhis demands (Exhibit V-2);h) That from at least the months of October, November and December 1970and January 1971, Modesto N. Cervantes was the Vice-President ofBormaheco, Inc. later President thereof, and also he is one of the Board ofDirectors of PM Parts; on the other hand, Atty. Martin M. De Guzman was thelegal counsel of Bormaheco, Inc., later Executive Vice-President thereof, andwho also is the legal counsel of Insurance Corporation of the Philippines andPM Parts; that Modesto N. Cervantes served later on as President of PM Parts,and that Atty. de Guzman was retained by Insurance Corporation of thePhilippines specifically for foreclosure purposes only;i) Defendant Bormaheco, Inc. on November 25, 1970 sold to Slobec Realty andDevelopment, Inc., represented by Santiago Rivera, President, one (1) unitCaterpillar Tractor D-7 with Serial No. 281114 evidenced by a contract markedExhibit J and Exhibit I for Bormaheco, Inc.;j) That the Surety Bond No. 14010 issued by co-defendant ICP was likewisesecured by an Agreement with Counter-Guaranty with Real Estate Mortgageexecuted by Slobec Realty & Development, Inc., Mauricia Castillo Meer,Buenaflor Castillo, Bertilla Castillo, Victoria Castillo, Marietta Castillo andLeovina Castillo, as mortgagors in favor of ICP which document was executedand ratified before notary public Alberto R. Navoa of the City of Manila onOctober 24,1970;k) That the property mortgaged consisted of four (4) parcels of land situatedin Lucena City and covered by TCT Nos. T-13114, T13115,T-13116 and T-13117 of the Register of Deeds of Lucena City;
l) That the tractor sold by defendant Bormaheco, Inc. to Slobec Realty &Development, Inc. was delivered to Bormaheco, Inc. on or about October2,1973, by Mr. Menandro Umali for purposes of repair;m) That in August 1976, PM Parts notified Mrs. Mauricia Meer about itsownership and the assignment of Mr. Petronilo Roque as caretaker of thesubject property;n) That plaintiff and other heirs are harvest fruits of the property (daranghita)which is worth no less than Pl,000.00 per harvest.As between plaintiffs anddefendant Bormaheco, Inco) That on 25 November 1970, at Makati, Rizal, Same Rivera, in representationof the Slobec Realty & Development Corporation executed in favor ofBormaheco, Inc., represented by its Vice-President Modesto N. Cervantes aChattel Mortgage concerning one unit model CAT D7 Caterpillar CrawlerTractor as described therein as security for the payment in favor of themortgagee of the amount of P180,000.00 (per Exhibit K) that Id document wassuperseded by another chattel mortgage dated January 23, 1971 (Exhibit 15);p) On 18 December 1970, at Makati, Rizal, the Bormaheco, Inc., representedby its Vice-President Modesto Cervantes and Slobec Realty Corporationrepresented by Santiago Rivera executed the sales agreement concerning thesale of one (1) unit Model CAT D7 Caterpillar Crawler Tractor as describedtherein for the amount of P230,000.00 (per Exhibit J) which document wassuperseded by the Sales Agreement dated January 23,1971 (Exhibit 16);q) Although it appears on the document entitled Chattel Mortgage (per ExhibitK) that it was executed on 25 November 1970, and in the document entitledSales Agreement (per Exhibit J) that it was executed on 18 December 1970, itappears in the notarial register of the notary public who notarized them thatthose two documents were executed on 11 December 1970. The certifiedxerox copy of the notarial register of Notary Public Guillermo Aragones issuedby the Bureau of Records Management is hereto submitted as Exhibit BB Thatsaid chattel mortgage was superseded by another document dated January23, 1971;r) That on 23 January 1971, Slobec Realty Development Corporation,represented by Santiago Rivera, received from Bormaheco, Inc. one (1) tractorCaterpillar Model D-7 pursuant to Invoice No. 33234 (Exhibits 9 and 9-A,Bormaheco, Inc.) and delivery receipt No. 10368 (per Exhibits 10 and 10-A forBormaheco, Incs) That on 28 September 1973, Atty. Martin M. de Guzman, as counsel ofInsurance Corporation of the Philippines purchased at public auction for saidcorporation the four (4) parcels of land subject of tills case (per Exhibit L), andwhich document was presented to the Register of Deeds on 1 October 1973;t) Although it appears that the realties in issue has (sic) been sold byInsurance Corporation of the Philippines in favor of PM Parts on 1 0 April 1975,Modesto N. Cervantes, formerly Vice- President and now President ofBormaheco, Inc., sent his letter dated 9 August 1976 to Mauricia Meer Vda. deCastillo (Exhibit V), demanding that she and her children should vacate thepremises;
u) That the Caterpillar Crawler Tractor Model CAT D-7 which was received bySlobec Realty Development Corporation was actually reconditioned andrepainted. " 2We cull the following antecedents from the decision of respondent Court of Appeals:Plaintiff Santiago Rivera is the nephew of plaintiff Mauricia Meer Vda. de Castillo. The Castillofamily are the owners of a parcel of land located in Lucena City which was given as securityfor a loan from the Development Bank of the Philippines. For their failure to pay theamortization, foreclosure of the said property was about to be initiated. This problem wasmade known to Santiago Rivera, who proposed to them the conversion into subdivision ofthe four (4) parcels of land adjacent to the mortgaged property to raise the necessary fund.The Idea was accepted by the Castillo family and to carry out the project, a Memorandum ofAgreement (Exh. U p. 127, Record) was executed by and between Slobec Realty andDevelopment, Inc., represented by its President Santiago Rivera and the Castillo family. Inthis agreement, Santiago Rivera obliged himself to pay the Castillo family the sum ofP70,000.00 immediately after the execution of the agreement and to pay the additionalamount of P400,000.00 after the property has been converted into a subdivision. Rivera,armed with the agreement, Exhibit U , approached Mr. Modesto Cervantes, President ofdefendant Bormaheco, and proposed to purchase from Bormaheco two (2) tractors Model D7 and D-8 Subsequently, a Sales Agreement was executed on December 28,1970 (Exh. J, p.22, Record).On January 23, 1971, Bormaheco, Inc. and Slobec Realty and Development, Inc., representedby its President, Santiago Rivera, executed a Sales Agreement over one unit of CaterpillarTractor D-7 with Serial No. 281114, as evidenced by the contract marked Exhibit '16'. Asshown by the contract, the price was P230,000.00 of which P50,000.00 was to constitute adown payment, and the balance of P180,000.00 payable in eighteen monthly installments.On the same date, Slobec, through Rivera, executed in favor of Bormaheco a ChattelMortgage (Exh. K, p. 29, Record) over the said equipment as security for the payment of theaforesaid balance of P180,000.00. As further security of the aforementioned unpaid balance,Slobec obtained from Insurance Corporation of the Phil. a Surety Bond, with ICP (InsuranceCorporation of the Phil.) as surety and Slobec as principal, in favor of Bormaheco, as borneout by Exhibit '8' (p. 111, Record). The aforesaid surety bond was in turn secured by anAgreement of Counter-Guaranty with Real Estate Mortgage (Exhibit I, p. 24, Record)executed by Rivera as president of Slobec and Mauricia Meer Vda. de Castillo, BuenaflorCastillo Umali, Bertilla Castillo-Rada, Victoria Castillo, Marietta Castillo and Leovina CastilloJalbuena, as mortgagors and Insurance Corporation of the Philippines (ICP) as mortgagee. Inthis agreement, ICP guaranteed the obligation of Slobec with Bormaheco in the amount ofP180,000.00. In giving the bond, ICP required that the Castillos mortgage to them theproperties in question, namely, four parcels of land covered by TCTs in the name of theaforementioned mortgagors, namely TCT Nos. 13114, 13115, 13116 and 13117 all of theRegister of Deeds for Lucena City.On the occasion of the execution on January 23, 1971, of the Sales Agreement Exhibit '16',Slobec, represented by Rivera received from Bormaheco the subject matter of the said SalesAgreement, namely, the aforementioned tractor Caterpillar Model D-7 as evidenced byInvoice No. 33234 (Exhs. 9 and 9-A, p. 112, Record) and Delivery Receipt No. 10368 (Exhs.10 and 10-A, p. 113). This tractor was known by Rivera to be a reconditioned and repaintedone [Stipulation of Facts, Pre-trial Order, par. (u)].Meanwhile, for violation of the terms and conditions of the Counter-Guaranty Agreement(Exh. 1), the properties of the Castillos were foreclosed by ICP As the highest bidder with abid of P285,212.00, a Certificate of Sale was issued by the Provincial Sheriff of Lucena Cityand Transfer Certificates of Title over the subject parcels of land were issued by the Registerof Deeds of Lucena City in favor of ICP namely, TCT Nos. T-23705, T 23706, T-23707 and T23708 (Exhs. M to P, pp. 38-45). The mortgagors had one (1) year from the date of theregistration of the certificate of sale, that is, until October 1, 1974, to redeem the property,but they failed to do so. Consequently, ICP consolidated its ownership over the subjectparcels of land through the requisite affidavit of consolidation of ownership dated October
29, 1974, as shown in Exh. '22'(p. 138, Rec.). Pursuant thereto, a Deed of Sale of Real Estatecovering the subject properties was issued in favor of ICP (Exh. 23, p. 139, Rec.).On April 10, 1975, Insurance Corporation of the Phil. ICP sold to Phil. Machinery PartsManufacturing Co. (PM Parts) the four (4) parcels of land and by virtue of said conveyance,PM Parts transferred unto itself the titles over the lots in dispute so that said parcels of landare now covered by TCT Nos. T-24846, T-24847, T-24848 and T-24849 (Exhs. Q-T, pp. 46-49,Rec.).Thereafter, PM Parts, through its President, Mr. Modesto Cervantes, sent a letter datedAugust 9,1976 addressed to plaintiff Mrs. Mauricia Meer Castillo requesting her and herchildren to vacate the subject property, who (Mrs. Castillo) in turn sent her reply expressingher refusal to comply with his demands.On September 29, 1976, the heirs of the late Felipe Castillo, particularly plaintiff BuenaflorM. Castillo Umali as the appointed administratrix of the properties in question filed an actionfor annulment of title before the then Court of First Instance of Quezon and docketed thereatas Civil Case No. 8085. Thereafter, they filed an Amended Complaint on January 10, 1980 (p.444, Record). On July 20, 1983, plaintiffs filed their Second Amended Complaint, impleadingSantiago M. Rivera as a party plaintiff (p. 706, Record). They contended that all theaforementioned transactions starting with the Agreement of Counter-Guaranty with RealEstate Mortgage (Exh. I), Certificate of Sale (Exh. L) and the Deeds of Authority to Sell, Saleand the Affidavit of Consolidation of Ownership (Annexes F, G, H, I) as well as the Deed ofSale (Annexes J, K, L and M) are void for being entered into in fraud and without the consentand approval of the Court of First Instance of Quezon, (Branch IX) before whom theadministration proceedings has been pending. Plaintiffs pray that the four (4) parcels of landsubject hereof be declared as owned by the estate of the late Felipe Castillo and that allTransfer Certificates of Title Nos. 13114,13115,13116,13117, 23705, 23706, 23707, 23708,24846, 24847, 24848 and 24849 as well as those appearing as encumbrances at the back ofthe certificates of title mentioned be declared as a nullity and defendants to pay damagesand attorney's fees (pp. 71071 1, Record).In their amended answer, the defendants controverted the complaint and alleged, by way ofaffirmative and special defenses that the complaint did not state facts sufficient to state acause of action against defendants; that plaintiffs are not entitled to the reliefs demanded;that plaintiffs are estopped or precluded from asserting the matters set forth in theComplaint; that plaintiffs are guilty of laches in not asserting their alleged right in due time;that defendant PM Parts is an innocent purchaser for value and relied on the face of the titlebefore it bought the subject property (p. 744, Record). 3After trial, the court a quo rendered judgment, with the following decretal portion:WHEREFORE, judgment is hereby rendered in favor of the plaintiffs and against thedefendants, declaring the following documents:Agreement of Counter-Guaranty with Chattel-Real Estate Mortgage datedOctober 24,1970 (Exhibit 1);Sales Agreement dated December 28, 1970 (Exhibit J)Chattel Mortgage dated November 25, 1970 (Exhibit K)Sales Agreement dated January 23, 1971 (Exhibit 16);Chattel Mortgage dated January 23, 1971 (Exhibit 17);Certificate of Sale dated September 28, 1973 executed by the ProvincialSheriff of Quezon in favor of Insurance Corporation of the Philippines (ExhibitL);
null and void for being fictitious, spurious and without consideration. Consequently, TransferCertificates of Title Nos. T 23705, T-23706, T23707 and T-23708 (Exhibits M, N, O and P)issued in the name of Insurance Corporation of the Philippines, are likewise null and void.The sale by Insurance Corporation of the- Philippines in favor of defendant PhilippineMachinery Parts Manufacturing Co., Inc., over Id four (4) parcels of land and TransferCertificates of Title Nos. T 24846, T-24847, T-24848 and T-24849 subsequently issued byvirtue of said sale in the name of Philippine Machinery Parts Manufacturing Co., Inc., aresimilarly declared null and void, and the Register of Deeds of Lucena City is hereby directedto issue, in lieu thereof, transfer certificates of title in the names of the plaintiffs, exceptSantiago Rivera.Orders the defendants jointly and severally to pay the plaintiffs moral damages in the sumof P10,000.00, exemplary damages in the amount of P5,000.00, and actual litigationexpenses in the sum of P6,500.00.Defendants are likewise ordered to pay the plaintiffs, jointly and severally, the sum ofP10,000.00 for and as attomey's fees. With costs against the defendants.SO ORDERED.
As earlier stated, respondent court reversed the aforequoted decision of the trial court and rendered thejudgment subject of this petitionPetitioners contend that respondent Court of Appeals erred:1. In holding and finding that the actions entered into between petitioner Rivera withCervantes are all fair and regular and therefore binding between the parties thereto;2. In reversing the decision of the lower court, not only based on erroneous conclusions offacts, erroneous presumptions not supported by the evidence on record but also, holdingvalid and binding the supposed payment by ICP of its obligation to Bormaheco, despite thefact that the surety bond issued it had already expired when it opted to forecloseextrajudically the mortgage executed by the petitioners;3. In aside the finding of the lower court that there was necessity to pierce the veil ofcorporate existence; and4. In reversing the decision of the lower court of affirming the same
I. Petitioners aver that the transactions entered into between Santiago M. Rivera, as President of SlobecRealty and Development Company (Slobec) and Mode Cervantes, as Vice-President of Bormaheco, such asthe Sales Agreement, 6 Chattel Mortgage 7 and the Agreement of Counter-Guaranty with Chattel/RealEstate Mortgage, 8 are all fraudulent and simulated and should, therefore, be declared nun and void. Suchallegation is premised primarily on the fact that contrary to the stipulations agreed upon in the SalesAgreement (Exhibit J), Rivera never made any advance payment, in the alleged amount of P50,000.00, toBormaheco; that the tractor was received by Rivera only on January 23, 1971 and not in 1970 as stated inthe Chattel Mortgage (Exhibit K); and that when the Agreement of Counter-Guaranty with Chattel/RealEstate Mortgage was executed on October 24, 1970, to secure the obligation of ICP under its surety bond,the Sales Agreement and Chattel Mortgage had not as yet been executed, aside from the fact that it wasBormaheco, and not Rivera, which paid the premium for the surety bond issued by ICPAt the outset, it will be noted that petitioners submission under the first assigned error hinges purely onquestions of fact. Respondent Court of Appeals made several findings to the effect that the questioneddocuments are valid and binding upon the parties, that there was no fraud employed by privaterespondents in the execution thereof, and that, contrary to petitioners' allegation, the evidence on recordreveals that petitioners had every intention to be bound by their undertakings in the various transactionshad with private respondents. It is a general rule in this jurisdiction that findings of fact of said appellatecourt are final and conclusive and, thus, binding on this Court in the absence of sufficient and convincing
proof, inter alia, that the former acted with grave abuse of discretion. Under the circumstances, we find nocompelling reason to deviate from this long-standing jurisprudential pronouncement.In addition, the alleged failure of Rivera to pay the consideration agreed upon in the Sales Agreement,which clearly constitutes a breach of the contract, cannot be availed of by the guilty party to justify andsupport an action for the declaration of nullity of the contract. Equity and fair play dictates that one whocommits a breach of his contract may not seek refuge under the protective mantle of the law.The evidence of record, on an overall calibration, does not convince us of the validity of petitioners'contention that the contracts entered into by the parties are either absolutely simulated or downrightfraudulent.There is absolute simulation, which renders the contract null and void, when the parties do not intend tobe bound at all by the same. 9 The basic characteristic of this type of simulation of contract is the fact thatthe apparent contract is not really desired or intended to either produce legal effects or in any way alterthe juridical situation of the parties. The subsequent act of Rivera in receiving and making use of thetractor subject matter of the Sales Agreement and Chattel Mortgage, and the simultaneous issuance of asurety bond in favor of Bormaheco, concomitant with the execution of the Agreement of Counter-Guarantywith Chattel/Real Estate Mortgage, conduce to the conclusion that petitioners had every intention to bebound by these contracts. The occurrence of these series of transactions between petitioners and privaterespondents is a strong indication that the parties actually intended, or at least expected, to exactfulfillment of their respective obligations from one another.Neither will an allegation of fraud prosper in this case where petitioners failed to show that they wereinduced to enter into a contract through the insidious words and machinations of private respondentswithout which the former would not have executed such contract. To set aside a document solemnlyexecuted and voluntarily delivered, the proof of fraud must be clear and convincing. 10 We are notpersuaded that such quantum of proof exists in the case at bar.The fact that it was Bormaheco which paid the premium for the surety bond issued by ICP does not perse affect the validity of the bond. Petitioners themselves admit in their present petition that Riveraexecuted a Deed of Sale with Right of Repurchase of his car in favor of Bormaheco and agreed that a partof the proceeds thereof shall be used to pay the premium for the bond. 11 In effect, Bormaheco acceptedthe payment of the premium as an agent of ICP The execution of the deed of sale with a right ofrepurchase in favor of Bormaheco under such circumstances sufficiently establishes the fact that Riverarecognized Bormaheco as an agent of ICP Such payment to the agent of ICP is, therefore, binding onRivera. He is now estopped from questioning the validity of the suretyship contract.II.,liability will attach directly to the officers and stockholders. 12 The doctrine applies when the corporatefiction is used to defeat public convenience, justify wrong, protect fraud, or defend crime, 13 or when it ismade as a shield to confuse the legitimate issues 14 or where a corporation is the mere alter ego orbusiness conduit of a person, or where the corporation is so organized and controlled and its affairs are soconducted as to make it merely an instrumentality, agency, conduit or adjunct of another corporation. 15In the case at bar, petitioners seek to pierce the V621 Of corporate entity of Bormaheco, ICP and PM Parts,alleging that these corporations employed fraud in causing the foreclosure and subsequent sale of the realproperties belonging to petitioners While we do not discount the possibility of the existence of fraud in theforeclosure proceeding, neither are we inclined to apply the doctrine invoked by petitioners in granting therelief sought. It is our considered opinion that piercing the veil of corporate entity is not the proper remedyin order that the foreclosure proceeding may be declared a nullity under the circumstances obtaining in thelegal case at bar.In the first place, the legal corporate entity is disregarded only if it is sought to hold the officers andstockholders directly liable for a corporate debt or obligation. In the instant case, petitioners do not seek toimpose a claim against the individual members of the three corporations involved; on the contrary, it isthese corporations which desire to enforce an alleged right against petitioners. Assuming that petitioners
were indeed defrauded by private respondents in the foreclosure of the mortgaged properties, this factalone is not, under the circumstances, sufficient to justify the piercing of the corporate fiction, sincepetitioners do not intend to hold the officers and/or members of respondent corporations personally liabletherefor. Petitioners are merely seeking the declaration of the nullity of the foreclosure sale, which reliefmay be obtained without having to disregard the aforesaid corporate fiction attaching to respondentcorporations. Secondly, petitioners failed to establish by clear and convincing evidence that privaterespondents were purposely formed and operated, and thereafter transacted with petitioners, with the soleintention of defrauding the latter.The mere fact, therefore, that the businesses of two or more corporations are interrelated is not ajustification for disregarding their separate personalities, 16 absent sufficient showing that the corporateentity was purposely used as a shield to defraud creditors and third persons of their rights.III. The main issue for resolution is whether there was a valid foreclosure of the mortgaged properties byICP Petitioners argue that the foreclosure proceedings should be declared null and void for two reasons,viz.: (1) no written notice was furnished by Bormaheco to ICP anent the failure of Slobec in paying itsobligation with the former, plus the fact that no receipt was presented to show the amount allegedly paidby ICP to Bormaheco; and (b) at the time of the foreclosure of the mortgage, the liability of ICP under thesurety bond had already expired.Respondent court, in finding for the validity of the foreclosure sale, declared:Now to the question of whether or not the foreclosure by the ICP of the real estate mortgagewas in the exercise of a legal right, We agree with the appellants that the foreclosureproceedings instituted by the ICP was in the exercise of a legal right. First, ICP has in itsfavor the legal presumption that it had indemnified Bormaheco by reason of Slobec's defaultin the payment of its obligation under the Sales Agreement, especially because Bormahecoconsented to ICPs foreclosure of the mortgage. This presumption is in consonance with pars.R and Q Section 5, Rule 5, * New Rules of Court which provides that it is disputablypresumed that private transactions have been fair and regular. likewise, it is disputablypresumed that the ordinary course of business has been followed: Second, ICP had the rightto proceed at once to the foreclosure of the mortgage as mandated by the provisions of Art.2071 Civil Code for these further reasons: Slobec, the principal debtor, was admittedlyinsolvent; Slobec's obligation becomes demandable by reason of the expiration of the periodof payment; and its authorization to foreclose the mortgage upon Slobec's default, whichresulted in the accrual of ICPS liability to Bormaheco. Third, the Agreement of CounterGuaranty with Real Estate Mortgage (Exh. 1) expressly grants to ICP the right to foreclosethe real estate mortgage in the event of 'non-payment or non-liquidation of the entireindebtedness or fraction thereof upon maturity as stipulated in the contract'. This is a validand binding stipulation in the absence of showing that it is contrary to law, morals, goodcustoms, public order or public policy. (Art. 1306, New Civil Code). 171. Petitioners asseverate that there was no notice of default issued by Bormaheco to ICP which would haveentitled Bormaheco to demand payment from ICP under the suretyship contract.Surety Bond No. B-1401 0 which was issued by ICP in favor of Bormaheco, wherein ICP and Slobecundertook to guarantee the payment of the balance of P180,000.00 payable in eighteen (18) monthlyinstallments on one unit of Model CAT D-7 Caterpillar Crawler Tractor, pertinently provides in part asfollows:1. The liability of INSURANCE CORPORATION OF THE PHILIPPINES, under this BOND will expireTwelve (I 2) months from date hereof. Furthermore, it is hereby agreed and understood thatthe INSURANCE CORPORATION OF THE PHILIPPINES will not be liable for any claim notpresented in writing to the Corporation within THIRTY (30) DAYS from the expiration of thisBOND, and that the obligee hereby waives his right to bring claim or file any action againstSurety and after the termination of one (1) year from the time his cause of action accrues. 18The surety bond was dated October 24, 1970. However, an annotation on the upper part thereofstates: "NOTE: EFFECTIVITY DATE OF THIS BOND SHALL BE ON JANUARY 22, 1971." 19
On the other hand, the Sales Agreement dated January 23, 1971 provides that the balance of P180,000.00shall be payable in eighteen (18) monthly installments. 20 The Promissory Note executed by Slobec on evendate in favor of Bormaheco further provides that the obligation shall be payable on or before February 23,1971 up to July 23, 1972, and that non-payment of any of the installments when due shall make the entireobligation immediately due and demandable. 21It is basic that liability on a bond is contractual in nature and is ordinarily restricted to the obligationexpressly assumed therein. We have repeatedly held that the extent of a surety's liability is determinedonly by the clause of the contract of suretyship as well as the conditions stated in the bond. It cannot beextended by implication beyond the terms the contract. 22Fundamental likewise is the rule that, except where required by the provisions of the contract, a demand ornotice of default is not required to fix the surety's liability. 23 Hence, where the contract of suretyshipstipulates that notice of the principal's default be given to the surety, generally the failure to comply withthe condition will prevent recovery from the surety. There are certain instances, however, when failure tocomply with the condition will not extinguish the surety's liability, such as a failure to give notice of slightdefaults, which are waived by the obligee; or on mere suspicion of possible default; or where, if a defaultexists, there is excuse or provision in the suretyship contract exempting the surety for liability therefor, orwhere the surety already has knowledge or is chargeable with knowledge of the default. 24In the case at bar, the suretyship contract expressly provides that ICP shag not be liable for any claim notfiled in writing within thirty (30) days from the expiration of the bond. In its decision dated May 25 1987,the court a quocategorically stated that '(n)o evidence was presented to show that Bormaheco demandedpayment from ICP nor was there any action taken by Bormaheco on the bond posted by ICP to guaranteethe payment of plaintiffs obligation. There is nothing in the records of the proceedings to show that ICPindemnified Bormaheco for the failure of the plaintiffs to pay their obligation. " 25 The failure, therefore, ofBormaheco to notify ICP in writing about Slobec's supposed default released ICP from liability under itssurety bond. Consequently, ICP could not validly foreclose that real estate mortgage executed bypetitioners in its favor since it never incurred any liability under the surety bond. It cannot claim exemptionfrom the required written notice since its case does not fall under any of the exceptions hereinbeforeenumerated.Furthermore, the allegation of ICP that it has paid Bormaheco is not supported by any documentaryevidence. Section 1, Rule 131 of the Rules of Court provides that the burden of evidence lies with the partywho asserts an affirmative allegation. Since ICP failed to duly prove the fact of payment, the disputablepresumption that private transactions have been fair and regular, as erroneously relied upon byrespondent Court of Appeals, finds no application to the case at bar.2. The liability of a surety is measured by the terms of his contract, and, while he is liable to the full extentthereof, such liability is strictly limited to that assumed by its terms. 26 While ordinarily the termination of asurety's liability is governed by the provisions of the contract of suretyship, where the obligation of asurety is, under the terms of the bond, to terminate at a specified time, his obligation cannot be enlargedby an unauthorized extension thereof. 27 This is an exception to the general rule that the obligation of thesurety continues for the same period as that of the principal debtor. 28It is possible that the period of suretyship may be shorter than that of the principal obligation, as wherethe principal debtor is required to make payment by installments. 29 In the case at bar, the surety bondissued by ICP was to expire on January 22, 1972, twelve (1 2) months from its effectivity date, whereasSlobec's installment payment was to end on July 23, 1972. Therefore, while ICP guaranteed the paymentby Slobec of the balance of P180,000.00, such guaranty was valid only for and within twelve (1 2) monthsfrom the date of effectivity of the surety bond, or until January 22, 1972. Thereafter, from January 23, 1972up to July 23, 1972, the liability of Slobec became an unsecured obligation. The default of Slobec duringthis period cannot be a valid basis for the exercise of the right to foreclose by ICP since its surety contracthad already been terminated. Besides, the liability of ICP was extinguished when Bormaheco failed to file awritten claim against it within thirty (30) days from the expiration of the surety bond. Consequently, theforeclosure of the mortgage, after the expiration of the surety bond under which ICP as surety has notincurred any liability, should be declared null and void.
3. Lastly, it has been held that where The guarantor holds property of the principal as collateral surety forhis personal indemnity, to which he may resort only after payment by himself, until he has paid somethingas such guarantor neither he nor the creditor can resort to such collaterals. 30The Agreement of Counter-Guaranty with Chattel/Real Estate Mortgage states that it is being issued forand in consideration of the obligations assumed by the Mortgagee-Surety Company under the terms andconditions of ICP Bond No. 14010 in behalf of Slobec Realty Development Corporation and in favor ofBormaheco, Inc. 31 There is no doubt that said Agreement of Counter-Guaranty is issued for the personalindemnity of ICP Considering that the fact of payment by ICP has never been established, it follows,pursuant to the doctrine above adverted to, that ICP cannot foreclose on the subject properties,IV. Private respondent PM Parts posits that it is a buyer in good faith and, therefore, it acquired a valid titleover the subject properties. The submission is without merit and the conclusion is speciousWe have stated earlier that the doctrine of piercing the veil of corporate fiction is not applicable in thiscase. However, its inapplicability has no bearing on the good faith or bad faith of private respondent PMParts. It must be noted that Modesto N. Cervantes served as Vice-President of Bormaheco and, later, asPresident of PM Parts. On this fact alone, it cannot be said that PM Parts had no knowledge of the aforesaidseveral transactions executed between Bormaheco and petitioners. In addition, Atty. Martin de Guzman,who is the Executive Vice-President of Bormaheco, was also the legal counsel of ICP and PM Parts. Thesefacts were admitted without qualification in the stipulation of facts submitted by the parties before the trialcourt. Hence, the defense of good faith may not be resorted to by private respondent PM Parts which ischarged with knowledge of the true relations existing between Bormaheco, ICP and herein petitioners.Accordingly, the transfer certificates of title issued in its name, as well as the certificate of sale, must bedeclared null and void since they cannot be considered altogether free of the taint of bad faith.WHEREFORE, the decision of respondent Court of Appeals is hereby REVERSED and SET ASIDE, andjudgment is hereby rendered declaring the following as null and void: (1) Certificate of Sale, datedSeptember 28,1973, executed by the Provincial Sheriff of Quezon in favor of the Insurance Corporation ofthe Philippines; (2) Transfer Certificates of Title Nos. T-23705, T-23706, T-23707 and T-23708 issued in thename of the Insurance Corporation of the Philippines; (3) the sale by Insurance Corporation of thePhilippines in favor of Philippine Machinery Parts Manufacturing Co., Inc. of the four (4) parcels of landcovered by the aforesaid certificates of title; and (4) Transfer Certificates of Title Nos. T-24846, T-24847, T24848 and T24849 subsequently issued by virtue of said sale in the name of the latter corporation.The Register of Deeds of Lucena City is hereby directed to cancel Transfer Certificates of Title Nos. T24846, T-24847, T24848 and T-24849 in the name of Philippine Machinery Parts Manufacturing Co., Inc.and to issue in lieu thereof the corresponding transfer certificates of title in the name of herein petitioners,except Santiago Rivera.The foregoing dispositions are without prejudice to such other and proper legal remedies as may beavailable to respondent Bormaheco, Inc. against herein petitioners.SO ORDERED.Melencio-Herrera (Chairman), Paras and Padilla, JJ., concur.Sarmiento, J., is on leave.
assessed deficiency sales tax due from petitioner for the four quarters of 1950; the respondents' lastdemand was in the total sum of P2,215,809.27 detailed as follows:
75%Deficiency SurchargSales Taxe
TotalAmountDue
Assessment(First) ofNovember 7,1950 fordeficiencysales Tax forthe period from3rd Qrtr 1947to 4th QrtrP1,031,296 P773,473. P1,804,7691949 inclusive.6045.05
AdditionalAssessment forperiod from 1stto 4th Qrtr176,160.1950, inclusive 234,880.1309 411,040.22
Total amountdemanded perletter ofDecember 16, P1,266,176 P949,632. P2,215,8091954.7354.27
This second assessment was contested by the petitioner Yutivo before the Court of Tax Appeals, allegingthat there is no valid ground to disregard the corporate personality of SM and to hold that it is an adjunctof petitioner Yutivo; (2) that assuming the separate personality of SM may be disregarded, the sales taxalready paid by Yutivo should first be deducted from the selling price of SM in computing the sales tax dueon each vehicle; and (3) that the surcharge has been erroneously imposed by respondent. Finding againstYutivo and sustaining the respondent Collector's theory that there was no legitimate or bona fide purposein the organization of SM the apparent objective of its organization being to evade the payment of taxes and that it was owned (or the majority of the stocks thereof are owned) and controlled by Yutivo and is amere subsidiary, branch, adjunct, conduit, instrumentality or alter ego of the latter, the Court of TaxAppeals with Judge Roman Umali not taking part disregarded its separate corporate existence and onApril 27, 1957, rendered the decision now complained of. Of the two Judges who signed the decision, onevoted for the modification of the computation of the sales tax as determined by the respondent Collector inhis decision so as to give allowance for the reduction of the tax already paid (resulting in the reduction ofthe assessment to P820,509.91 exclusive of surcharges), while the other voted for affirmance. Thedispositive part of the decision, however, affirmed the assessment made by the Collector. Reconsiderationof this decision having been denied, Yutivo brought the case to this Court thru the present petition forreview.It is an elementary and fundamental principle of corporation law that a corporation is an entity separateand distinct from its stockholders and from other corporation petitions to which it may be connected.However, "when the notion of legal entity is used to defeat public convenience, justify wrong, protectfraud, or defend crime," the law will regard the corporation as an association of persons, or in the case oftwo corporations merge them into one. (Koppel [Phil.], Inc. vs. Yatco, 77 Phil. 496, citing I Fletcher
Cyclopedia of Corporation, Perm Ed., pp. 135 136; United States vs. Milwaukee Refrigeration Transit Co.,142 Fed., 247, 255 per Sanborn, J.) Another rule is that, when the corporation is the "mere alter ego orbusiness conduit of a person, it may be disregarded." (Koppel [Phil.], Inc. vs. Yatco, supra.)After going over the voluminous record of the present case, we are inclined to rule that the Court of TaxAppeals was not justified in finding that SM was organized for no other purpose than to defraud theGovernment of its lawful revenues. In the first place, this corporation was organized in June, 1946 when itcould not have caused Yutivo any tax savings. From that date up to June 30, 1947, or a period of more thanone year, GM was the importer of the cars and trucks sold to Yutivo, which, in turn resold them to SM.During that period, it is not disputed that GM as importer, was the one solely liable for sales taxes. NeitherYutivo or SM was subject to the sales taxes on their sales of cars and trucks. The sales tax liability of Yutivodid not arise until July 1, 1947 when it became the importer and simply continued its practice of selling toSM. The decision, therefore, of the Tax Court that SM was organized purposely as a tax evasion device runscounter to the fact that there was no tax to evade.Making the observation from a newspaper clipping (Exh. "T") that "as early as 1945 it was known that GMwas preparing to leave the Philippines and terminate its business of importing vehicles," the court belowspeculated that Yutivo anticipated the withdrawal of GM from business in the Philippines in June, 1947. Thisobservation, which was made only in the resolution on the motion for reconsideration, however, finds nobasis in the record. On the other hand, GM had been an importer of cars in the Philippines even before thewar and had but recently resumed its operation in the Philippines in 1946 under an ambitious plan toexpand its operation by establishing an assembly plant here, so that it could not have been expected tomake so drastic a turnabout of not merely abandoning the assembly plant project but also totally ceasingto do business as an importer. Moreover, the newspaper clipping, Exh. "T", was published on March 24,1947, and clipping, merely reported a rumored plan that GM would abandon the assembly plant project inthe Philippines. There was no mention of the cessation of business by GM which must not be confused withthe abandonment of the assembly plant project. Even as respect the assembly plant, the newspaperclipping was quite explicit in saying that the Acting Manager refused to confirm that rumor as late as March24, 1947, almost a year after SM was organized.At this juncture, it should be stated that the intention to minimize taxes, when used in the context of fraud,must be proved to exist by clear and convincing evidence amounting to more than mere preponderance,and cannot be justified by a mere speculation. This is because fraud is never lightly to be presumed. (Vitelli& Sons vs. U.S 250 U.S. 355; Duffin vs. Lucas, 55 F (2d) 786; Budd vs. Commr., 43 F (2d) 509; MarylandCasualty Co. vs. Palmette Coal Co., 40 F (2d) 374; Schoonfield Bros., Inc. vs. Commr., 38 BTA 943; CharlesHeiss vs. Commr 36 BTA 833; Kerbaugh vs. Commr 74 F (2d) 749; Maddas vs. Commr., 114 F. (2d) 548;Moore vs. Commr., 37 BTA 378; National City Bank of New York vs. Commr., 98 (2d) 93; Richard vs.Commr., 15 BTA 316; Rea Gane vs. Commr., 19 BTA 518). (See also Balter, Fraud Under Federal Law, pp.301-302, citing numerous authorities: Arroyo vs. Granada, et al., 18 Phil. 484.) Fraud is never imputed andthe courts never sustain findings of fraud upon circumstances which, at the most, create only suspicion.(Haygood Lumber & Mining Co. vs. Commr., 178 F (2d) 769; Dalone vs. Commr., 100 F (2d) 507).In the second place, SM was organized and it operated, under circumstance that belied any intention toevade sales taxes. "Tax evasion" is a term that connotes fraud thru the use of pretenses and forbiddendevices to lessen or defeat taxes. The transactions between Yutivo and SM, however, have always been inthe open, embodied in private and public documents, constantly subject to inspection by the taxauthorities. As a matter of fact, after Yutivo became the importer of GM cars and trucks for Visayas andMindanao, it merely continued the method of distribution that it had initiated long before GM withdrewfrom the Philippines.On the other hand, if tax saving was the only justification for the organization of SM, such justificationcertainly ceased with the passage of Republic Act No. 594 on February 16, 1951, governing payment ofadvance sales tax by the importer based on the landed cost of the imported article, increased by mark-upsof 25%, 50%, and 100%, depending on whether the imported article is taxed under sections 186, 185 and184, respectively, of the Tax Code. Under Republic Act No. 594, the amount at which the article is sold isimmaterial to the amount of the sales tax. And yet after the passage of that Act, SM continued to exist upto the present and operates as it did many years past in the promotion and pursuit of the businesspurposes for which it was organized.
In the third place, sections 184 to 186 of the said Code provides that the sales tax shall be collected "onceonly on every original sale, barter, exchange . . , to be paid by the manufacturer, producer or importer."The use of the word "original" and the express provision that the tax was collectible "once only" evidentlyhas made the provisions susceptible of different interpretations. In this connection, it should be stated thata taxpayer has the legal right to decrease the amount of what otherwise would be his taxes or altogetheravoid them by means which the law permits. (U.S. vs. Isham 17 Wall. 496, 506; Gregory vs. Helvering 293U.S. 465, 469; Commr. vs. Tower, 327 U.S. 280; Lawton vs. Commr 194 F (2d) 380). Any legal means by thetaxpayer to reduce taxes are all right Benry vs. Commr. 25 T. Cl. 78). A man may, therefore, perform an actthat he honestly believes to be sufficient to exempt him from taxes. He does not incur fraud thereby evenif the act is thereafter found to be insufficient. Thus in the case ofCourt Holding Co. vs. Commr. 2 T. Cl.531, it was held that though an incorrect position in law had been taken by the corporation there was nosuppression of the facts, and a fraud penalty was not justified.The evidence for the Collector, in our opinion, falls short of the standard of clear and convincing proof offraud. As a matter of fact, the respondent Collector himself showed a great deal of doubt or hesitancy as tothe existence of fraud. He even doubted the validity of his first assessment dated November 7, 1959. Itmust be remembered that the fraud which respondent Collector imputed to Yutivo must be related to itsfiling of sales tax returns of less taxes than were legally due. The allegation of fraud, however, cannot besustained without the showing that Yutivo, in filing said returns, did so fully knowing that the taxes calledfor therein called for therein were less than what were legally due. Considering that respondent Collectorhimself with the aid of his legal staff, and after some two years of investigation and duty of investigationand study concluded in 1952 that Yutivo's sales tax returns were correct only to reverse himself afteranother two years it would seem harsh and unfair for him to say in 1954 that Yutivo fully knew inOctober 1947 that its sales tax returns were inaccurate.On this point, one other consideration would show that the intent to save taxes could not have existed inthe minds of the organizers of SM. The sales tax imposed, in theory and in practice, is passed on to thevendee, and is usually billed separately as such in the sales invoice. As pointed out by petitioner Yutivo,had not SM handled the retail, the additional tax that would have been payable by it, could have beeneasily passed off to the consumer, especially since the period covered by the assessment was a "seller'smarket" due to the post-war scarcity up to late 1948, and the imposition of controls in the late 1949.It is true that the arrastre charges constitute expenses of Yutivo and its non-inclusion in the selling price byYutivo cost the Government P4.00 per vehicle, but said non-inclusion was explained to have been due toan inadvertent accounting omission, and could hardly be considered as proof of willful channelling andfraudulent evasion of sales tax. Mere understatement of tax in itself does not prove fraud. (JamesNicholson, 32 BTA 377, affirmed 90 F. (2) 978, cited in Merten's Sec. 55.11 p. 21) The amount involved,moreover, is extremely small inducement for Yutivo to go thru all the trouble of organizing SM. Besides, thenon-inclusion of these small arrastre charges in the sales tax returns of Yutivo is clearly shown in therecords of Yutivo, which is uncharacteristic of fraud (See Insular Lumber Co. vs. Collector, G.R. No. L-719,April 28, 1956.)We are, however, inclined to agree with the court below that SM was actually owned and controlled bypetitioner as to make it a mere subsidiary or branch of the latter created for the purpose of selling thevehicles at retail and maintaining stores for spare parts as well as service repair shops. It is not disputedthat the petitioner, which is engaged principally in hardware supplies and equipment, is completelycontrolled by the Yutivo, Young or Yu family. The founders of the corporation are closely related to eachother either by blood or affinity, and most of its stockholders are members of the Yu (Yutivo or Young)family. It is, likewise, admitted that SM was organized by the leading stockholders of Yutivo headed by YuKhe Thai. At the time of its incorporation 2,500 shares worth P250,000.00 appear to have been subscribedin five equal proportions by Yu Khe Thai, Yu Khe Siong, Yu Khe Jin, Yu Eng Poh and Washington Sycip. Thefirst three named subscribers are brothers, being the sons of Yu Tien Yee, one of Yutivo's founders. Yu EngPoh and Washington Sycip are respectively sons of Yu Tiong Sing and Alberto Sycip who are co-founders ofYutivo. According to the Articles of Incorporation of the said subscriptions, the amount of P62,500 was paidby the aforenamed subscribers, but actually the said sum was advanced by Yutivo. The additionalsubscriptions to the capital stock of SM and subsequent transfers thereof were paid by Yutivo itself. Thepayments were made, however, without any transfer of funds from Yutivo to SM. Yutivo simply charged theaccounts of the subscribers for the amount allegedly advanced by Yutivo in payment of the shares.Whether a charge was to be made against the accounts of the subscribers or said subscribers were to
subscribe shares appears to constitute a unilateral act on the part of Yutivo, there being no showing thatthe former initiated the subscription.The transactions were made solely by and between SM and Yutivo. In effect, it was Yutivo who undertookthe subscription of shares, employing the persons named or "charged" with corresponding account asnominal stockholders. Of course, Yu Khe Thai, Yu Khe Jin, Yu Khe Siong and Yu Eng Poh were manifestlyaware of these subscriptions, but considering that they were the principal officers and constituted themajority of the Board of Directors of both Yutivo and SM, their subscriptions could readily or easily be thatof Yutivo's Moreover, these persons were related to death other as brothers or first cousins. There wasevery reason for them to agree in order to protect their common interest in Yutivo and SM.The issued capital stock of SM was increased by additional subscriptions made by various person's butexcept Ng Sam Bak and David Sycip, "payments" thereof were effected by merely debiting 'or charging theaccounts of said stockholders and crediting the corresponding amounts in favor of SM, without actuallytransferring cash from Yutivo. Again, in this instance, the "payments" were Yutivo, by effected by the mereunilateral act of Yutivo a accounts of the virtue of its control over the individual persons charged, wouldnecessarily exercise preferential rights and control directly or indirectly, over the shares, it being the partywhich really undertook to pay or underwrite payment thereof.The shareholders in SM are mere nominal stockholders holding the shares for and in behalf of Yutivo, soeven conceding that the original subscribers were stockholders bona fide Yutivo was at all times in controlof the majority of the stock of SM and that the latter was a mere subsidiary of the former.True, petitioner and other recorded stockholders transferred their shareholdings, but the transfers weremade to their immediate relatives, either to their respective spouses and children or sometimes brothersor sisters. Yutivo's shares in SM were transferred to immediate relatives of persons who constituted itscontrolling stockholders, directors and officers. Despite these purported changes in stock ownership inboth corporations, the Board of Directors and officers of both corporations remained unchanged andMessrs. Yu Khe Thai, Yu Khe Siong Hu Khe Jin and Yu Eng Poll (all of the Yu or Young family) continued toconstitute the majority in both boards. All these, as observed by the Court of Tax Appeals, merely serve tocorroborate the fact that there was a common ownership and interest in the two corporations.SM is under the management and control of Yutivo by virtue of a management contract entered intobetween the two parties. In fact, the controlling majority of the Board of Directors of Yutivo is also thecontrolling majority of the Board of Directors of SM. At the same time the principal officers of bothcorporations are identical. In addition both corporations have a common comptroller in the person ofSimeon Sy, who is a brother-in-law of Yutivo's president, Yu Khe Thai. There is therefore no doubt that byvirtue of such control, the business, financial and management policies of both corporations could bedirected towards common ends.Another aspect relative to Yutivo's control over SM operations relates to its cash transactions. All cashassets of SM were handled by Yutivo and all cash transactions of SM were actually maintained thru Yutivo.Any and all receipts of cash by SM including its branches were transmitted or transferred immediately anddirectly to Yutivo in Manila upon receipt thereof. Likewise, all expenses, purchases or other obligationsincurred by SM are referred to Yutivo which in turn prepares the corresponding disbursement vouchers andpayments in relation there, the payment being made out of the cash deposits of SM with Yutivo, if any, orin the absence thereof which occurs generally, a corresponding charge is made against the account of SMin Yutivo's books. The payments for and charges against SM are made by Yutivo as a matter of course andwithout need of any further request, the latter would advance all such cash requirements for the benefit ofSM. Any and all payments and cash vouchers are made on Yutivo stationery and made under authority ofYutivo's corporate officers, without any copy thereof being furnished to SM. All detailed records such ascash disbursements, such as expenses, purchases, etc. for the account of SM, are kept by Yutivo and SMmerely keeps a summary record thereof on the basis of information received from Yutivo.All the above plainly show that cash or funds of SM, including those of its branches which are directlyremitted to Yutivo, are placed in the custody and control of Yutivo, resources and subject to withdrawalonly by Yutivo. SM's being under Yutivo's control, the former's operations and existence became dependentupon the latter.
Consideration of various other circumstances, especially when taken together, indicates that Yutivo treatedSM merely as its department or adjunct. For one thing, the accounting system maintained by Yutivo showsthat it maintained a high degree of control over SM accounts. All transactions between Yutivo and SM arerecorded and effected by mere debit or credit entries against the reciprocal account maintained in theirrespective books of accounts and indicate the dependency of SM as branch upon Yutivo.Apart from the accounting system, other facts corroborate or independently show that SM is a branch ordepartment of Yutivo. Even the branches of SM in Bacolod, Iloilo, Cebu, and Davao treat Yutivo Manila astheir "Head Office" or "Home Office" as shown by their letters of remittances or other correspondences.These correspondences were actually received by Yutivo and the reference to Yutivo as the head or homeoffice is obvious from the fact that all cash collections of the SM's branches are remitted directly to Yutivo.Added to this fact, is that SM may freely use forms or stationery of YutivoThe fact that SM is a mere department or adjunct of Yutivo is made more patent by the fact that arrastreconveying, and charges paid for the "operation of receiving, loading or unloading" of imported cars andtrucks on piers and wharves, were charged against SM. Overtime charges for the unloading of cars andtrucks as requested by Yutivo and incurred as part of its acquisition cost thereof, were likewise chargedagainst and treated as expenses of SM. If Yutivo were the importer, these arrastre and overtime chargeswere Yutivo's expenses in importing goods and not SM's. But since those charges were made against SM, itplainly appears that Yutivo had sole authority to allocate its expenses even as against SM in the sense thatthe latter is a mere adjunct, branch or department of the former.Proceeding to another aspect of the relation of the parties, the management fees due from SM to Yutivowere taken up as expenses of SM and credited to the account of Yutivo. If it were to be assumed that thetwo organizations are separate juridical entities, the corresponding receipts or receivables should havebeen treated as income on the part of Yutivo. But such management fees were recorded as "Reserve forBonus" and were therefore a liability reserve and not an income account. This reserve for bonus weresubsequently distributed directly to and credited in favor of the employees and directors of Yutivo, therebyclearly showing that the management fees were paid directly to Yutivo officers and employees.Briefly stated, Yutivo financed principally, if not wholly, the business of SM and actually extended all thecredit to the latter not only in the form of starting capital but also in the form of credits extended for thecars and vehicles allegedly sold by Yutivo to SM as well as advances or loans for the expenses of the latterwhen the capital had been exhausted. Thus, the increases in the capital stock were made in advances or"Guarantee" payments by Yutivo and credited in favor of SM. The funds of SM were all merged in the cashfund of Yutivo. At all times Yutivo thru officers and directors common to it and SM, exercised full controlover the cash funds, policies, expenditures and obligations of the latter.Southern Motors being but a mere instrumentality, or adjunct of Yutivo, the Court of Tax Appeals correctlydisregarded the technical defense of separate corporate entity in order to arrive at the true tax liability ofYutivo.Petitioner contends that the respondent Collector had lost his right or authority to issue the disputedassessment by reason of prescription. The contention, in our opinion, cannot be sustained. It will be notedthat the first assessment was made on November 7, 1950 for deficiency sales tax from 1947 to 1949. Thecorresponding returns filed by petitioner covering the said period was made at the earliest on October 1,as regards the third quarter of 1947, so that it cannot be claimed that the assessment was not made withinthe five-year period prescribed in section 331 of the Tax Code invoked by petitioner. The assessment, it isadmitted, was withdrawn by the Collector on insufficiency of evidence, but November 15, 1952 due toinsufficiency of evidence, but the withdrawal was made subject to the approval of the Secretary of Financeand the Board of Tax Appeals, pursuant to the provisions of section 9 of Executive Order No. 401-A, seriesof 1951. The decision of the previous assessment of November 7, Collector countermanding the as 1950was forwarded to the Board of Tax Appeals through the Secretary of Finance but that official, apparentlydisagreeing with the decision, sent it back for re-investigation. Consequently, the assessment of November7, 1950 cannot be considered to have been finally withdrawn. That the assessment was subsequentlyreiterated in the decision of respondent Collector on December 16, 1954 did not alter the fact that it wasmade seasonably. In this connection, it would appear that a warrant of distraint and levy had been issuedon March 28, 1951 in relation with this case and by virtue thereof the properties of Yutivo were placedunder constructive distraint. Said warrant and constructive distraint have not been lifted up to the present,which shows that the assessment of November 7, 1950 has always been valid and subsisting.
Anent the deficiency sale tax for 1950, considering that the assessment thereof was made on December16, 1954, the same was assessed well within the prescribed five-year period.Petitioner argues that the original assessment of November 7, 1950 did not extend the prescriptive periodon assessment. The argument is untenable, for, as already seen, the assessment was never finallywithdrawn, since it was not approved by the Secretary of Finance or of the Board of Tax Appeals. Theauthority of the Secretary to act upon the assessment cannot be questioned, for he is expressly grantedsuch authority under section 9 of Executive Order No. 401-And under section 79 (c) of the RevisedAdministrative Code, he has "direct control, direction and supervision over all bureaus and offices under hisjurisdiction and may, any provision of existing law to the contrary not withstanding, repeal or modify thedecision of the chief of said Bureaus or offices when advisable in public interest."It should here also be stated that the assessment in question was consistently protested by petitioner,making several requests for reinvestigation thereof. Under the circumstances, petitioner may beconsidered to have waived the defense of prescription."Estoppel has been employed to prevent the application of the statute of limitations against thegovernment in certain instances in which the taxpayer has taken some affirmative action to preventthe collection of the tax within the statutory period. It is generally held that a taxpayer is estoppedto repudiate waivers of the statute of limitations upon which the government relied. The casesfrequently involve dissolved corporations. If no waiver has been given, the cases usually show comeconduct directed to a postponement of collection, such, for example, as some variety of request toapply an overassessment. The taxpayer has 'benefited' and 'is not in a position to contest' his taxliability. A definite representation of implied authority may be involved, and in many cases thetaxpayer has received the 'benefit' of being saved from the inconvenience, if not hardship ofimmediate collection. "Conceivably even in these cases a fully informed Commissioner may err to the sorrow of therevenues, but generally speaking, the cases present a strong combination of equities against thetaxpayer, and few will seriously quarrel with their application of the doctrine of estoppel." (MertensLaw of Federal Income Taxation, Vol. 10-A, pp. 159-160.)It is also claimed that section 9 of Executive Order No. 401-A, series of 1951 es involving an originalassessment of more than P5,000 refers only to compromises and refunds of taxes, but not to totalwithdrawal of the assessment. The contention is without merit. A careful examination of the provisions ofboth sections 8 and 9 of Executive Order No. 401-A, series of 1951, reveals the procedure prescribedtherein is intended as a check or control upon the powers of the Collector of Internal Revenue in respect toassessment and refunds of taxes. If it be conceded that a decision of the Collector of Internal Revenue onpartial remission of taxes is subject to review by the Secretary of Finance and the Board of Tax Appeals,then with more reason should the power of the Collector to withdraw totally an assessment be subject tosuch review.We find merit, however, in petitioner's contention that the Court of Tax Appeals erred in the imposition ofthe 5% fraud surcharge. As already shown in the early part of this decision, no element of fraud is present.Pursuant to Section 183 of the National Internal Revenue Code the 50% surcharge should be added to thedeficiency sales tax "in case a false or fraudulent return is willfully made." Although the sales made by SMare in substance by Yutivo this does not necessarily establish fraud nor the willful filing of a false orfraudulent return.The case of Court Holding Co. v. Commissioner of Internal Revenue (August 9, 1943, 2 TC 531, 541-549) isin point. The petitioner Court Holding Co. was a corporation consisting of only two stockholders, to wit:Minnie Miller and her husband Louis Miller. The only assets of third husband and wife corporation consistedof an apartment building which had been acquired for a very low price at a judicial sale. Louis Miller, thehusband, who directed the company's business, verbally agreed to sell this property to Abe C. Fine andMargaret Fine, husband and wife, for the sum of $54,000.00, payable in various installments. He received$1,000.00 as down payment. The sale of this property for the price mentioned would have netted thecorporation a handsome profit on which a large corporate income tax would have to be paid. On theafternoon of February 23, 1940, when the Millers and the Fines got together for the execution of thedocument of sale, the Millers announced that their attorney had called their attention to the large
corporate tax which would have to be paid if the sale was made by the corporation itself. So instead ofproceeding with the sale as planned, the Millers approved a resolution to declare a dividend to themselves"payable in the assets of the corporation, in complete liquidation and surrender of all the outstandingcorporate stock." The building, which as above stated was the only property of the corporation, was thentransferred to Mr. and Mrs. Miller who in turn sold it to Mr. and Mrs. Fine for exactly the same price andunder the same terms as had been previously agreed upon between the corporation and the Fines.The return filed by the Court Holding Co. with the respondent Commissioner of Internal Revenue reportedno taxable gain as having been received from the sale of its assets. The Millers, of course, reported a longterm capital gain on the exchange of their corporate stock with the corporate property. The Commissionerof Internal Revenue contended that the liquidating dividend to stockholders had no purpose other thanthat of tax avoidance and that, therefore, the sale by the Millers to the Fines of the corporation's propertywas in substance a sale by the corporation itself, for which the corporation is subject to the taxable profitthereon. In requiring the corporation to pay the taxable profit on account of the sale, the Commissioner ofInternal Revenue, imposed a surcharge of 25% for delinquency, plus an additional surcharge as fraudpenalties.The U. S. Court of Tax Appeals held that the sale by the Millers was for no other purpose than to avoid thetax and was, in substance, a sale by the Court Holding Co., and that, therefore, the said corporation shouldbe liable for the assessed taxable profit thereon. The Court of Tax Appeals also sustained theCommissioner of Internal Revenue on the delinquency penalty of 25%. However, the Court of Tax Appealsdisapproved the fraud penalties, holding that an attempt to avoid a tax does not necessarily establishfraud; that it is a settled principle that a taxpayer may diminish his tax liability by means which the lawpermits; that if the petitioner, the Court Holding Co., was of the opinion that the method by which itattempted to effect the sale in question was legally sufficient to avoid the imposition of a tax upon it, itsadoption of that methods not subject to censure; and that in taking a position with respect to a question oflaw, the substance of which was disclosed by the statement indorsed on it return, it may not be said thatthat position was taken fraudulently. We quote in full the pertinent portion of the decision of the Court ofTax Appeals: .". . . The respondent's answer alleges that the petitioner's failure to report as income the taxableprofit on the real estate sale was fraudulent and with intent to evade the tax. The petitioner filed areply denying fraud and averring that the loss reported on its return was correct to the best of itsknowledge and belief. We think the respondent has not sustained the burden of proving afraudulent intent. We have concluded that the sale of the petitioner's property was in substance asale by the petitioner, and that the liquidating dividend to stockholders had no purpose other thanthat of tax avoidance. But the attempt to avoid tax does not necessarily establish fraud. It is asettled principle that a taxpayer may diminish his liability by any means which the lawpermits. United States v. Isham, 17 Wall. 496; Gregory v. Helvering, supra; Chrisholm v.Commissioner, 79 Fed. (2d) 14. If the petitioner here was of the opinion that the method by which itattempted to effect the sale in question was legally sufficient to avoid the imposition of tax upon it,its adoption of that method is not subject to censure. Petitioner took a position with respect to aquestion of law, the substance of which was disclosed by the statement endorsed on its return. Wecan not say, under the record before us, that that position was taken fraudulently. Thedetermination of the fraud penalties is reversed."When GM was the importer and Yutivo, the wholesaler, of the cars and trucks, the sales tax was paid onlyonce and on the original sales by the former and neither the latter nor SM paid taxes on their subsequentsales. Yutivo might have, therefore, honestly believed that the payment by it, as importer, of the sales taxwas enough as in the case of GM Consequently, in filing its return on the basis of its sales to SM and not onthose by the latter to the public, it cannot be said that Yutivo deliberately made a false return for thepurpose of defrauding the government of its revenues which will justify the imposition of the surchargepenalty.We likewise find meritorious the contention that the Tax Court erred in computing the alleged deficiencysales tax on the selling price of SM without previously deducting therefrom the sales tax due thereon. Thesales tax provisions (sees. 184.186, Tax Code) impose a tax on original sales measured by "gross sellingprice" or "gross value in money". These terms, as interpreted by the respondent Collector, do not includethe amount of the sales tax, if invoiced separately. Thus, General Circular No. 431 of the Bureau of InternalRevenue dated July 29, 1939, which implements sections 184.186 of the Tax Code provides: "
. . .'Gross selling price' or gross value in money' of the articles sold, bartered, exchanged,transferred as the term is used in the aforecited sections (sections 184, 185 and 186) of theNational Internal Revenue Code, is the total amount of money or its equivalent which the purchaserpays to the vendor to receive or get the goods. However, if a manufacturer, producer, or importer,in fixing the gross selling price of an article sold by him has included an amount intended to coverthe sales tax in the gross selling price of the articles, the sales tax shall be based on the grossselling price less the amount intended to cover the tax, if the same is billed to the purchaser as aseparate item.General Circular No. 440 of the same Bureau reads:Amount intended to cover the tax must be billed as a separate em so as not to pay a tax on the tax. On sales made after he third quarter of 1939, the amount intended to cover the sales tax mustbe billed to the purchaser as separate items in the, invoices in order that the reduction thereof fromthe gross ailing price may be allowed in the computation of the merchants' percentage tax on thesales. Unless billed to the purchaser as a separate item in the invoice, the amounts intended tocover the sales tax shall be considered as part of the gross selling price of the articles sold, anddeductions thereof will not be allowed, (Cited in Dalupan, Nat. Int. Rev. Code, Annotated, Vol. II, pp.52-53.)Yutivo complied with the above circulars on its sales to SM, and as separately billed, the sales taxes did notform part of the "gross selling price" as the measure of the tax. Since Yutivo had previously billed the salestax separately in its sales invoices to SM General Circulars Nos. 431 and 440 should be deemed to havebeen complied. Respondent Collector's method of computation, as opined by Judge Nable in the decisioncomplained of . . . is unfair, because . . .(it is) practically imposing tax on a tax already paid. Besides, the adoptionof the procedure would in certain cases elevate the bracket under which the tax is based. The latepayment is already penalized, thru the imposition of surcharges, by adopting the theory of theCollector, we will be creating an additional penalty not contemplated by law."If the taxes based on the sales of SM are computed in accordance with Gen. Circulars Nos. 431 and 440 thetotal deficiency sales taxes, exclusive of the 25% and 50% surcharges for late payment and for fraud,would amount only to P820,549.91 as shown in the following computation:
Rates ofSales Tax
5%
SalesTaxes DueGross Sales andof Vehicles ComputedExclusive of underSales TaxGen. CirNos. 431 &400
Total GrossSellingPriceCharged tothe Public
10%
15%
30% 837,146.97
50%
75%
251,114.0 1,088,291.906
8,000.00
6,000.00
14,000.00
Less TaxesPaid byYutivo
988,655.76
Deficiency P820,549.Tax still due91
This is the exact amount which, according to Presiding Judge Nable of the Court of Tax Appeals, Yutivowould pay, exclusive of the surcharges.Petitioner finally contends that the Court of Tax Appeals erred or acted in excess of its jurisdiction inpromulgating judgment for the affirmance of the decision of respondent Collector by less than thestatutory requirement of at least two votes of its judges. Anent this contention, section 2 of Republic ActNo. 1125, creating the Court of Tax Appeals, provides that "Any two judges of the Court of Tax Appealsshall constitute a quorum, and the concurrence of two judges shall be necessary to promulgate decisionthereof. . . . " It is on record that the present case was heard by two judges of the lower court. And whileJudge Nable expressed his opinion on the issue of whether or not the amount of the sales tax should beexcluded from the gross selling price in computing the deficiency sales tax due from the petitioner, theopinion, apparently, is merely an expression of his general or "private sentiment" on the particular issue,for he concurred the dispositive part of the decision. At any rate, assuming that there is no valid decisionfor lack of concurrence of two judges, the case was submitted for decision of the court below on March 28,1957 and under section 13 of Republic Act 1125, cases brought before said court hall be decided within 30days after submission thereof. "If no decision is rendered by the Court within thirty days from the date acase is submitted for decision, the party adversely affected by said ruling, order or decision, may file withsaid Court a notice of his intention to appeal to the Supreme Court, and if no decision has as yet beenrendered by the Court, the aggrieved party may file directly with the Supreme Court an appeal from saidruling, order or decision, notwithstanding the foregoing provisions of this section." The case having beenbrought before us on appeal, the question raised by petitioner as become purely academic.
IN VIEW OF THE FOREGOING, the decision of the Court of Tax Appeals under review is hereby modified inthat petitioner shall be ordered to pay to respondent the sum of P820,549.91, plus 25% surcharge thereonfor late payment.So ordered without costs.Bengzon, Labrador, Concepcion, Reyes, J.B.L., Barrera and Paredes, JJ., concur.Padilla, J., took no part.
HILADO, J.:This is an appeal by Koppel (Philippines), Inc., from the judgment of the Court of First Instance of Manila incivil case No. 51218 of said court dismissing said corporation's complaint for the recovery of the sum ofP64,122.51 which it had paid under protest to the Collector of Internal Revenue on October 30, 1936, asmerchant sales tax. The main facts of the case were stipulated in the court below as follows:AGREED STATEMENT OF FACTSNow come the plaintiff by attorney Eulogio P. Revilla and the defendant by the Solicitor General andundersigned Assistant Attorney of the Bureau of Justice and, with leave of this Honorable Court,hereby respectfully stipulated and agree to the following facts, to wit:I. That plaintiff is a corporation duly organized and existing under and by virtue of the laws of thePhilippines, with principal office therein at the City of Manila, the capital stock of which is dividedinto thousand (1,000) shares of P100 each. The Koppel Industrial Car and Equipment company, acorporation organized and existing under the laws of the State of Pennsylvania, United States ofAmerica, and not licensed to do business in the Philippines, owned nine hundred and ninety-five(995) shares out of the total capital stock of the plaintiff from the year 1928 up to and including theyear 1936, and the remaining five (5) shares only were and are owned one each by officers of theplaintiff corporation.II. That plaintiff, at all times material to this case, was and now is duly licensed to engage inbusiness as a merchant and commercial broker in the Philippines; and was and is the holder of thecorresponding merchant's and commercial broker's privilege tax receipts.III. That the defendant Collector of Internal revenue is now Mr. Bibiano L. Meer in lieu of Mr. AlfredoL. Yatco.IV. That during the period from January 1, 1929, up to and including December 31, 1932, plaintifftransacted business in the Philippines in the following manner, with the exception of thetransactions which are described in paragraphs V and VI of this stipulation:When a local buyer was interested in the purchase of railway materials, machinery, and supplies, itasked for price quotations from plaintiff. Atypical form of such request is attached hereto and madea part hereof as Exhibit A. (Exhibit A represents typical transactions arising from written requestsfor quotations, while Exhibits B to G, inclusive, are typical transactions arising from verbal requestsfor quotation.) Plaintiff then cabled for the quotation desired for Koppel Industrial Car andEquipment Company. A sample of the pertinent cable is hereto attached and made a part hereof asExhibit B. Koppel Industrial Car and Equipment Company answered by cable quoting its cost price,usually A. C. I. F. Manila cost price, which was later followed by a letter of confirmation. A sample ofthe said cable quotation and of the letter of confirmation are hereto attached and made a parthereof as Exhibits C and C-1. Plaintiff, however, quoted by Koppel Industrial Car and EquipmentCompany. Copy of the plaintiff's letter to purchaser is hereto attached and made a part hereof asExhibit D. On the basis of these quotations, orders were placed by the local purchasers, copies ofwhich orders are hereto attached as Exhibits E and E-1.
A cable was then sent to Koppel Industrial Car and Equipment company giving instructions to shipthe merchandise to Manila forwarding the customer's order. Sample of said cable is hereto attachedas Exhibit F. The bills of lading were usually made to "order" and indorsed in blank with notation tothe effect that the buyer be notified of the shipment of the goods covered in the bills of lading;commercial invoices were issued by Koppel Industrial Car and Equipment Company in the names ofthe purchasers and certificates of insurance were likewise issued in their names, or in the name ofKoppel Industrial Car and Equipment Company but indorsed in blank and attached to drafts drawnby Koppel Industrial Car and Equipment Company on the purchasers, which were forwarded throughforeign banks to local banks. Samples of the bills of lading are hereto attached as Exhibits F-1, I-1, I2 and I-3. Bills of ladings, Exhibits I-1, I-2 and I-3, may equally have been employed, but saidExhibits I-1, I-2 and I-3 have no connection with the transaction covered by Exhibits B to G,inclusive. The purchasers secured the shipping papers by arrangement with the banks, andthereupon received and cleared the shipments. If the merchandise were of European origin, and ifthere was not sufficient time to forward the documents necessary for clearance, through foreignbanks to local banks, to the purchasers, the Koppel Industrial Car and Equipment company did, inmany cases, send the documents directly from Europe to plaintiff with instructions to turn thesedocuments over to the purchasers. In many cases, where sales was effected on the basis of C. I. F.Manila, duty paid, plaintiff advanced the sums required for the payment of the duty, and thesesums, so advanced, were in every case reimbursed to plaintiff by Koppel Industrial Car andEquipment Company. The price were payable by drafts agreed upon in each case and drawn byKoppel Industrial Car and Equipment Company on respective purchasers through local banks, andpayments were made to the banks by the purchasers on presentation and delivery to them of theabove-mentioned shipping documents or copies thereof. A sample of said drafts is hereto attachedas Exhibit G. Plaintiff received by way of compensation a percentage of the profits realized on theabove transactions as fixed in paragraph 6 of the plaintiff's contract with Koppel Industrial Car andEquipment Company, which contract is hereto attached as Exhibit H, and suffered its correspondingshare in the losses resulting from some of the transactions.That the total gross sales from January 1, 1929, up to and including December 31, 1932, effected inthe foregoing manner and under the above specified conditions, amount to P3, 596,438.84.V. That when a local sugar central was interested in the purchase of railway materials, machineryand supplies, it secured quotations from, and placed the corresponding orders with, the plaintiff insubstantially the same manner as outlined in paragraph IV of this stipulation, with the onlydifference that the purchase orders which were agreed to by the central and the plaintiff are similarto the sample hereto attached and made a part hereof as Exhibit I. Typical samples of the bills oflading covering the herein transaction are hereto attached and made a part hereto as Exhibits I-1, I2 and I-3. The value of the sales carried out in the manner mentioned in this paragraph isP133,964.98.VI. That sometime in February, 1929, Miguel J. Ossorio, of Manila, Philippines, placed an option withKoppel Industrial Car and Equipment Company, through plaintiff, to purchase within three months apair of Atlas-Diesel Marine Engines. Koppel Industrial Car and Equipment Company purchased saidDiesel Engines in Stockholm, Sweden, for $16,508.32. The suppliers drew a draft for the amount of$16,508.32 on the Koppel Industrial Car and Equipment Company, which paid the amount coveredby the draft. Later, Miguel J. Ossorio definitely called the deal off, and as Koppel Industrial Car andEquipment Company could not ship to or draw on said Mr. Miguel J. Ossorio, it in turn drew anotherdraft on plaintiff for the same amount at six months sight, with the understanding that KoppelIndustrial Car and Equipment Company would reimburse plaintiff when said engines were disposedof. Plaintiff honored the draft and debited the said sum of $16,508.32 to merchandise account. Theengines were left stored at Stockholm, Sweden. On April 1, 1930, a new local buyer, Mr. CesarBarrios, of Iloilo, Philippines, was found and the same engines were sold to him for $21,000(P42,000) C. I. F. Hongkong. The engines were shipped to Hongkong and a draft for $21,000 wasdrawn by Koppel Industrial Car and Equipment Company on Mr. Cesar Barrios. After the draft wasfully paid by Mr. Barrios, Koppel Industrial Car and Equipment Company reimbursed plaintiff withcost price of $16,508.32 and credited it with $1,152.95 as its share of the profit on the transaction.Exhibits J and J-1 are herewith attached and made integral parts of this stipulation with particularreference to paragraph VI hereof.
VII. That plaintiff's share in the profits realized out of these transactions described in paragraphs IV,V and VI hereof totaling P3,772,403.82, amounts to P132,201.30; and that plaintiff within the timeprovided by law returned the aforesaid amount P132,201.30 for the purpose of the commercialbroker's 4 per cent tax and paid thereon the sum P5,288.05 as such tax.VIII. That defendant demanded of the plaintiff the sum of P64,122.51 as the merchants' sales tax of1% per cent on the amount of P3,772,403.82, representing the total gross value of the salesmentioned in paragraphs IV, V and VI hereof, including the 25 per cent surcharge for the latepayment of the said tax, which tax and surcharge were determined after the amount of P5,288.05mentioned in paragraph VI hereof was deducted.IX. That plaintiff, on October 30, 1936, paid under protest said sum of P64,122.51 in order to avoidfurther penalties, levy and distraint proceedings.X. That defendant, on November 10, 1936, overruled plaintiff's protest, and defendant has failedand refused and still fails and refuses, notwithstanding demands by plaintiff, to return to theplaintiff said sum of P64,122.51 or any part thereof.xxx
That the parties hereby reserve the right to present additional evidence in support oftheir respective contentions.Manila, Philippines, December 26, 1939(Sgd.) ROMAN OZAETASolicitor General(Sgd.) ANTONIO CAIZARESAssistant Attorney(Sgd.) E. P. REVILLAAttorney for the Plaintiff3rd Floor, Perez Samanillo Bldg., ManilaBoth parties adduced some oral evidence in clarification of or addition to their agreed statement offacts. A preponderance of evidence has established, besides the facts thus stipulated, the following:(a) The shares of stock of plaintiff corporation were and are all owned by Koppel IndustriesCar and Equipment Company of Pennsylvania, U. S. A., exceptive which were necessary toqualify the Board of Directors of said plaintiff corporation;(b) In the transactions involved herein the plaintiff corporation acted as the representative ofKoppel Industrial Car and Equipment Company only, and not as the agent of both the lattercompany and the respective local purchasers plaintiff's principal witness, A.H. Bishop, itsresident Vice-President, in his testimony invariably referred to Koppel Industrial Car andEquipment Co. as "our principal" 9 t. s. n., pp. 10, 11, 12, 19, 75), except that at the bottomof page 10 to the top of page 11, the witness stated that they had "several principal" abroadbut that "our principal abroad was, for the years in question, Koppel Industrial Car andEquipment Company," and on page 68, he testified that what he actually said was ". . . butour principal abroad" and not "our principal abroad" as to which it is very significant thatneither this witness nor any other gave the name of even a single other principal abroad ofthe plaintiff corporation;(c) The plaintiff corporation bore alone incidental expenses as, for instance, cableexpenses-not only those of its own cables but also those of its "principal" (t.s.n., pp. 52, 53);
(d) the plaintiff's "share in the profits" realized from the transactions in which it intervenedwas left virtually in the hands of Koppel Industrial Car and Equipment Company (t.s.n., p.51);(e) Where drafts were not paid by the purchasers, the local banks were instructed not toprotest them but to refer them to plaintiff which was fully empowered by Koppel IndustrialCar and Equipment company to instruct the banks with regards to disposition of the draftsand documents (t.s.n., p. 50; Exhibit G);lawphil.net(f) Where the goods were European origin, consular invoices, bill of lading, and, in general,the documents necessary for clearance were sent directly to plaintiff (t.s.n., p. 14);(g) If the plaintiff had in stock the merchandise desired by local buyers, it immediately filledthe orders of such local buyers and made delivery in the Philippines without the necessity ofcabling its principal in America either for price quotations or confirmation or rejection of thatagreed upon between it and the buyer (t.s.n., pp. 39-43);(h) Whenever the deliveries made by Koppel Industrial Car and Equipment Company wereincomplete or insufficient to fill the local buyer's orders, plaintiff used to make good thedeficiencies by deliveries from its own local stock, but in such cases it charged its principalonly the actual cost of the merchandise thus delivered by it from its stock and in suchtransactions plaintiff did not realize any profit (t.s.n., pp. 53-54);(i) The contract of sale involved herein were all perfected in the Philippines.Those described in paragraph IV of the agreed statement of facts went through the followingprocess: (1) "When a local buyer was interested in the purchase of railway materials, machinery,and supplies, it asked for price quotations from plaintiff"; (2) "Plaintiff then cabled for the quotationdesired from Koppel Industrial Car and Equipment Company"; (3) "Plaintiff, however, quoted to thepurchaser a selling price above the figures quoted by Koppel Industrial Car and EquipmentCompany"; (4) "On the basis of these quotations, orders were placed by the local purchasers . . ."Those described in paragraph V of said agreed statement of facts were transacted "in substantiallythe same manner as outlined in paragraph IV."As to the single transaction described in paragraph VI of the same agreed statement of facts,discarding the Ossorio option which anyway was called off, "On April 1, 1930, a new local buyer, Mr.Cesar Barrios, of Iloilo, Philippines, was found and the same engines were sold to him for$21,000(P42,000) C.I.F. Hongkong." (Emphasis supplied.).(j) Exhibit H contains Court of First Instance held for the defendant and dismissed plaintiff's complaint with costs to it.Upon this appeal, seven errors are assigned to said judgment as follows:.1. That the court a quo erred in not holding that appellant is a domestic corporation distinct andseparate from, and not a mere branch of Koppel Industrial Car and Equipment Co.;2. the court a quo erred in ignoring the ruling of the Secretary of Finance, dated January 31, 1931,Exhibit M;
3. the court a quo erred in not holding that a character of a broker is determined by the nature ofthe transaction and not by the basis or measure of his compensation;4. The court a quo erred in not holding that appellant acted as a commercial broker in thetransactions covered under paragraph VI of the agreed statement of facts;5. The court a quo erred in not holding that appellant acted as a commercial broker in thetransactions covered under paragraph v of the agreed statement of facts;6. The court a quo erred in not holding that appellant acted as a commercial broker in the soletransaction covered under paragraph VI of the agreed statement of facts;7. the court a quo erred in dismissing appellant's complaint.The lower court found and held that Koppel (Philippines), Inc. is a mere dummy or brach ("hechura") ofKoppel industrial Car and Equipment Company. The lower court did not deny legal personality to Koppel(Philippines), Inc. for any and all purposes, but in effect its conclusion was that, in the transactionsinvolved herein, the public interest and convenience would be defeated and what would amount to a taxevasion perpetrated, unless resort is had to the doctrine of "disregard of the corporate fiction."I. In its first assignment of error appellant submits that the trial court erred in not holding that it is adomestic corporation distinct and separate from and not a mere branch of Koppel Industrial Car andEquipment Company. It contends that its corporate existence as Philippine corporation can not becollaterally attacked and that the Government is estopped from so doing. As stated above, the lower courtdid not deny legal personality to appellant for any and all purposes, but held in effect that in thetransaction involved in this case the public interest and convenience would be defeated and what wouldamount to a tax evasion perpetrated, unless resort is had to the doctrine of "disregard of the corporatefiction." In other words, in looking through the corporate form to the ultimate person or corporation behindthat form, in the particular transactions which were involved in the case submitted to its determination andjudgment, the court did so in order to prevent the contravention of the local internal revenue laws, and theperpetration of what would amount to a tax evasion, inasmuch as it considered and in our opinion,correctly that appellant Koppel (Philippines), Inc. was a mere branch or agency or dummy ("hechura") ofKoppel Industrial Car and Equipment Co. The court did not hold that the corporate personality of Koppel(Philippines), Inc., would also be disregarded in other cases or for other purposes. It would have had nopower to so hold. The courts' action in this regard must be confined to the transactions involved in thecase at bar "for the purpose of adjudging the rights and liabilities of the parties in the case. They have nojurisdiction to do more." (1 Flethcer, Cyclopedia of Corporation, Permanent ed., p. 124, section 41.)A leading and much cited case puts it as follows convinience, justify wrong, protectfraud, or defend crime, the law will regard the corporation as an association of persons. (1 FletcherCyclopedia of Corporation [Permanent Edition], pp. 135, 136; United States vs. MilwaukeeRefrigeration Transit Co., 142 Fed., 247, 255, per Sanborn, J.)In his second special defense appellee alleges "that the plaintiff was and is in fact a branch or subsidiary ofKoppel Industrial Car and Equipment Co., a Pennsylvania corporation not licensed to do business in thePhilippines but actually doing business here through the plaintiff; that the said foreign corporation holds995 of the 1,000 shares of the plaintiff's capital stock, the remaining five shares being held by the officersof the plaintiff herein in order to permit the incorporation thereof and to enable its aforesaid officers to actas directors of the plaintiff corporation; and that plaintiff was organized as a Philippine corporation for thepurpose of evading the payment by its parent foreign corporation of merchants' sales tax on thetransactions involved in this case and others of similar nature."By most courts the entity is normally regarded but is disregarded to prevent injustice, or thedistortion or hiding of the truth, or to let in a just defense. (1 Fletcher, Cyclopedia of Corporation,Permanent Edition, pp. 139,140; emphasis supplied.)
Another rule is that, when the corporation is the mere alter ego, or business conduit of a person, itmay de disregarded." (1 Fletcher, Cyclopedia of Corporation, Permanent Edition, p. 136.)Manifestly, the principle is the same whether the "person" be natural or artificial.A very numerous and growing class of cases wherein the corporate entity is disregarded is that (it isso organized and controlled, and its affairs are so conducted, as to make it merely aninstrumentality, agency, conduit or adjunct of another corporation)." (1 Fletcher, Cyclopedia ofCorporation, Permanent ed., pp. 154, 155.)While we recognize the legal principle that a corporation does not lose its entity by the ownership ofthe bulk or even the whole of its stock, by another corporation (Monongahela Co. vs. Pittsburg Co.,196 Pa., 25; 46 Atl., 99; 79 Am. St. Rep., 685) yet it is equally well settled and ignore corporateforms." (Colonial Trust Co. vs. Montello Brick Works, 172 Fed., 310.)Where it appears that two business enterprises are owned, conducted and controlled by the sameparties, both law and equity will, when necessary to protect the rights of third persons, disregardthe legal fiction that two corporations are distinct entities, and treat them as identical. (Abney vs.Belmont Country Club Properties, Inc., 279 Pac., 829.). . . the legal fiction of distinct corporate existence will be disregarded in a case where a corporationis so organized and controlled and its affairs are so conducted, as to make it merely aninstrumentality or adjunct of another corporation. (Hanter vs. Baker Motor Vehicle Co., 190 Fed.,665.)In United States vs. Lehigh Valley R. Co. 9220 U.S., 257; 55 Law. ed., 458, 464), the Supreme Court of theUnited States disregarded the artificial personality of the subsidiary coal company in order to avoid thatthe parent corporation, the Lehigh Valley R. Co., should be able, through the fiction of that personality, toevade the prohibition of the Hepburn Act against the transportation by railroad companies of the articlesand commodities described therein.Chief Justice White, speaking for the court, said:. . . Coming to discharge this duty it follows, in view of the express prohibitions of the commoditiesclause, it must be held that while the right of a railroad company as a stockholder to use its stockownership for the purpose of a bona fide separate administration of the affairs of a corporation inwhich it has a stock interest may not be denied, the use of such stock ownership in substance forthe purpose of destroying the entity of a producing, etc., corporation, and commingling its affairs inadministration with the affairs of the railroad company, so as to make the two corporations virtuallyone, brings the railroad company so voluntarily acting as to such producing, etc., corporation withinthe prohibitions of the commodities clause. In other words, that by operation and effect of thecommodities clause there is duty cast upon a railroad company proposing to carry in interstatecommerce the product of a producing, etc., corporation in which it has a stock interest, not to abusesuch power so as virtually to do by indirection that which the commodities clause prohibits, aduty which plainly would be violated by the unnecessary commingling of the affairs of theproducing company with its own, so as to cause them to be one and inseparable.Corrobarative authorities can be cited in support of the same proposition, which we deem unnecessary tomention here.From the facts hereinabove stated, as established by a preponderance of the evidence , particularly thosenarrated in paragraph (a), (b), (c), (d), (e),(f), (h), (i), and (j) after the agreed statement of facts, we findthat, in so far as the sales involved herein are concerned, Koppel (Philippines), Inc., and Koppel IndustrialCar and Equipment company are to all intents and purposes one and the same; or, to use another mode ofexpression, that, as regards those transactions, the former corporation is a mere branch, subsidiary oragency of the latter. To our mind, this is conclusively borne out by the fact, among others, that the amountof he so-called "share in the profits" of Koppel (Philippines), Inc., was ultimately left to the sole, unbridledcontrol of Koppel Industrial Car and Equipment Company. If, in their relations with each other, Koppel(Philippines), Inc., was considered and intended to function as a bona fide separate corporation, we can
not conceive how this arrangement could have been adopted, for if there was any factor in its business asto which it would in that case naturally have been opposed to being thus controlled, it must have beenprecisely the amount of profit which it could endeavor and hope to earn. No group of businessmen couldbe expected to organize a mercantile corporation the ultimate end of which could only be profit if theamount of that profit were to be subjected to such a unilateral control of another corporation, unlessindeed the former has previously been designed by the incorporators to serve as a mere subsidiary,branch or agency of the latter. Evidently, Koppel Industrial Car and Equipment Company made us of itsownership of the overwhelming majority 99.5% of the capital stock of the local corporation to controlthe operations of the latter to such an extent that it had the final say even as to how much should beallotted to said local entity in the so-called sharing in the profits. We can not overlook the fact that in thepractical working of corporate organizations of the class to which these two entities belong, the holder orholders of the controlling part of the capital stock of the corporation, particularly where the control isdetermined by the virtual ownership of the totality of the shares, dominate not only the selection of theBoard of Directors but, more often than not, also the action of that Board. Applying this to the instant case,we can not conceive how the Philippine corporation could effectively go against the policies, decisions, anddesires of the American corporation with regards to the scheme which was devised through theinstrumentality of the contract Exhibit H, as well as all the other details of the system which was adoptedin order to avoid paying the 1 per cent merchants sales tax. Neither can we conceive how the Philippinecorporation could avoid following the directions of the American corporation held 99.5 per cent of thecapital stock of the Philippine corporation. In the present instance, we note that Koppel (Philippines), Inc.,was represented in the Philippines by its "resident Vice-President." This fact necessarily leads to theinference that the corporation had at least a Vice-President, and presumably also a President, who werenot resident in the Philippines but in America, where the parent corporation is domiciled. If Koppel(Philippines), Inc., had been intended to operate as a regular domestic corporation in the Philippines,where it was formed, the record and the evidence do not disclose any reason why all its officers should notreside and perform their functions in the Philippines.Other facts appearing from the evidence, and presently to be stated, strengthen our conclusion, becausethey can only be explained if the local entity is considered as a mere subsidiary, branch or agency of theparent organization. Plaintiff charged the parent corporation no more than actual cost without profitwhatsoever for merchandise allegedly of its own to complete deficiencies of shipments made by saidparent corporation (t.s.n., pp. 53, 54) a fact which could not conceivably have been the case if plaintiffhad acted in such transactions as an entirely independent entity doing business for profit, of course with the American concern. There has been no attempt even to explain, if the latter situation reallyobtained, why these two corporations should have thus departed from the ordinary course of business.Plaintiff was charged by the American corporation with the cost even of the latter's cable quotations from ought that appears from the evidence, this can only be comprehended by considering plaintiff assuch a subsidiary, branch or agency of the parent entity, in which case it would be perfectlyunderstandable that for convenient accounting purposes and the easy determination of the profits orlosses of the parent corporation's Philippines should be charged against the Philippine office and set offagainst its receipts, thus separating the accounts of said branch from those which the central organizationmight have in other countries. The reference to plaintiff by local banks, under a standing instruction of theparent corporation, of unpaid drafts drawn on Philippine customers by said parent corporation, wheneversaid customers dishonored the drafts, and the fact that the American corporation had previously advisedsaid banks that plaintiff in those cases was "fully empowered to instruct (the banks) with regard to thedisposition of the drafts and documents" (t.s.n., p. 50), in the absence of any other satisfactory explanationnaturally give rise to the inference that plaintiff was a subsidiary, branch or agency of the Americanconcern, rather than an independent corporation acting as a broker. For, without such positive explanation,this delegation of power is indicative of the relations between central and branch offices of the samebusiness enterprise, with the latter acting under instructions already given by the former. Far fromdisclosing a real separation between the two entities, particularly in regard to the transactions in question,the evidence reveals such commongling and interlacing of their activities as to render evenincomprehensible certain accounting operations between them, except upon the basis that the Philippinecorporation was to all intents and purposes a mere subsidiary, branch, or agency of the American parententity. Only upon this basis can it be comprehended why it seems not to matter at all how much profitwould be allocated to plaintiff, or even that no profit at all be so allocated to it, at any given time or afterany given period.As already stated above, under the evidence the sales in the Philippines of the railway materials,machinery and supplies imported here by Koppel Industrial Car and Equipment Company could have beenas conviniently and efficiently transacted and handled if not more so had said corporation merely
established a branch or agency in the Philippines and obtained license to do business locally; and if it haddone so and said sales had been effected by such branch or agency, there seems to be no dispute that the1 per cent merchants' sales tax then in force would have been collectible. So far as we can discover,there would be only one, but very important, difference between the two schemes a difference in taxliability on the ground that the sales were made through another and distinct corporation, as allegedbroker, when we have seen that this latter corporation is virtually owned by the former, or that theypractically one and the same, is to sanction a circumvention of our tax laws, and permit a tax evasion of nomean proportions and the consequent commission of a grave injustice to the Government. Not only this; itwould allow the taxpayer to do by indirection what the tax laws prohibited to be done directly (nonpayment of legitimate taxes), paraphrasing the United States Supreme Court in United States vs. LehighValley R. Co., supra.The act of one corporation crediting or debiting the other for certain items, expenses or even merchandisesold or disposed of, is perfectly compatible with the idea of the domestic entity being or acting as a merebranch, agency or subsidiary of the parent organization. Such operations were called for any way by theexigencies or convenience of the entire business. Indeed, accounting operation such as these are invitable,and have to be effected in the ordinary course of business enterprise extends its trade to another landthrough a branch office, or through another scheme amounting to the same thing.If plaintiff were to act as broker in the Philippines for any other corporation, entity or person, distinct fromKoppel Industrial Car and Equipment company, an entirely different question will arise, which, however, weare not called upon, nor in a position, to decide.As stated above, Exhibit H contains to foregoing paragraph, construed in the light of other facts noted elsewhere in this decision, betrays, wethink a deliberate intent, through the medium of a scheme devised with great care, to avoid the paymentof precisely the 1 per cent merchants' sales tax in force in the Philippines before, at the time of, andafter, the making of the said contract Exhibit H. If this were to be allowed, the payment of a tax, whichdirectly could not have been avoided, could be evaded by indirection, consideration being had of theaforementioned peculiar relations between the said American and local corporations. Such evasion,involving as it would, a violation of the former Internal Revenue Law, would even fall within the penalsanction of section 2741 of the Revised Administrative Code. Which only goes to show the illegality of thewhole scheme. We are not here concerned with the impossibility of collecting the merchants' sales tax, asa mere incidental consequence of transactions legal in themselves and innocent in their purpose. We aredealing with a scheme the primary, not to say the sole, object of which the evasion of the payment of suchtax. It is this aim of the scheme that makes it illegal.We have said above that the contracts of sale involved herein were all perfected in the Philippines. Fromthe facts stipulated in paragraph IV of the agreed statement of facts, it clearly appears that the Philippinepurchasers had to wait for Koppel Industrial Car and Equipment Company to communicate its cost prices toKoppel (Philippines), Inc., were perfected in the Philippines. In those cases where no such price quotationsfrom the American corporation were needed, of course, the sales effected in those cases described inparagraph V of the agreed statement of facts were, as expressed therein, transacted "in substantially thesame manner as outlined in paragraph VI." Even the single transaction described in paragraph VI of theagreed statement of facts was also perfected in the Philippines, because the contracting parties were hereand the consent of each was given here. While it is true that when the contract was thus perfected in thePhilippines the pair of Atlas-Diesel Marine Engines were in Sweden and the agreement was to deliver themC.I.F. Hongkong, the contract of sale being consensual perfected by mere consent (Civil Code, article1445; 10 Manresa, 4th ed., p. 11), the location of the property and the place of delivery did not matter inthe question of where the agreement was perfected.
In said paragraph VI, we read the following, as indicating where the contract was perfected, consideringbeforehand that one party, Koppel (Philippines),Inc., which in contemplation of law, as to that transaction,was the same Koppel Industrial Car Equipment Co., was in the Philippines:. . . on April 1, 1930, a new local buyer Mr. Cesar Barrios, of Iloilo, Philippines, was found and thesame engines were sold to him for $21,000 (P42,000) C.I.F. Hongkong . . . (Emphasis supplied.)Under the revenue law in force when the sales in question took place, the merchants' sales tax attachedupon the happening of the respective sales of the "commodities, goods, wares, and merchandise"involved, and we are clearly of opinion that such "sales" took place upon the perfection of thecorresponding contracts. If such perfection took place in the Philippines, the merchants' sales tax then inforce here attached to the transactions.Even if we should consider that the Philippine buyers in the cases covered by paragraph IV and V of theagreed statement of facts, contracted with Koppel Industrial Car and Equipment company, we will arrive atthe same final result. It can not be denied in that case that said American corporation contracted throughKoppel (Philippines), Inc., which was in the Philippines. The real transaction in each case of sale, in finaleffect, began with an offer of sale from the seller, said American corporation, through its agent, the localcorporation, of the railway materials, machinery, and supplies at the prices quoted, and perfected orcompleted by the acceptance of that offer by the local buyers when the latter, accepting those prices,placed their orders. The offer could not correctly be said to have been made by the local buyers when theyasked for price quotations, for they could not rationally be taken to have bound themselves to buy beforeknowing the prices. And even if we should take into consideration the fact that the american corporationcontracted, at least partly, through correspondence, according to article 54 of the Code of Commerce, therespective contracts were completed from the time of the acceptance by the local buyers, which happenedin the Philippines.Contracts executed through correspondence shall be completed from the time an answer ismade accepting the proposition or the conditions by which the latter may be modified." (Code ofCommerce, article 54; emphasis supplied.)A contract is as a rule considered as entered into at the place where the place it is performed. Sowhere delivery is regarded as made at the place of delivery." (13 C. J., 580-81, section 581.)(In the consensual contract of sale delivery is not needed for its perfection.)II. Appellant's second assignment of error can be summarily disposed of. It is clear that the ruling of theSecretary of Finance, Exhibit M, was not binding upon the trial court, much less upon this tribunal, sincethe duty and power of interpreting the laws is primarily a function of the judiciary. (Ortua vs. SingsonEncarnacion, 59 Phil., 440, 444.) Plaintiff cannot be excused from abiding by this legal principle, nor can itproperly be heard to say that it relied on the Secretary's ruling and that, therefore, the courts should notnow apply an interpretation at variance therewith. The rule of stare decisis is undoubtedly entitled to morerespect in the construction of statutes than the interpretations given by officers of the administrativebranches of the government, even those entrusted with the administration of particular laws. But thiscourt, in Philippine Trust Company and Smith, Bell and Co. vs. Mitchell(59 Phil., 30, 36), said:. . . The rule of stare decisis is entitled to respect. Stability in the law, particularly in the businessfield, is desirable. But idolatrous reverence for precedent, simply as precedent, no longer rules.More important than anything else is that court should be right. . . .III. In the view we take of the case, and after the disposition made above of the first assignment of error, itbecomes unnecessary to make any specific ruling on the third, fourth, fifth, sixth, and seventhassignments of error, all of which are necessarily disposed of adversely to appellant's contention.Wherefore, he judgment appealed from is affirmed, with costs of both instances against appellant. Soordered.Moran, C.J., Paras, Feria, Pablo, Bengzon, Briones, and Tuason, JJ., concur.
On March 8, 1949, stock dividends were again issued by Liddell & Co. and in accordance with theagreements, Exhibits A, B, and C, the stocks of said company stood as follows:
Name
FrankLiddell
No. ofShare Amounts
PerCent
IreneLiddell
.01%
MercedesVecin
CharlesKurz
E.J.Darras
AngelManzano
JulianSerrano
710
71,000 3.74%
E. Hasim
500
50,000 2.64%
G. W.Kernot
On November 15, 1948, in accordance with a resolution of a special meeting of the Board of Directors ofLiddell & Co., stock dividends were again declared. As a result of said declaration and in accordance withthe agreements, Exhibits, A, B, and C, the stockholdings in the company appeared to be:
No. ofAmountShares
19,738
P1,973,8 65.79100%
.003%
E.Hasim
830
83,000 2.770%
30,000
P3,000,0 100.00000%
On the basis of the agreement Exhibit A, (May, 1947) "40%" of the earnings available for dividendsaccrued to Frank Liddell although at the time of the execution of aid instrument, Frank Liddell owned all ofthe shares in said corporation. 45% accrued to the employees, parties thereto; Kurz 12-1/2%; Darras 121/2%; A. Manzano 12-1/2% and Julian Serrano 7-1/2%. The agreement Exhibit A was also made retroactiveto 1946. Frank Liddell reserved the right to reapportion the 45% dividends pertaining to the employees inthe future for the purpose of including such other faithful and efficient employees as he may subsequentlydesignate. (As a matter of fact, Frank Liddell did so designate two additional employees namely: E. Hasim
and G. W. Kernot). It was for such inclusion of future faithful employees that Exhibits B-1 and C wereexecuted. As per Exhibit C, dated May 13, 1948, the 45% given by Frank Liddell to his employees wasreapportioned as follows: C. Kurz 12,%; E. J. Darras 12%; A. Manzano l2%; J. Serrano 3-1/2%; G.W. Kernot 2%.Exhibit B contains the employees' definition in detail of the manner by which they sought to prevent theirshare-holdings from being transferred to others who may be complete strangers to the business on Liddell& Co.From 1946 until November 22, 1948 when the purpose clause of the Articles of Incorporation of Liddell &Co. Inc., was amended so as to limit its business activities to importations of automobiles and trucks,Liddell & Co. was engaged in business as an importer and at the same time retailer of Oldsmobile andChevrolet passenger cars and GMC and Chevrolet trucks.On December 20, 1948, the Liddell Motors, Inc. was organized and registered with the Securities andExchange Commission with an authorized capital stock of P100,000 of which P20,000 was subscribed andpaid for as follows: Irene Liddell wife of Frank Liddell 19,996 shares and Messrs. Marcial P. Lichauco, E. K.Bromwell, V. E. del Rosario and Esmenia Silva, 1 share each.At about the end of the year 1948, Messrs. Manzano, Kurz and Kernot resigned from their respectivepositions in the Retail Dept. of Liddell & Co. and they were taken in and employed by Liddell Motors, Inc.:Kurz as Manager-Treasurer, Manzano as General Sales Manager for cars and Kernot as General SalesManager for trucks.Beginning January, 1949, Liddell & Co. stopped retailing cars and trucks; it conveyed them instead toLiddell Motors, Inc. which in turn sold the vehicles to the public with a steep mark-up. Since then, Liddell &Co. paid sales taxes on the basis of its sales to Liddell Motors Inc. considering said sales as its originalsales.Upon review of the transactions between Liddell & Co. and Liddell Motors, Inc. the Collector of InternalRevenue determined that the latter was but an alter ego of Liddell & Co. Wherefore, he concluded, that forsales tax purposes, those sales made by Liddell Motors, Inc. to the public were considered as the originalsales of Liddell & Co. Accordingly, the Collector of Internal Revenue assessed against Liddell & Co. a salestax deficiency, including surcharges, in the amount of P1,317,629.61. In the computation, the gross sellingprice of Liddell Motors, Inc. to the general public from January 1, 1949 to September 15, 1950, was madethe basis without deducting from the selling price, the taxes already paid by Liddell & Co. in its sales to theLiddell Motors Inc.The Court of Tax Appeals upheld the position taken by the Collector of Internal Revenue.A. Judge Umali: Appellant urges the disqualification on of Judge Roman M. Umali to participate in thedecision of the instant case because he was Chief of the Law Division, then Acting Deputy Collector andlater Chief Counsel of the Bureau of Internal Revenue during the time when the assessment in questionwas made.1 In refusing to disqualify himself despite admission that had held the aforementioned offices,Judge Umali stated that he had not in any way participated, nor expressed any definite opinion, on anyquestion raised by the parties when this case was presented for resolution before the said bureau.Furthermore, after careful inspection of the records of the Bureau, he (Judge Umali as well as the othermembers of the court below), had not found any indication that he had expressed any opinion or made anydecision that would tend to disqualify him from participating in the consideration of the case in the TaxCourt.At this juncture, it is well to consider that petitioner did not question the truth of Judge Umali's statements.In view thereof, this Tribunal is not inclined to disqualify said judge. Moreover, in furtherance of thepresumption of the judge's moral sense of responsibility this Court has adopted, and now here repeats, theruling that the mere participation of a judge in prior proceedings relating to the subject in the capacity ofan administrative official does not necessarily disqualify him from acting as judge. 2Appellant also contends that Judge Umali signed the said decision contrary to the provision of Section 13,Republic Act No. 1125;3 that whereas the case was submitted for decision of the Court of Tax Appeals on
July 12, 1955, and the decision of Associate Judge Luciano and Judge Nable were both signed on August 11,1955 (that is, on the last day of the 30-day period provided for in Section 13, Republic Act No. 1125), JudgeUmali signed the decision August 31, 1955 or 20 days after the lapse of the 30-day period allotted by law.By analogy it may be said that inasmuch as in Republic Act No. 1125 (law creating the Court of TaxAppeals) like the law governing the procedure in the court of Industrial Relations, there is no provisioninvalidating decisions rendered after the lapse of 30 days, the requirement of Section 13, Republic Act No.1125 should be construed as directory.4Besides as pointed out by appellee, the third paragraph of Section 13 of Republic Act No. 1125 (quoted inthe margin)5 confirms this view; because in providing for two thirty-day periods, the law means thatdecision may still be rendered within the second period of thirty days (Judge Umali signed his decisionwithin that period).B. Identity of the two corporations: On the question whether or not Liddell Motors, Inc. is the alter ego ofLiddell & Co. Inc., we are fully convinced that Liddell & Co. is wholly owned by Frank Liddell. As of the timeof its organization, 98% of the capital stock belonged to Frank Liddell. The 20% paid-up subscription withwhich the company began its business was paid by him. The subsequent subscriptions to the capital stockwere made by him and paid with his own money.These stipulations and conditions appear in Exhibit A: (1) that Frank Liddell had the authority to designatein the future the employee who could receive earnings of the corporation; to apportion among the stockholders the share in the profits; (2) that all certificates of stock in the names of the employees should bedeposited with Frank Liddell duly indorsed in blank by the employees concerned; (3) that each employeewas required to sign an agreement with the corporation to the effect that, upon his death or upon hisretirement or separation for any cause whatsoever from the corporation, the said corporation should,within a period of sixty days therefor, have the absolute and exclusive option to purchase and acquire thewhole of the stock interest of the employees so dying, resigning, retiring or separating.These stipulations in our opinion attest to the fact that Frank Liddell also owned it. He supplied the originalhis complete control over the corporation.As to Liddell Motors, Inc. we are fully persuaded that Frank Liddell also owned it. He supplied the originalcapital funds.6 It is not proven that his wife Irene, ostensibly the sole incorporator of Liddell Motors, Inc.had money of her own to pay for her P20,000 initial subscription. 7 Her income in the United States in theyears 1943 and 1944 and the savings therefrom could not be enough to cover the amount of subscription,much less to operate an expensive trade like the retail of motor vehicles. The alleged sale of her propertyin Oregon might have been true, but the money received therefrom was never shown to have been savedor deposited so as to be still available at the time of the organization of the Liddell Motors, Inc.The evidence at hand also shows that Irene Liddell had scant participation in the affairs of Liddell Motors,Inc. She could hardly be said to possess business experience. The income tax forms record no independentincome of her own. As a matter of fact, the checks that represented her salary and bonus from LiddellMotors, Inc. found their way into the personal account of Frank Liddell. Her frequent absences from thecountry negate any active participation in the affairs of the Motors company.There are quite a series of conspicuous circumstances that militate against the separate and distinctpersonality of Liddell Motors, Inc. from Liddell & Co. 8 We notice that the bulk of the business of Liddell &Co. was channeled through Liddell Motors, Inc. On the other hand, Liddell Motors, Inc. pursued no activitiesexcept to secure cars, trucks, and spare parts from Liddell & Co. Inc. and then sell them to the generalpublic. These sales of vehicles by Liddell & Co. to Liddell Motors, Inc. for the most part were shown to havetaken place on the same day that Liddell Motors, Inc. sold such vehicles to the public. We may even saythat the cars and trucks merely touched the hands of Liddell Motors, Inc. as a matter of formality.During the first six months of 1949, Liddell & Co. issued ten (10) checks payable to Frank Liddell whichwere deposited by Frank Liddell in his personal account with the Philippine National Bank. During this timealso, he issued in favor of Liddell Motors, Inc. six (6) checks drawn against his personal account with thesame bank. The checks issued by Frank Liddell to the Liddell Motors, Inc. were significantly for the most
part issued on the same day when Liddell & Co. Inc. issued the checks for Frank Liddell 9 and for the sameamounts.It is of course accepted that the mere fact that one or more corporations are owned and controlled by asingle stockholder is not of itself sufficient ground for disregarding separate corporate entities.Authorities10 support the rule that it is lawful to obtain a corporation charter, even with a single substantialstockholder, to engage in a specific activity, and such activity may co-exist with other private activities ofthe stockholder. If the corporation is a substantial one, conducted lawfully and without fraud on another, itsseparate identity is to be respected.Accordingly, the mere fact that Liddell & Co. and Liddell Motors, Inc. are corporations owned and controlledby Frank Liddell directly or indirectly is not by itself sufficient to justify the disregard of the separatecorporate identity of one from the other. There is, however, in this instant case, a peculiar consequence ofthe organization and activities of Liddell Motors, Inc.Under the law in force at the time of its incorporation the sales tax on original sales of cars (sections 184,185 and 186 of the National Internal Revenue Code), was progressive, i.e. 10% of the selling price of thecar if it did not exceed P5000, and 15% of the price if more than P5000 but not more than P7000, etc. Thisprogressive rate of the sales tax naturally would tempt the taxpayer to employ a way of reducing the priceof the first sale. And Liddell Motors, Inc. was the medium created by Liddell & Co. to reduce the price andthe tax liability.Let us illustrate: a car with engine motor No. 212381 was sold by Liddell & Co. Inc. to Liddell Motors, Inc.on January 17, 1948 for P4,546,000.00 including tax; the price of the car was P4,133,000.23, the tax paidbeing P413.22, at 10%. And when this car was later sold (on the same day) by Liddell Motors, Inc. to P.V.Luistro for P5500, no more sales tax was paid.11 In this price of P5500 was included the P413.32representing taxes paid by Liddell & Co. Inc. in the sale to Liddell Motors, Inc. Deducting P413.32representing taxes paid by Liddell & Co., Inc. the price of P5500, the balance of P5,087.68 would havebeen the net selling price of Liddell & Co., Inc. to the general public (had Liddell Motors, Inc. notparticipated and intervened in the sale), and 15% sales tax would have been due. In this transaction,P349.68 in the form of taxes was evaded. All the other transactions (numerous) examined in this light willinevitably reveal that the Government coffers had been deprived of a sizeable amount of taxes.As opined in the case of Gregory v. Helvering, 12 "the legal right of a taxpayer to decrease the amount ofwhat otherwise would be his taxes, or altogether avoid them by means which the law permits, cannot bedoubted." But, as held in another case,13 "where a corporation is a dummy, is unreal or a sham and servesno business purpose and is intended only as a blind, the corporate form may be ignored for the law cannotcountenance a form that is bald and a mischievous fiction."Consistently with this view, the United States Supreme Court 14 held that "a taxpayer may gain advantageof doing business thru a corporation if he pleases, but the revenue officers in proper cases, may disregardthe separate corporate entity where it serves but as a shield for tax evasion and treat the person whoactually may take the benefits of the transactions as the person accordingly taxable."Thus, we repeat: to allow a taxpayer to deny tax liability on the ground that the sales were made throughan other and distinct corporation when it is proved that the latter is virtually owned by the former or thatthey are practically one and the same is to sanction a circumvention of our tax laws. 15C. Tax liability computation: In the Yutivo case16 the same question involving the computation of thealleged deficiency sales tax has been raised. In accordance with our ruling in said case we hold as correctlystated by Judge Nable in his concurring and dissenting opinion on this case, that the deficiency sales taxshould be based on the selling price obtained by Liddell Motors, Inc. to the public AFTER DEDUCTING THETAX ALREADY PAID BY LIDDELL & CO., INC. in its sales to Liddell Motors, Inc.On the imposition of the 50% surcharge by reason of fraud, we see that the transactions between LiddellMotors Inc. and Liddell & Co., Inc. have always been embodied in proper documents, constantly subject toinspection by the tax authorities. Liddell & Co., Inc. have always made a full report of its income andreceipts in its income tax returns.
Paraphrasing our decision in the Yutivo case, we may now say, in filing its return on the basis of its sales toLiddell Motors, Inc. and not on those by the latter to the public, it cannot be held that the Liddell & Co., Inc.deliberately made a false return for the purpose of defrauding the government of its revenue, and shouldsuffer a 50% surcharge. But penalty for late payment (25%) should be imposed.In view of the foregoing, the decision appealed from is hereby modified: Liddell & Co., Inc. is declared liableonly for the amount of P426,811.67 with 25% surcharge for late payment and 6% interest thereon from thetime the judgment becomes final.As it appears that, during the pendency of this litigation appellant paid under protest to the Governmentthe total amount assessed by the Collector, the latter is hereby required to return the excess to thepetitioner. No costs.Padilla, Labrador, Concepcion, Reyes, J.B.L., Barrera, Paredes, Dizon, De Leon and Natividad, JJ., concur.
SECOND DIVISION
DECISION
Before us is a petition for review of the Decision [1] of the Court of Appeals (CA) in CA-G.R. CV No.54201 affirming in toto that of the Regional Trial Court (RTC) in Civil Case No. 90-237 for specificperformance; and the Resolution dated January 11, 2002 denying the motion for reconsideration thereof.
In 1979-1980, respondent JRB Realty, Inc. built a nine-storey building, named Blanco Center, on itsparcel of land located at 119 Alfaro St., Salcedo Village, Makati City. An air conditioning system was neededfor the Blanco Law Firm housed at the second floor of the building. On March 13, 1980, the respondentsExecutive Vice-President, Jose R. Blanco, accepted the contract quotation of Mr. A.G. Morrison, President ofAircon and Refrigeration Industries, Inc. (Aircon), for two (2) sets of Fedders Adaptomatic 30,000 kcal(Code: 10-TR) air conditioning equipment with a net total selling price of P99,586.00.[2] Thereafter, two (2)brand new packaged air conditioners of 10 tons capacity each to deliver 30,000 kcal or 120,000BTUH[3] were installed by Aircon. When the units with rotary compressors were installed, they could notdeliver the desired cooling temperature. Despite several adjustments and corrective measures, therespondent conceded that Fedders Air Conditioning USAs technology for rotary compressors for bigcapacity conditioners like those installed at the Blanco Center had not yet been perfected. The partiesthereby agreed to replace the units with reciprocating/semi-hermetic compressors instead. In a Letterdated March 26, 1981,[4] Aircon stated that it would be replacing the units currently installed with new onesusing rotary compressors, at the earliest possible time. Regrettably, however, it could not specify a datewhen delivery could be effected.TempControl Systems, Inc. (a subsidiary of Aircon until 1987) undertook the maintenance of theunits, inclusive of parts and services. In October 1987, the respondent learned, through newspaper ads,[5]that Maxim Industrial and Merchandising Corporation (Maxim, for short) was the new and exclusivelicensee of Fedders Air Conditioning USA in the Philippines for the manufacture, distribution, sale,installation and maintenance of Fedders air conditioners. The respondent requested that Maxim honor theobligation of Aircon, but the latter refused. Considering that the ten-year period of prescription was fastapproaching, to expire on March 13, 1990, the respondent then instituted, on January 29, 1990, an actionfor specific performance with damages against Aircon & Refrigeration Industries, Inc., Fedders AirConditioning USA, Inc., Maxim Industrial & Merchandising Corporation and petitioner Jardine Davies, Inc.[6]The latter was impleaded as defendant, considering that Aircon was a subsidiary of the petitioner. Therespondent prayed that judgment be rendered, as follows:
1. Ordering the defendants to jointly and severally at their account and expensedeliver, install and place in operation two brand new units of each 10-tons capacityFedders unitary packaged air conditioners with Fedders USAs technology perfected rotarycompressors to always deliver 30,000 kcal or 120,000 BTUH to the second floor of theBlanco Center building at 119 Alfaro St., Salcedo Village, Makati, Metro Manila;
2. Ordering defendants to jointly and severally reimburse plaintiff not only the sumsof P415,118.95 for unsaved electricity from 21 st October 1981 to 7th January 1990and P99,287.77 for repair costs of the two service units from 7 th March 1987 to 11th January1990, with legal interest thereon from the filing of this Complaint until fully reimbursed,but also like unsaved electricity costs and like repair costs therefrom until Prayer No. 1above shall have been complied with;
4. Granting plaintiff such other and further relief as shall be just and equitable inthe premises.[7]
Of the four defendants, only the petitioner filed its Answer. The court did not acquire jurisdictionover Aircon because the latter ceased operations, as its corporate life ended on December 31, 1986.[8]Upon motion, defendants Fedders Air Conditioning USA and Maxim were declared in default. [9]On May 17, 1996, the RTC rendered its Decision, the dispositive portion of which reads:
1.
To deliver, install and place into operation the two (2) brand new unitsof Fedders unitary packaged airconditioning units each of 10 tons capacitywith rotary compressors to deliver 30,000 kcal or 120,000 BTUH to thesecond floor of the Blanco Center building, or to pay plaintiff the currentprice for two such units;
2.
3.
4.
Cost of suit.[10]
The petitioner filed its notice of appeal with the CA, alleging that the trial court erred in holding itliable because it was not a party to the contract between JRB Realty, Inc. and Aircon, and that it had apersonality separate and distinct from that of Aircon.On March 23, 2000, the CA affirmed the trial courts ruling in toto; hence, this petition.
II.ASSUMING ARGUENDO THAT AIRCON MAY BE CONSIDERED AS JARDINES MERE ALTER EGO,THE COURT OF APPEALS ERRED IN NOT DECLARING AIRCONS OBLIGATION TO DELIVER THETWO (2) AIRCONDITIONING UNITS TO JRB AS HAVING BEEN SUBSTANTIALLY COMPLIEDWITH IN GOOD FAITH.
III.ASSUMING ARGUENDO THAT AIRCON MAY BE CONSIDERED AS JARDINES MERE ALTER EGO,THE COURT OF APPEALS ERRED IN NOT DECLARING JRBS CAUSES OF ACTION AS HAVINGBEEN BARRED BY LACHES.IV.ASSUMING ARGUENDO THAT AIRCON MAY BE CONSIDERED AS JARDINES MERE ALTER EGO,THE COURT OF APPEALS ERRED IN FINDING JRB ENTITLED TO RECOVER ALLEGED UNSAVEDELECTRICITY EXPENSES.
V.THE COURT OF APPEALS ERRED IN HOLDING JARDINE LIABLE TO PAY ATTORNEYS FEES.VI.THE COURT OF APPEALS ERRED IN NOT HOLDING JRB LIABLE TO JARDINE FOR DAMAGES. [11]
It is the well-settled rule that factual findings of the trial court, as affirmed by the CA, are accordedhigh respect, even finality at times. However, considering that the factual findings of the CA and the RTCwere based on speculation and conjectures, unsupported by substantial evidence, the Court finds that theinstant case falls under one of the excepted instances. There is, thus, a need to correct the error.
The trial court ruled that Aircon was a subsidiary of the petitioner, and concluded, thus:
Plaintiffs documentary evidence shows that at the time it contracted with Aircon onMarch 13, 1980 (Exhibit D) and on the date the revised agreement was reached on March26, 1981, Aircon was a subsidiary of Jardine. The phrase A subsidiary of Jardine Davies, Inc.was printed on Aircons letterhead of its March 13, 1980 contract with plaintiff (Exhibit D-1),as well as the Aircons letterhead of Jardines Director and Senior Vice-President A.G.Morrison and Aircons President in his March 26, 1981 letter to plaintiff (Exhibit J-2)confirming the revised agreement. Aircons newspaper ads of April 12 and 26, 1981 and apress release on August 30, 1982 (Exhibits E, F and L) also show that defendant Jardinepublicly represented Aircon to be its subsidiary.
Records from the Securities and Exchange Commission (SEC) also reveal that as perJardines December 31, 1986 and 1985 Financial Statements that The company acts asgeneral manager of its subsidiaries (Exhibit P). Jardines Consolidated Balance Sheet as ofDecember 31, 1979 filed with the SEC listed Aircon as its subsidiary by owning 94.35% ofAircon (Exhibit P-1). Also, Aircons reportorial General Information Sheet as of April 1980and April 1981 filed with the SEC show that Jardine was 94.34% owner of Aircon (Exhibits Qand R) and that out of seven members of the Board of Directors of Aircon, four (4) are alsoof Jardine.
The foregoing circumstances provide justifiable basis for this Court to disregard thefiction of corporate entity and treat defendant Aircon as part of the instrumentality of codefendant Jardine.[12]
The respondent court arrived at the same conclusion basing its ruling on the following documents,to wit:
(a)
(c) Letter dated March 26, 1981 of A.G. Morrison, President of Aircon, to Atty. J.R.Blanco (Exh. J);
(d) News items of Bulletin Today dated August 30, 1982 (Exh. L);
(e) Balance Sheet of Jardine Davies, Inc. as of December 31, 1979 listing Aircon asone of its subsidiaries (Exh. P);(f) Financial Statement of Aircon as of December 31, 1982 and 1981 (Exh. S);
(g) Financial Statement of Aircon as of December 31, 1981 (Exh. S-1). [13]
Applying the doctrine of piercing the veil of corporate fiction, both the respondent and trial courtsconveniently held the petitioner liable for the alleged omissions of Aircon, considering that the latter wasits instrumentality or corporate alter ego. The petitioner is now before us, reiterating its defense ofseparateness, and the fact that it is not a party to the contract.
While it is true that Aircon is a subsidiary of the petitioner, it does not necessarily follow thatAircons corporate legal existence can just be disregarded. In Velarde v. Lopez, Inc.,[17] the Courtcategorically held that a subsidiary has an independent and separate juridical personality, distinct fromthat of its parent company; hence, any claim or suit against the latter does not bind the former, and viceversa. In applying the doctrine, the following requisites must be established: (1) control, not merelymajority or complete stock control; (2) such control must have been used by the defendant to commitfraud or wrong, to perpetuate the violation of a statutory or other positive legal duty, or dishonest acts incontravention of plaintiffs legal rights; and (3) the aforesaid control and breach of duty must proximatelycause the injury or unjust loss complained of.[18]
The records bear out that Aircon is a subsidiary of the petitioner only because the latter acquiredAircons majority of capital stock. It, however, does not exercise complete control over Aircon; nowhere canit be gathered that the petitioner manages the business affairs of Aircon. Indeed, no managementagreement exists between the petitioner and Aircon, and the latter is an entirely different entity from thepetitioner.[19]
Jardine Davies, Inc., incorporated as early as June 28, 1946, [20] is primarily a financial and tradingcompany. Its Articles of Incorporation states among many others that the purposes for which the saidcorporation was formed, are as follows:
(b) Upon complying with the requirements of law applicable thereto, to act as agentsof companies and underwriters doing and engaging in any and all kinds of insurancebusiness.[21]
On the other hand, Aircon, incorporated on December 27, 1952, [22] is a manufacturing firm. ItsArticles of Incorporation states that its purpose is mainly -
The existence of interlocking directors, corporate officers and shareholders, which the respondentcourt considered, is not enough justification to pierce the veil of corporate fiction, in the absence of fraudor other public policy considerations.[24] But even when there is dominance over the affairs of thesubsidiary, the doctrine of piercing the veil of corporate fiction applies only when such fiction is used todefeat public convenience, justify wrong, protect fraud or defend crime. [25] To warrant resort to thisextraordinary remedy, there must be proof that the corporation is being used as a cloak or cover for fraudor illegality, or to work injustice. [26] Any piercing of the corporate veil has to be done with caution. [27] Thewrongdoing must be clearly and convincingly established. It cannot just be presumed. [28]
In the instant case, there is no evidence that Aircon was formed or utilized with the intention ofdefrauding its creditors or evading its contracts and obligations. There was nothing fraudulent in the actsof Aircon in this case. Aircon, as a manufacturing firm of air conditioners, complied with its obligation ofproviding two air conditioning units for the second floor of the Blanco Center in good faith, pursuant to itscontract with the respondent. Unfortunately, the performance of the air conditioning units did not satisfythe respondent despite several adjustments and corrective measures. In a Letter [29] dated October 22,1980, the respondent even conceded that Fedders Air Conditioning USA has not yet perhaps perfected itstechnology of rotary compressors, and agreed to change the compressors with the semi-hermetic type.Thus, Aircon substituted the units with serviceable ones which delivered the cooling temperature neededfor the law office. After enjoying ten (10) years of its cooling power, respondent cannot now complainabout the performance of these units, nor can it demand a replacement thereof.
Moreover, it was reversible error to award the respondent the amount of P556,551.55 representingthe alleged 30% unsaved electricity costs and P185,951.67 as maintenance cost without showing anybasis for such award. To justify a grant of actual or compensatory damages, it is necessary to prove with areasonable degree of certainty, premised upon competent proof and on the best evidence obtainable bythe injured party, the actual amount of loss. [30] The respondent merely based its cause of action on Airconsalleged representation that Fedders air conditioners with rotary compressors can save as much as 30% onelectricity compared to other brands. Offered in evidence were newspaper advertisements published onApril 12 and 26, 1981. The respondent then recorded its electricity consumption from October 21, 1981 upto April 3, 1995 and computed 30% thereof, which amounted to P556,551.55. The Court rules that thisamount is highly speculative and merely hypothetical, and for which the petitioner can not be heldaccountable.
First. The respondent merely relied on the newspaper advertisements showing the Fedders windowtype air conditioners, which are far different from the big capacity air conditioning units installed at BlancoCenter.
Second. After such print advertisements, the respondent informed Aircon that it was going to installan electric meter to register its electric consumption so as to determine the electric costs not saved by thepresently installed units with semi-hermetic compressors. Contrary to the allegations of the respondentthat this was in pursuance to their Revised Agreement, no proof was adduced that Aircon agreed to therespondents proposition. It was a unilateral act on the part of the respondent, which Aircon did not obligeor commit itself to pay.
Third. Needless to state, the amounts computed are mere estimates representing the respondentsself-serving claim of unsaved electricity cost, which is too speculative and conjectural to meritconsideration. No other proofs, reports or bases of comparison showing that Fedders Air Conditioning USAcould indeed cut down electricity cost by 30% were adduced.
Likewise, there is no basis for the award of P185,951.67 representing maintenance cost. Therespondent merely submitted a schedule[31] prepared by the respondents accountant, listing the allegedrepair costs from March 1987 up to June 1994. Such evidence is self-serving and can not also be given
probative weight, considering that there are no proofs of receipts, vouchers, etc., which would substantiatethe amounts paid for such services. Absent any more convincing proof, the Court finds that therespondents claims are without basis, and cannot, therefore, be awarded.
We sustain the petitioners separateness from that of Aircon in this case. It bears stressing that thepetitioner was never a party to the contract. Privity of contracts take effect only between parties, theirsuccessors-in-interest, heirs and assigns.[32] The petitioner, which has a separate and distinct legalpersonality from that of Aircon, cannot, therefore, be held liable.
IN VIEW OF THE FOREGOING, the petition is GRANTED. The assailed decision of the Court ofAppeals, affirming the decision of the Regional Trial Court is REVERSEDand SET ASIDE. The complaint ofthe respondent is DISMISSED. Costs against the respondent.
SO ORDERED.
THE COURT OF APPEALS PALPABLY ERRED IN ALLOWING THE TRIAL COURT TO ISSUE IN EXCESS ORLACK OF JURISDICTION A WRIT OF PRELIMINARY INJUNCTION OVER AND BEYOND WHAT WASPRAYED FOR IN THE COMPLAINT A QUO CONTRARY TO CHIEF OF STAFF, AFP VS. GUADIZ JR., 101SCRA 827.2Petitioner prays, inter alia, that the Court of Appeals' Decision dated March 27, 2000 and the trial court'sOrders dated June 30, 1999 and October 4, 1999 be set aside and the dismissal of the complaint in theinstant case.3In their Comment, respondents argue that even assuming arguendo that petitioner and PNB-IFL are twoseparate entities, petitioner is still the party-in-interest in the application for preliminary injunction becauseit is tasked to commit acts of foreclosing respondents' properties. 4 Respondents maintain that the entirecredit facility is void as it contains stipulations in violation of the principle of mutuality of contracts. 5 Inaddition, respondents justified the act of the court a quo in applying the doctrine of "Piercing the Veil ofCorporate Identity" by stating that petitioner is merely an alter ego or a business conduit of PNB-IFL.6The petition is impressed with merit.Respondents, in their complaint, anchor their prayer for injunction on alleged invalid provisions of thecontract:GROUNDSITHE DETERMINATION OF THE INTEREST RATES BEING LEFT TO THE SOLE DISCRETION OF THEDEFENDANT PNB CONTRAVENES THE PRINCIPAL OF MUTUALITY OF CONTRACTS.IITHERE BEING A STIPULATION IN THE LOAN AGREEMENT THAT THE RATE OF INTEREST AGREEDUPON MAY BE UNILATERALLY MODIFIED BY DEFENDANT, THERE WAS NO STIPULATION THAT THERATE OF INTEREST SHALL BE REDUCED IN THE EVENT THAT THE APPLICABLE MAXIMUM RATE OFINTEREST IS REDUCED BY LAW OR BY THE MONETARY BOARD. 7Based on the aforementioned grounds, respondents sought to enjoin and restrain PNB from the foreclosureand eventual sale of the property in order to protect their rights to said property by reason of void creditfacilities as bases for the real estate mortgage over the said property. 8The contract questioned is one entered into between respondent and PNB-IFL, not PNB. In their complaint,respondents admit that petitioner is a mere attorney-in-fact for the PNB-IFL with full power and authorityto, inter alia, foreclose on the properties mortgaged to secure their loan obligations with PNB-IFL. In otherwords, herein petitioner is an agent with limited authority and specific duties under a special power ofattorney incorporated in the real estate mortgage. It is not privy to the loan contracts entered into byrespondents and PNB-IFL.The issue of the validity of the loan contracts is a matter between PNB-IFL, the petitioner's principal andthe party to the loan contracts, and the respondents. Yet, despite the recognition that petitioner is a mereagent, the respondents in their complaint prayed that the petitioner PNB be ordered to re-compute therescheduling of the interest to be paid by them in accordance with the terms and conditions in thedocuments evidencing the credit facilities, and crediting the amount previously paid to PNB by hereinrespondents.9Clearly, petitioner not being a part to the contract has no power to re-compute the interest rates set forthin the contract. Respondents, therefore, do not have any cause of action against petitioner.The trial court, however, in its Order dated October 4, 1994, ruled that since PNB-IFL, is a wholly ownedsubsidiary of defendant Philippine National Bank, the suit against the defendant PNB is a suit against PNB-
IFL.10 In justifying its ruling, the trial court, citing the case of Koppel Phil. Inc. vs. Yatco,11 reasoned that thecorporate entity may be disregarded where a corporation is the mere alter ego, or business conduit of aperson or where the corporation is so organized and controlled and its affairs are so conducted, as to makeit merely an instrumentality, agency, conduit or adjunct of another corporation. 12We disagree.The general rule is that as a legal entity, a corporation has a personality distinct and separate from itsindividual stockholders or members, and is not affected by the personal rights, obligations andtransactions of the latter.13 The mere fact that a corporation owns all of the stocks of another corporation,taken alone is not sufficient to justify their being treated as one entity. If used to perform legitimatefunctions, a subsidiary's separate existence may be respected, and the liability of the parent corporationas well as the subsidiary will be confined to those arising in their respective business. The courts may inthe exercise of judicial discretion step in to prevent the abuses of separate entity privilege and pierce theveil of corporate entity.We find, however, that the ruling in Koppel finds no application in the case at bar. In said case, this Courtdisregarded the separate existence of the parent and the subsidiary on the ground that the latter wasformed merely for the purpose of evading the payment of higher taxes. In the case at bar, respondents failto show any cogent reason why the separate entities of the PNB and PNB-IFL should be disregarded.While there exists no definite test of general application in determining when a subsidiary may be treatedas a mere instrumentality of the parent corporation, some factors have been identified that will justify theapplication of the treatment of the doctrine of the piercing of the corporate veil. The case of Garrett vs.Southern Railway Co.14 is enlightening. The case involved a suit against the Southern Railway Company.Plaintiff was employed by Lenoir Car Works and alleged that he sustained injuries while working for Lenoir.He, however, filed a suit against Southern Railway Company on the ground that Southern had acquired theentire capital stock of Lenoir Car Works, hence, the latter corporation was but a mere instrumentality ofthe former. The Tennessee Supreme Court stated that as a general rule the stock ownership alone by onecorporation of the stock of another does not thereby render the dominant corporation liable for the torts ofthe subsidiary unless the separate corporate existence of the subsidiary is a mere sham, or unless thecontrol of the subsidiary is such that it is but an instrumentality or adjunct of the dominant corporation.Said Court then outlined the circumstances which may be useful in the determination of whether thesubsidiary is but a mere instrumentality of the parent-corporation:The Circumstance rendering the subsidiary an instrumentality. It is manifestly impossible tocatalogue the infinite variations of fact that can arise but there are certain common circumstanceswhich are important and which, if present in the proper combination, are controlling.These are as follows:its incorporation.(e) The subsidiary has grossly inadequate capital.(f) The parent corporation pays the salaries and other expenses or losses of the subsidiary.(g) The subsidiary has substantially no business except with the parent corporation or no assetsexcept those conveyed to or by the parent corporation.
(h) In the papers of the parent corporation or in the statements of its officers, the subsidiary isdescribed as a department or division of the parent corporation, or its business or financialresponsibility is referred to as the parent corporation's own.(i) The parent corporation uses the property of the subsidiary as its own.(j) The directors or executives of the subsidiary do not act independently in the interest of thesubsidiary but take their orders from the parent corporation.(k) The formal legal requirements of the subsidiary are not observed.The Tennessee Supreme Court thus ruled:In the case at bar only two of the eleven listed indicia occur, namely, the ownership of most of thecapital stock of Lenoir by Southern, and possibly subscription to the capital stock of Lenoir. . . Thecomplaint must be dismissed.Similarly, in this jurisdiction, we have held that the doctrine of piercing the corporate veil is an equitabledoctrine developed to address situations where the separate corporate personality of a corporation isabused or used for wrongful purposes. The doctrine applies when the corporate fiction is used to defeatpublic convenience, justify wrong, protect fraud or defend crime, or when it is made as a shield to confusethe legitimate issues, or where a corporation is the mere alter ego or business conduit of a person, orwhere the corporation is so organized and controlled and its affairs are so conducted as to make it merelyan instrumentality, agency, conduit or adjunct of another corporation. 15In Concept Builders, Inc. v. NLRC,16 we have laid the test in determining the applicability of the doctrine ofpiercing the veil of corporate fiction, to wit:1. Control, not mere majority or complete control, but complete domination, not only of finances butof policy and business practice in respect to the transaction attacked so that the corporate entity asto this transaction,3. The aforesaid control and breach of duty must proximately cause the injury or unjust losscomplained of.The absence of any one of these elements prevents "piercing the corporate veil." In applying the"instrumentality" or "alter ego" doctrine, the courts are concerned with reality and not form, withhow the corporation operated and the individual defendant's relationship to the operation. 17Aside from the fact that PNB-IFL is a wholly owned subsidiary of petitioner PNB, there is no showing of theindicative factors that the former corporation is a mere instrumentality of the latter are present. Neither isthere a demonstration that any of the evils sought to be prevented by the doctrine of piercing thecorporate veil exists. Inescapably, therefore, the doctrine of piercing the corporate veil based on the alterego or instrumentality doctrine finds no application in the case at bar.In any case, the parent-subsidiary relationship between PNB and PNB-IFL is not the significant legalrelationship involved in this case since the petitioner was not sued because it is the parent company ofPNB-IFL. Rather, the petitioner was sued because it acted as an attorney-in-fact of PNB-IFL in initiating theforeclosure proceedings. A suit against an agent cannot without compelling reasons be considered a suitagainst the principal. Under the Rules of Court, every action must be prosecuted or defended in the nameof the real party-in-interest, unless otherwise authorized by law or these Rules. 18 In mandatory terms, theRules require that "parties-in-interest without whom no final determination can be had, an action shall bejoined either as plaintiffs or defendants."19 In the case at bar, the injunction suit is directed only against theagent, not the principal.
Anent the issuance of the preliminary injunction, the same must be lifted as it is a mere provisional remedybut adjunct to the main suit.20 A writ of preliminary injunction is an ancillary or preventive remedy that mayonly be resorted to by a litigant to protect or preserve his rights or interests and for no other purposeduring the pendency of the principal action. The dismissal of the principal action thus results in the denialof the prayer for the issuance of the writ. Further, there is no showing that respondents are entitled to theissuance of the writ. Section 3, Rule 58, of the 1997 Rules of Civil Procedure provides:SECTION 3. Grounds for issuance of preliminary injunction. A preliminary injunction may begranted when it is established:(a) That the applicant is entitled to the relief demanded, and the whole or part of such reliefconsists in restraining the commission or continuance of the act or acts complained of, or inrequiring the performance of an act or acts, either for a limited period or perpetually,(b) That the commission, continuance or non-performance of the acts or acts complained of duringthe litigation would probably work injustice to the applicant; or(c) That a party, court, agency or a person is doing, threatening, or is attempting to do, or isprocuring or suffering to be done, some act or acts probably in violation of the rights of theapplicant respecting the subject of the action or proceeding, and tending to render the judgmentineffectual.Thus, an injunctive remedy may only be resorted to when there is a pressing necessity to avoid injuriousconsequences which cannot be remedied under any standard compensation. 21 Respondents do not denytheir indebtedness. Their properties are by their own choice encumbered by real estate mortgages. Uponthe non-payment of the loans, which were secured by the mortgages sought to be foreclosed, themortgaged properties are properly subject to a foreclosure sale. Moreover, respondents questioned thealleged void stipulations in the contract only when petitioner initiated the foreclosure proceedings. Clearly,respondents have failed to prove that they have a right protected and that the acts against which the writis to be directed are violative of said right.22 The Court is not unmindful of the findings of both the trialcourt and the appellate court that there may be serious grounds to nullify the provisions of the loanagreement. However, as earlier discussed, respondents committed the mistake of filing the case againstthe wrong party, thus, they must suffer the consequences of their error.All told, respondents do not have a cause of action against the petitioner as the latter is not privy to thecontract the provisions of which respondents seek to declare void. Accordingly, the case before theRegional Trial Court must be dismissed and the preliminary injunction issued in connection therewith, mustbe lifted.IN VIEW OF THE FOREGOING, the petition is hereby GRANTED. The assailed decision of the Court ofAppeals is hereby REVERSED. The Orders dated June 30, 1999 and October 4, 1999 of the Regional TrialCourt of Makati, Branch 147 in Civil Case No. 99-1037 are hereby ANNULLED and SET ASIDE and thecomplaint in said case DISMISSED.SO ORDERED.Puno, Pardo and Santiago, JJ ., concur.Davide, Jr., C .J ., on official leave.
Petitioners,
- versus -
Respondents.
Present:
YNARES-SANTIAGO, J.,Chairperson,CARPIO,*CHICO-NAZARIO,
NACHURA, andPERALTA, JJ.
Promulgated:
NACHURA, J.:
Before us are two consolidated petitions assailing the Court of Appeals (CA) Decision [1] dated June 3, 2005and its Resolution[2] dated December 7, 2005 in CA-G.R. SP No. 80599.
In G.R. No. 170689, the Pantranco Employees Association (PEA) and Pantranco RetrenchedEmployees Association (PANREA) pray that the CA decision be set aside and a new one be entered,declaring the Philippine National Bank (PNB) and PNB Management and Development Corporation (PNBMadecor) jointly and solidarily liable for the P722,727,150.22 National Labor Relations Commission (NLRC)judgment in favor of the Pantranco North Express, Inc. (PNEI) employees; [3] while in G.R. No. 170705, PNBprays that the auction sale of the Pantranco properties be declared null and void. [4]
The facts of the case, as found by the CA, [5] and established in Republic of the Phils. v. NLRC, [6] PantrancoNorth Express, Inc. v. NLRC,[7] and PNB MADECOR v. Uy,[8] follow:
The Gonzales family owned two corporations, namely, the PNEI and Macris Realty Corporation (Macris).PNEI provided transportation services to the public, and had its bus terminal at the corner of Quezon andRoosevelt Avenues in Quezon City. The terminal stood on four valuable pieces of real estate (known asPantranco properties) registered under the name of Macris. [9] The Gonzales family later incurred hugefinancial losses despite attempts of rehabilitation and loan infusion. In March 1975, their creditors tookovermerged with the National Warehousing Corporation (Nawaco) to form the new PNB subsidiary, the PNBMadecor.In 1985, NIDC sold PNEI to North Express Transport, Inc. (NETI), a company owned by GregorioAraneta III. In 1986, PNEI was among the several companies placed under sequestration by the PresidentialCommission on Good Government (PCGG) shortly after the historic events in EDSA. In January 1988, PCGGlifted the sequestration order to pave the way for the sale of PNEI back to the private sector through theAsset Privatization Trust (APT). APT thus took over the management of PNEI.
In 1992, PNEI applied with the Securities and Exchange Commission (SEC) for suspension ofpayments. A management committee was thereafter created which recommended to the SEC the sale ofthe company through privatization. As a cost-saving measure, the committee likewise suggested theretrenchment of several PNEI employees. Eventually, PNEI ceased its operation. Along with the cessation ofbusiness came the various labor claims commenced by the former employees of PNEI where the latterobtained favorable decisions.
On July 5, 2002, the Labor Arbiter issued the Sixth Alias Writ of Execution [10] commanding the NLRCSheriffs to levy on the assets of PNEI in order to satisfy theP722,727,150.22 due its former employees, asfull and final satisfaction of the judgment awards in the labor cases. The sheriffs were likewise instructed toproceed against PNB, PNB-Madecor and Mega Prime. [11] In implementing the writ, the sheriffs levied uponthe four valuable pieces of real estate located at the corner of Quezon and Roosevelt Avenues, on whichthe former Pantranco Bus Terminal stood. These properties were covered by Transfer Certificate of Title(TCT) Nos. 87881-87884, registered under the name of PNB-Madecor. [12]Subsequently, Notice of Sale of theforegoing real properties was published in the newspaper and the sale was set on July 31, 2002. Havingbeen notified of the auction sale, motions to quash the writ were separately filed by PNB-Madecor andMega Prime, and PNB. They likewise filed their Third-Party Claims. [13] PNB-Madecor anchored its motion onits right as the registered owner of the Pantranco properties, and Mega Prime as the successor-in-interest.For its part, PNB sought the nullification of the writ on the ground that it was not a party to the labor case.[14]InitsThird-PartyClaim,PNBallegedthatPNBMadecor was indebted to the former and that the Pantranco propertieswould answer for such debt. As such, the scheduled auction sale of the aforesaid properties was not legallyin order.[15]
On September 10, 2002, the Labor Arbiter declared that the subject Pantranco properties were owned byPNB-Madecor. It being a corporation with a distinct and separate personality, its assets could not answerfor the liabilities of PNEI. Considering, however, that PNB-Madecor executed a promissory note in favor ofPNEI for P7,884,000.00, the writ of execution to the extent of the said amount was concerned wasconsidered valid.[16]
PNBs third-party claim to nullify the writ on the ground that it has an interest in the Pantranco propertiesbeing a creditor of PNB-Madecor, on the other hand, was denied because it only had an inchoate interest inthe properties.[17]
The dispositive portion of the Labor Arbiters September 10, 2002 Resolution is quoted hereunder:
WHEREFORE, the Third Party Claim of PNB Madecor and/or Mega Prime Holdings, Inc. ishereby GRANTED and concomitantly the levies made by the sheriffs of the NLRC on theproperties of PNB Madecor should be as it (sic) is hereby LIFTED subject to the payment byPNB Madecor to the complainants the amount of P7,884,000.00.
The Motion to Quash and Third Party Claim of PNB is hereby DENIED.
The Motion to Quash of PNB Madecor and Mega Prime Holdings, Inc. is hereby PARTIALLYGRANTED insofar as the amount of the writ exceeds P7,884,000.00.
The Motion for Recomputation and Examination of Judgment Awards is hereby DENIED forwant of merit.
The Motion to Expunge from the Records claimants/complainants Opposition dated August 3,2002 is hereby DENIED for lack of merit.
SO ORDERED.[18]
On appeal to the NLRC, the same was denied and the Labor Arbiters disposition was affirmed.[19]Specifically, the NLRC concluded as follows:
(1)PNB-Madecor and Mega Prime contended that it would be impossible forthem to comply with the requirement of the labor arbiter to pay to the PNEI employees theamount of P7.8 million as a condition to the lifting of the levy on the properties, since thecredit was already garnished by Gerardo Uy and other creditors of PNEI. The NLRC found noevidence that Uy had satisfied his judgment from the promissory note, and opined that evenif the credit was in custodia legis, the claim of the PNEI employees should enjoy preferenceunder the Labor Code.
(2)The PNEI employees contested the finding that PNB-Madecor wasindebted to the PNEI for only P7.8 million without considering the accrual of interest. But theNLRC said that there was no evidence that demand was made as a basis for reckoninginterest.
(3)The PNEI employees further argued that the labor arbiter may notproperly conclude from a decision of Judge Demetrio Macapagal Jr. of the RTC of Quezon Citythat PNB-Madecor was the owner of the properties as his decision was reconsidered by thenext presiding judge, nor from a decision of the Supreme Court that PNEI was a mere lesseeof the properties, the fact being that the transfer of the properties to PNB-Madecor was doneto avoid satisfaction of the claims of the employees with the NLRC and that as a result of acivil case filed by Mega Prime, the subsequent sale of the properties by PNB to Mega Primewas rescinded. The NLRC pointed out that while the Macapagal decision was set aside byJudge Bruselas and hence, his findings could not be invoked by the labor arbiter, the titles ofPNB-Madecor are conclusive and there is no evidence that PNEI had ever been an owner. TheSupreme Court had observed in its decision that PNEI owed back rentals of P8.7 million toPNB-Madecor.
(4)The PNEI employees faulted the labor arbiter for not finding that PNEI,PNB, PNB-Madecor and Mega Prime were all jointly and severally liable for their claims. TheNLRC underscored the fact that PNEI and Macris were subsidiaries of NIDC and had passedthrough and were under the Asset Privatization Trust (APT) when the labor claimsaccrued. The labor arbiter was correct in not granting PNBs third-party claim because at thetime the causes of action accrued, the PNEI was managed by a management committeeappointed by the PNB as the new owner of PNRI (sic) and Macris through a deed ofassignment or transfer of ownership. The NLRC says at length that the same is not true withPNB-Madecor which is now the registered owner of the properties. [20]
The parties separate motions for reconsideration were likewise denied. [21] Thereafter, the matter waselevated to the CA by PANREA, PEA-PTGWO and the Pantranco Association of Concerned Employees. Thelatter group, however, later withdrew its petition. The former employees petition was docketed as CA-G.R.SP No. 80599.
PNB-Madecor and Mega Prime likewise filed their separate petition before the CA which was docketed asCA-G.R. SP No. 80737, but the same was dismissed.[22]
In view of the P7,884,000.00 debt of PNB-Madecor to PNEI, on June 23, 2004, an auction sale wasconducted over the Pantranco properties to satisfy the claim of the PNEI employees, wherein CPAR Realtywas adjudged as the highest bidder.[23]On June 3, 2005, the CA rendered the assailed decision affirming the NLRC resolutions.
The appellate court pointed out that PNB, PNB-Madecor and Mega Prime are corporations with personalitiesseparate and distinct from PNEI. As such, there being no cogent reason to pierce the veil of corporatefiction, the separate personalities of the above corporations should be maintained. The CA added that thePantranco properties were never owned by PNEI; rather, their titles were registered under the name ofPNB-Madecor. If PNB and PNB-Madecor could not answer for the liabilities of PNEI, with more reason shouldMega Prime not be held liable being a mere successor-in-interest of PNB-Madecor.
Unsatisfied, PEA-PTGWO and PANREA filed their motion for reconsideration; [24] while PNB filed its PartialMotion for Reconsideration.[25] PNB pointed out that PNB-Madecor was made to answer for P7,884,000.00to the PNEI employees by virtue of the promissory note it (PNB-Madecor) earlier executed in favor ofPNEI. PNB, however, questioned the June 23, 2004 auction sale as the P7.8 million debt had already beensatisfied pursuant to this Courts decision in PNB MADECOR v. Uy.[26]
In two separate petitions, PNB and the former PNEI employees come up to this Court assailing the CAdecision and resolution. The former PNEI employees raise the lone error, thus:
The Honorable Court of Appeals palpably departed from the established rules andjurisprudence in ruling that private respondents Pantranco North Express, Inc. (PNEI),Philippine National Bank (PNB), Philippine National Bank Management and DevelopmentCorporation (PNB-MADECOR), Mega Prime Realty and Holdings, Inc. (Mega Prime) are notjointly and severally answerable to theP722,727,150.22 Million NLRC money judgmentawards in favor of the 4,000 individual members of the Petitioners. [28]
They claim that PNB, through PNB-Madecor, directly benefited from the operation of PNEI and hadcomplete control over the funds of PNEI. Hence, they are solidarily answerable with PNEI for the unpaidmoney claims of the employees.[29] Citing A.C. Ransom Labor Union-CCLU v. NLRC,[30] the employees insistthat where the employer corporation ceases to exist and is no longer able to satisfy the judgment awardsin favor of its employees, the owner of the employer corporation should be made jointly and severallyliable.[31] They added that malice or bad faith need not be proven to make the owners liable.
On the other hand, PNB anchors its petition on this sole assignment of error, viz.:
THE AUCTION SALE OF THE PROPERTY COVERED BY TCT NO. 87884 INTENDED TO PARTIALLYSATISFY THE CLAIMS OF FORMER WORKERS OF PNEI IN THE AMOUNT OFP7,884,000.00 (THEAMOUNT OF PNB-MADECORS PROMISSORY NOTE IN FAVOR OF PNEI) IS NOTIN ORDER AS THE SAID PROPERTY IS NOT OWNED BY PNEI. FURTHER, THE SAID PROMISSORYNOTE HAD ALREADY BEEN GARNISHED IN FAVOR OF GERARDO C. UY WHICH LED TO THREE(3) PROPERTIES UNDER THE NAME OF PNB-MADECOR, NAMELY TCT NOS. 87881, 87882 AND
87883, BEING LEVIED AND SOLD ON EXECUTION IN THE PNB-MADECOR VS. UY CASE (363SCRA 128 [2001]) AND GERARDO C. UY VS. PNEI (CIVIL CASE NO. 95-72685, RTC MANILA,BRANCH 38).[32]
PNB insists that the Pantranco properties could no longer be levied upon because the promissory note forwhich the Labor Arbiter held PNB-Madecor liable to PNEI, and in turn to the latters former employees, hadalready been satisfied in favor of Gerardo C. Uy. It added that the properties were in fact awarded to thehighest bidder. Besides, says PNB, the subject properties were not owned by PNEI, hence, the executionsale thereof was not validly effected. [33]
Stripped of the non-essentials, the sole issue for resolution raised by the former PNEI employees iswhether they can attach the properties (specifically the Pantranco properties) of PNB, PNB-Madecor andMega Prime to satisfy their unpaid labor claims against PNEI.
First, the subject property is not owned by the judgment debtor, that is, PNEI. Nowhere in the records wasit shown that PNEI owned the Pantranco properties. Petitioners, in fact, never alleged in any of theirpleadings the fact of such ownership. What was established, instead, in PNB MADECOR v. Uy[34] and PNB v.Mega Prime Realty and Holdings Corporation/Mega Prime Realty and Holdings Corporation v. PNB [35] wasthat the properties were owned by Macris, the predecessor of PNB-Madecor. Hence, they cannot bepursued against by the creditors of PNEI.
We would like to stress the settled rule that the power of the court in executing judgments extendsonly to properties unquestionably belonging to the judgment debtor alone. [36]To be sure, one mans goodsshall not be sold for another mans debts. [37] A sheriff is not authorized to attach or levy on property notbelonging to the judgment debtor, and even incurs liability if he wrongfully levies upon the property of athird person.[38]
Second, PNB, PNB-Madecor and Mega Prime are corporations with personalities separate and distinct fromthat of PNEI. PNB is sought to be held liable because it acquired PNEI through NIDC at the time when PNEIwas suffering financial reverses. PNB-Madecor is being made to answer for petitioners labor claims as theowner of the subject Pantranco properties and as a subsidiary of PNB. Mega Prime is also included forhaving acquired PNBs shares over PNB-Madecor.The general rule is that a corporation has a personality separate and distinct from those of itsstockholders and other corporations to which it may be connected. [39] This is a fiction created by law forconvenience and to prevent injustice.[40] Obviously, PNB, PNB-Madecor, Mega Prime, and PNEI arecorporations with their own personalities. The separate personalities of the first three corporations hadbeen recognized by this Court in PNB v. Mega Prime Realty and Holdings Corporation/Mega Prime Realtyand Holdings Corporation v. PNB [41] where we stated that PNB was only a stockholder of PNB-Madecorwhichformer. Settled is the rule that where one corporation sells or otherwise transfers all its assets to anothercorporation for value, the latter is not, by that fact alone, liable for the debts and liabilities of thetransferor.[42]
Lastly, while we recognize that there are peculiar circumstances or valid grounds that may exist towarrant the piercing of the corporate veil, [43] none applies in the present case whether between PNB andPNEI; or PNB and PNB-Madecor.
Under the doctrine of piercing the veil of corporate fiction, the court looks at the corporation as amere collection of individuals or an aggregation of persons undertaking business as a group, disregardingthe separate juridical personality of the corporation unifying the group. [44] Another formulation of thisdoctrine is that when two business enterprises are owned, conducted and controlled by the same parties,both law and equity will, when necessary to protect the rights of third parties, disregard the legal fictionthat two corporations are distinct entities and treat them as identical or as one and the same. [45]
Whether the separate personality of the corporation should be pierced hinges on obtaining factsappropriately pleaded or proved. However, any piercing of the corporate veil has to be done with caution,albeit the Court will not hesitate to disregard the corporate veil when it is misused or when necessary inthe interest of justice. After all, the concept of corporate entity was not meant to promote unfairobjectives.[46]
As between PNB and PNEI, petitioners want us to disregard their separate personalities, and insistthat because the company, PNEI, has already ceased operations and there is no other way by which thejudgment in favor of the employees can be satisfied, corporate officers can be held jointly and severallyliable with the company. Petitioners rely on the pronouncement of this Court in A.C. Ransom Labor UnionCCLU v. NLRC[47] and subsequent cases.[48]
This reliance fails to persuade. We find the aforesaid decisions inapplicable to the instant case.
For one, in the said cases, the persons made liable after the companys cessation of operations werethe officers and agents of the corporation. The rationale is that, since the corporation is an artificial person,it must have an officer who can be presumed to be the employer, being the person acting in the interest ofthe employer. The corporation, only in the technical sense, is the employer. [49] In the instant case, what isbeing made liable is another corporation (PNB) which acquired the debtor corporation (PNEI).
Moreover, in the recent cases Carag v. National Labor Relations Commission [50] and McLeod v.National Labor Relations Commission,[51] the Court explained the doctrine laid down in AC Ransom relativeto the personal liability of the officers and agents of the employer for the debts of the latter. In ACRansom, the Court imputed liability to the officers of the corporation on the strength of the definition of anemployer in Article 212(c) (now Article 212[e]) of the Labor Code. Under the saidprovision, employer includes any person acting in the interest of an employer, directly or indirectly, butdoes not include any labor organization or any of its officers or agents except when acting as employer. Itwas clarified in Caragand McLeod that Article 212(e) of the Labor Code, by itself, does not make acorporate officer personally liable for the debts of the corporation. It added that the governing law on
personal liability of directors or officers for debts of the corporation is still Section 31 [52] of the CorporationCode.
More importantly, as aptly observed by this Court in AC Ransom, it appears that Ransom, foreseeing thepossibility or probability of payment of backwages to its employees, organizedRosario to replace Ransom,with the latter to be eventually phased out if the strikers win their case. The execution could not beimplemented against Ransom because of the disposition posthaste of its leviable assets evidently in orderto evade its just and due obligations. [53] Hence, the Court sustained the piercing of the corporate veil andmade the officers of Ransom personally liable for the debts of the latter.
Clearly, what can be inferred from the earlier cases is that the doctrine of piercing the corporateveil applies only in three (3) basic areas, namely: 1) defeat of public convenience as when the corporatefiction is used as a vehicle for the evasion of an existing obligation; 2) fraud cases or when the corporateentity is used to justify a wrong, protect fraud, or defend a crime; or 3) alter ego cases, where acorporation is merely a farce since it is a mere alter ego or business conduit of a person, or where thecorporation is so organized and controlled and its affairs are so conducted as to make it merely aninstrumentality, agency, conduit or adjunct of another corporation. [54] In the absence of malice, bad faith,or a specific provision of law making a corporate officer liable, such corporate officer cannot be madepersonally liable for corporate liabilities.[55]
Applying the foregoing doctrine to the instant case, we quote with approval the CA disposition inthis wise:
It would not be enough, then, for the petitioners in this case, the PNEI employees, torest on their laurels with evidence that PNB was the owner of PNEI. Apart from provingownership, it is necessary to show facts that will justify us to pierce the veil of corporatefiction and hold PNB liable for the debts of PNEI. The burden undoubtedly falls on thepetitioners to prove their affirmative allegations. In line with the basic jurisprudentialprinciples we have explored, they must show that PNB was using PNEI as a mere adjunct orinstrumentality or has exploited or misused the corporate privilege of PNEI.
We do not see how the burden has been met. Lacking proof of a nexus apart frommere ownership, the petitioners have not provided us with the legal basis to reach theassets of corporations separate and distinct from PNEI.[56]
Assuming, for the sake of argument, that PNB may be held liable for the debts of PNEI, petitioners stillcannot proceed against the Pantranco properties, the same being owned by PNB-Madecor, notwithstandingthe fact that PNB-Madecor was a subsidiary of PNB. The general rule remains that PNB-Madecor has apersonality separate and distinct from PNB. The mere fact that a corporation owns all of the stocks ofanother corporation, taken alone, is not sufficient to justify their being treated as one entity. If used toperform legitimate functions, a subsidiarys separate existence shall be respected, and the liability of theparent corporation as well as the subsidiary will be confined to those arising in their respective businesses.[57]
In PNB v. Ritratto Group, Inc.,[58] we outlined the circumstances which are useful in thedetermination of whether a subsidiary is but a mere instrumentality of the parent-corporation, to wit:
The parent corporation owns all or most of the capital stock of the subsidiary;
4.5.
The parent corporation subscribes to all the capital stock of the subsidiary orotherwise causes its incorporation;The subsidiary has grossly inadequate capital;
6.
The parent corporation pays the salaries and other expenses or losses of thesubsidiary;
7.
The subsidiary has substantially no business except with the parent corporationor no assets except those conveyed to or by the parent corporation;
8.
In the papers of the parent corporation or in the statements of its officers, thesubsidiary is described as a department or division of the parent corporation, or itsbusiness or financial responsibility is referred to as the parent corporations own;
9.10.11.
The parent corporation uses the property of the subsidiary as its own;The directors or executives of the subsidiary do not act independently in theinterest of the subsidiary, but take their orders from the parent corporation;The formal legal requirements of the subsidiary are not observed.
None of the foregoing circumstances is present in the instant case. Thus, piercing of PNB-Madecorscorporate veil is not warranted. Being a mere successor-in-interest of PNB-Madecor, with more reasonshould no liability attach to Mega Prime.
It has been repeatedly stated that the Pantranco properties which were the subject of execution sale wereowned by Macris and later, the PNB-Madecor. They were never owned by PNEI or PNB. Following our earlierdiscussion on the separate personalities of the different corporations involved in the instant case, the onlyentity which has the right and interest to question the execution sale and the eventual right to annul thesame, if any, is PNB-Madecor or its successor-in-interest. Settled is the rule that proceedings in court mustbe instituted by the real party in interest.A real party in interest is the party who stands to be benefited or injured by the judgment in thesuit, or the party entitled to the avails of the suit. [59] Interest within the meaning of the rule means materialinterest, an interest in issue and to be affected by the decree, as distinguished from mere interest in thequestion involved, or a mere incidental interest. [60] The interest of the party must also be personal and notone based on a desire to vindicate the constitutional right of some third and unrelated party. [61] Realinterest, on the other hand, means a present substantial interest, as distinguished from a mere expectancyor a future, contingent, subordinate, or consequential interest. [62]
Specifically, in proceedings to set aside an execution sale, the real party in interest is the personwho has an interest either in the property sold or the proceeds thereof. Conversely, one who is notinterested or is not injured by the execution sale cannot question its validity. [63]
In justifying its claim against the Pantranco properties, PNB alleges that Mega Prime, the buyer of its entirestockholdings in PNB-Madecor was indebted to it (PNB). Considering that said indebtedness remainsunpaid, PNB insists that it has an interest over PNB-Madecor and Mega Primes assets.
Again, the contention is bereft of merit. While PNB has an apparent interest in Mega Primes assets beingthe creditor of the latter for a substantial amount, its interest remains inchoate and has not yet ripenedinto a present substantial interest, which would give it the standing to maintain an action involving thesubject properties. As aptly observed by the Labor Arbiter, PNB only has an inchoate right to the propertiesof Mega Prime in case the latter would not be able to pay its indebtedness. This is especially true in theinstant case, as the debt being claimed by PNB is secured by the accessory contract of pledge of the entirestockholdings of Mega Prime to PNB-Madecor.[64]
The Court further notes that the Pantranco properties (or a portion thereof ) were sold on execution tosatisfy the unpaid obligation of PNB-Madecor to PNEI. PNB-Madecor was thus made liable to the formerPNEI employees as the judgment debtor of PNEI. It has long been established in PNB-Madecor v. Uy andother similar cases that PNB-Madecor had an unpaid obligation to PNEI amounting to more or less P7million which could be validly pursued by the creditors of the latter. Again, this strengthens the properparties right to question the validity of the execution sale, definitely not PNB.
Besides, the issue of whether PNB has a substantial interest over the Pantranco properties has alreadybeen laid to rest by the Labor Arbiter.[65] It is noteworthy that in its Resolution dated September 10, 2002,the Labor Arbiter denied PNBs Third-Party Claim primarily because PNB only has an inchoate right over thePantranco properties.[66] Such conclusion was later affirmed by the NLRC in its Resolution dated June 30,2003.[67] Notwithstanding said conclusion, PNB did not elevate the matter to the CA via a petition forreview. Hence it is presumed to be satisfied with the adjudication therein. [68] That decision of the NLRC hasbecome final as against PNB and can no longer be reviewed, much less reversed, by this Court. [69] This is inaccord with the doctrine that a party who has not appealed cannot obtain from the appellate court anyaffirmative relief other than the ones granted in the appealed decision. [70]
WHEREFORE, premises considered, the petitions are hereby DENIED for lack of. | https://it.scribd.com/document/295391425/FT1 | CC-MAIN-2020-29 | en | refinedweb |
Limits of the Android Geocoder
Limits of the Android Geocoder
Join the DZone community and get the full member experience.Join For Free
Android provides a Geocoder in the standard APIs which is pretty simple to use, as this code excerpt demonstrates:
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import it.tidalwave.geo.Coordinate;
Context context = ... ;
Coordinate coordinate = ... ;
Geocoder geocoder = new Geocoder(context);
List<Address> addresses = geocoder.getFromLocation(coordinate.getLatitude(), coordinate.getLongitude(), 100);
Unfortunately, tests on the field proved it to be almost useless, at least in my typical scenarios. The problem is that it seems that a single geocoder service is available (and of course it is the one provided by Google by means of its web services) and the following problems arise:
- I've repeated this a number of times in the past years: the "always connected" thing is a myth. Italy's mobile network coverage is excellent and just an epsilon below the 100%. Still, in the countryside, or in a dense wood, it's easy to find places where the radio signal is so weak that the connection doesn't work or takes a very long time to transfer data. Usually it's a matter of moving around to pick a better signal, but this is not the thing you want to do while observing birds. Thus, I need to have a geocoder capable to resolve at least a subset of common locations without requiring a network connection.
- The quality of data provided by the Google geocoder in my country is very variable. Sometimes it's able to pick even the name of the nearest, small fraction of houses around; other times it just resorts to returning "Province of XYZ", which is too vague. Being able to aggregate multiple results from different geocoders (e.g. GeoNames, or Yahoo!) might resolve the issue or at least improve things here.
- I've realized that for my purposes I also need to rely on user-provided location names. For a birder, the indication "Observatory #5 in the FooBar Wildlife Sanctuary" might be extremely useful, but I don't think it's even possible to have the Google geocoder capable to resolve it (while it would be possible, for instance, with GeoNames that accepts user-contributed data). Another case for multiple geocoding services, one of which should be local. Indeed, I'm a bit surprised that Android doesn't provide a service to register custom locations in the preferences, as it is possible e.g. to have a database of contacts.
In other words, the Location APIs in Android are too closed and Google-centric. I'll have to import the code used in forceTen, which implements pluggabe GeoCoders and already has got a GeoNames provider. Fortunately, the fact I'm able to run at least a subset of the NetBeans Lookup API on Android should make the task not too hard to achieve.
First Screencast of blueBill Mobile
I'm able to provide a first decent screencast of blueBill Mobile, even though I've still to learn and improve the way screencasts of Android applications can be made:
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/android-geocoder-limitations | CC-MAIN-2020-29 | en | refinedweb |
07-19-2019
03:57 AM
I have a design with an AXI4Lite Bus and an ILA attached to that bus:
The configuration of the ILA looks like this:
I generate a bitstream, export the bitstream to the SDK and write my application software:
#include "xgpio.h"
#include "xparameters.h"
u32 Counter = 0x06;
u32 Status = XST_SUCCESS;
XGpio Gpio;
int main()
{
Status = XGpio_Initialize(&Gpio, XPAR_LED_DEVICE_ID);
if(Status != XST_SUCCESS)
{
xil_printf("GPIO Initialization failed: %lu\r\n", Status);
return XST_FAILURE;
}
while(1)
{
XGpio_DiscreteWrite(&Gpio, 1, Counter);
for(u32 Delay = 0; Delay < 0xFFFFFF; Delay++);
XGpio_DiscreteClear(&Gpio, 1, Counter);
for(u32 Delay = 0; Delay < 0xFFFFFF; Delay++);
if(Counter < 0x0F)
{
Counter++;
}
else
{
Counter = 0x00;
}
xil_printf("Counter: %lu\n\r", Counter);
}
return 0;
}
Now I create a new debug setting:
I launch this debug settings and wait for the debugger to jump at the entry point at "main". Now I open the hardware manager in Vivado, connect to my target, add the signals to the ILA and change the trigger mode to "TRIG_IN_ONLY" :
Now the ILA got armed by clicking "Run trigger for this ILA core" and after that step I resume my application (F8) to jump to a breakpoint at
XGpio_DiscreteWrite(&Gpio, 1, Counter);
but my ILA doesn´t trigger. The status is "Waiting for Trigger".
So what is wrong with my settings?
07-19-2019
04:28 AM
Okay I think I found the solution for the problem. It seems that I have to switch the Cross Trigger settings in my debug configuration.Why do I have to set "CPUDBGACK0" as input and the "FTM trigger" as output? I want to hold the ILA when a break point is hit. So I assumed that the signals should go from the CPU to the ILA and not from the ILA to the CPU.Can someone explain this to me?
Thank you! | https://forums.xilinx.com/t5/Processor-System-Design-and-AXI/ILA-cross-trigger-doesn-t-work/td-p/998120 | CC-MAIN-2020-29 | en | refinedweb |
import "go.chromium.org/luci/tokenserver/appengine/impl/certconfig"
Package certconfig contains code to work with imported CAs and their CRLs.
These CAs are used to validate certificates used in MintMachineToken RPC calls.
ca.go crl.go doc.go rpc_fetch_crl.go rpc_get_ca_status_rpc.go rpc_import_ca_configs.go rpc_list_cas.go warmup.go
CRLShardCount is a number of shards to use for storing CRL in the datastore.
Each shard can hold ~2 MB of data (taking into account zlib compression), so 16 shards ~= 32 MB. Good enough for a foreseeable future.
Changing this value requires rerunning of Admin.FetchCRL RPC to rebuild the entities.
GetCAByUniqueID returns CN name that corresponds to given unique ID.
It uses cached CAUniqueIDToCNMap for lookups. Returns empty string if there's no such CA.
ListCAs returns names of all currently active CAs, in no particular order.
LoadCAUniqueIDToCNMap loads CAUniqueIDToCNMap from the datastore.
StoreCAUniqueIDToCNMap overwrites CAUniqueIDToCNMap with new content.
UpdateCRLSet splits a set of revoked certificate serial numbers into shards, storing each shard in a separate entity (CRLShardBody).
It effectively overwrites the entire set.
type CA struct { // CN is CA's Common Name. CN string `gae:"$id"` // Config is serialized CertificateAuthorityConfig proto message. Config []byte `gae:",noindex"` // Cert is a certificate of this CA (in der encoding). // // It is read from luci-config from path specified in the config. Cert []byte `gae:",noindex"` // Removed is true if this CA has been removed from the config. Removed bool // Ready is false before this CA's CRL is fetched for the first time. Ready bool AddedRev string `gae:",noindex"` // config rev when this CA appeared UpdatedRev string `gae:",noindex"` // config rev when this CA was updated RemovedRev string `gae:",noindex"` // config rev when it was removed // ParsedConfig is parsed Config. // // Populated if CA is fetched through CertChecker. ParsedConfig *admin.CertificateAuthorityConfig `gae:"-"` // ParsedCert is parsed Cert. // // Populated if CA is fetched through CertChecker. ParsedCert *x509.Certificate `gae:"-"` }
CA defines one trusted Certificate Authority (imported from config).
Entity key is CA Common Name (that must match what's is in the certificate). Certificate issuer (and the certificate signature) is ignored. Usually, the certificates here will be self-signed.
Removed CAs are kept in the datastore, but not actively used.
ParseConfig parses proto message stored in Config.
type CAUniqueIDToCNMap struct { GobEncodedMap []byte `gae:",noindex"` // gob-encoded map[int64]string // contains filtered or unexported fields }
CAUniqueIDToCNMap is a singleton entity that stores a mapping between CA's unique_id (specified in config) and its Common Name.
It's loaded in memory in full and kept cached there (for 1 min). See GetCAByUniqueID below.
type CRL struct { // Parent is pointing to parent CA entity. Parent *ds.Key `gae:"$parent"` // EntityVersion is used for simple concurrency control. // // Increase on each update of this entity. EntityVersion int `gae:",noindex"` // LastUpdateTime is extracted from corresponding field of CRL. // // It indicates a time when CRL was generated by the CA. LastUpdateTime time.Time `gae:",noindex"` // LastFetchTime is when this CRL was fetched the last time. // // Updated only when newer CRL version is fetched. LastFetchTime time.Time `gae:",noindex"` // LastFetchETag is ETag header of last downloaded CRL file. // // If CRL's etag doesn't change, we can skip reparsing CRL. LastFetchETag string `gae:",noindex"` // RevokedCertsCount is a number of revoked certificates in CRL. FYI only. RevokedCertsCount int `gae:",noindex"` // contains filtered or unexported fields }
CRL represents a parsed Certificate Revocation List of some CA.
ID is always "crl", the parent entity is corresponding CA.
GetStatusProto returns populated CRLStatus proto message.
CRLChecker knows how to check presence of a certificate serial number in CRL.
Uses entities prepared by UpdateCRLSet.
It is a stateful object that caches CRL shards in memory (occasionally refetching them from the datastore), thus providing an eventually consistent view of the CRL set.
Safe for concurrent use. Should be reused between requests.
NewCRLChecker initializes new CRLChecker that knows how to examine CRL of a CA (identifies by its Common Name).
It must know number of shards in advance. Usually is it just CRLShardCount.
It will cache shards in local memory, refetching them if necessary after 'cacheDuration' interval.
IsRevokedSN returns true if given serial number is in the CRL.
type CRLShardBody struct { Parent *ds.Key `gae:"$parent"` // key of CRLShardHeader SHA1 string `gae:",noindex"` // SHA1 of serialized shard data (before compression) ZippedData []byte `gae:",noindex"` // zlib-compressed serialized shards.Shard. // contains filtered or unexported fields }
CRLShardBody is a fat entity that contains serialized CRL shard.
See CRLShardHeader for more info.
Parent entity is CRLShardHeader. ID is always "1".
type CRLShardHeader struct { ID string `gae:"$id"` SHA1 string `gae:",noindex"` // SHA1 of serialized shard data (before compression) }
CRLShardHeader represents a hash of a shard of a CRL sharded set.
We split CRL into a bunch of shards to avoid hitting datastore entity size limits. Each shard lives in its own entity group, where root entity (CRLShardHeader) contains a hash of the shard data (CRLShardBody).
It is used to skip fetches of fat shard entities if we already have the same data locally (based on matching hash).
ID is "<cn name>|<total number of shards>|<shard index>" (see shardEntityID).
FetchCRLRPC implements CertificateAuthorities.FetchCRL RPC method.
func (r *FetchCRLRPC) FetchCRL(c context.Context, req *admin.FetchCRLRequest) (*admin.FetchCRLResponse, error)
FetchCRL makes the server fetch a CRL for some CA.
GetCAStatusRPC implements CertificateAuthorities.GetCAStatus RPC method.
func (r *GetCAStatusRPC) GetCAStatus(c context.Context, req *admin.GetCAStatusRequest) (*admin.GetCAStatusResponse, error)
GetCAStatus returns configuration of some CA defined in the config.
ImportCAConfigsRPC implements Admin.ImportCAConfigs RPC method.
func (r *ImportCAConfigsRPC) ImportCAConfigs(c context.Context, _ *empty.Empty) (*admin.ImportedConfigs, error)
ImportCAConfigs fetches CA configs from from luci-config right now.
func (r *ImportCAConfigsRPC) SetupConfigValidation(rules *validation.RuleSet)
SetupConfigValidation registers the config validation rules.
ListCAsRPC implements CertificateAuthorities.ListCAs RPC method.
ListCAs returns a list of Common Names of registered CAs.
Package certconfig imports 35 packages (graph) and is imported by 8 packages. Updated 2020-07-02. Refresh now. Tools for package owners. | https://godoc.org/go.chromium.org/luci/tokenserver/appengine/impl/certconfig | CC-MAIN-2020-29 | en | refinedweb |
For each loop in Java
In this tutorial, we are going to learn about one of the most famous looping techniques, For each loop in Java that is also known as enhanced for loop. This loop is a control flow statement used for traversal of an array or a collection. In Java it was firstly introduced in JDK 1.5.
It’s common syntax is: –
for(return datatype : the collection or the array name){ //Code You Want To Write; }
For each loop Java Implementation
Now we are gonna create a String Array containing some random String values. So, we will be using for each loop to traverse through that array and print its value.
CODE: –
public class Main { public static void main(String[] args) { String array[]={"ASD","ZXC","QWE","RTY","GHJ"}; for(String i:array){ System.out.println(i); } } }
Code Output: –
ASD ZXC QWE RTY GHJ
We saw that in this loop we did not even mention the length of the array and we traversed all the elements. The syntax is also quite simple just the return type and the name of the array that is being traversed.
Now we are creating a list(collection) of integers and we are going to add the integers in the list and will print it’s sum.
CODE: –
import java.util.*; public class Main { public static void main(String[] args) { List<Integer> lst=new ArrayList<Integer>(); lst.add(10); lst.add(20); lst.add(30); lst.add(40); int sum=0; for(int i:lst){ sum+=i; } System.out.println("The sum of the List is: "+sum); } }
Code Output: –
The sum of the List is: 100
Some bulletin points for using for each loop: –
- We Can’t use this loop for backward propagation i.e we cannot go from back to front in this. For this first reverse the array then we can propagate backward.
- It is less prone to error due to its easy syntax.
- No use of indexing is there.
Also read: –
Exit from a loop in Java with | https://www.codespeedy.com/for-each-loop-in-java/ | CC-MAIN-2020-29 | en | refinedweb |
Customizing the Product Detail Page
To customize the Product Detail Page (PDP), I had to add a static image to the layout and remove the breadcrumbs, basically I wanted to override the
render() of
ProductDetail. For this the easiest way is to create a custom
render function and pass it in the props to
ProductDetail. The code in almost all the components is written in such a way that if a
render function is passes in the
props, that function will be run instead of the default one.
Create the render function in a file, for example in
custom/components/ProductDetailCustom.js, the code is in the format:
export default { render() { // custom render code } }
And this is passed to the
ProductDetail component in
src/pages/products.js like:
import ProductDetailCustom from "custom/components/ProductDetailCustom"; render() { .... <ProductDetail ... render={ProductDetailCustom.render} /> }
To read more about this pattern follow
A example of customization was that price had to displayed with title instead of with the ProductDetail. So in
ProductDetailCustom.render we add
<ProductDetailTitle pageTitle={product.pageTitle} title={product.title} priceRange={productPrice.displayPrice} render={ProductDetailTitleCustom.render}/> <ProductDetailInfo description={product.description} vendor={product.vendor} render={ProductDetailInfoCustom.render} />
As you can see from the above code,
priceRange is now passed to
ProductDetailTitle instead of
ProductDetailTitleCustom.
But we still have to display the
priceRange in
ProductDetailTitle, for this we again follow the above approach.
Create a file
ProductDetailTitleCustom which exports a
render function like:
import React, { Component } from "react"; import Typography from "@material-ui/core/Typography"; import Grid from "@material-ui/core/Grid"; export default { render() { const { title, pageTitle, priceRange, classes } = this.props; // Render nothing if neither the title nor pageTitle exists if (!title && !pageTitle) return null; return ( <Grid className={classes.root} item sm={12}> {title && <Typography className={classes.title} gutterBottom={true}{title}</Typography>} {pageTitle && <Typography className={classes.pageTitle}{pageTitle}</Typography>} {priceRange && <Typography className={classes.priceRange} gutterBottom={true}{priceRange}</Typography>} </Grid> ); } }
In this the
render function adds the code to display
priceRange. Now this function is exported and passed to the
ProductDetailTitle via
props
The final thing left to do is to remove the code to display
priceRange from
ProductDetailInfo. This can be done in exactly the same way.
Create a file
ProductDetailInfoCustom which exports
render() which has exactly the same code as ProductDetailInfo's
render except the component that displays the
priceRange. Pass this
render to the
props of
ProductDetailInfo as shown above.
Done!
The whole of PDP is customized in a similar way. | https://docs.reactioncommerce.com/docs/next/swag-shop-6 | CC-MAIN-2020-29 | en | refinedweb |
?
But of course, interpreted and byte-compiled languages do require the original language, or a version of it, in order to run. True, Java programs are compiled, but they're compiled into bytecodes then executed by the JVM. Similarly, .NET programs cannot run unless the CLR is present.
Even so, many of the students in my Python courses are surprised to discover that if you want to run a Python program, you need to have the Python language installed. If you're running Linux, this isn't a problem. Python has come with every distribution I've used since 1995. Sometimes the Python version isn't as modern as I'd like, but the notion of "this computer can't run Python programs" isn't something I've had to deal with very often.
However, not everyone runs Linux, and not everyone's computer has Python on it. What can you do about that? More specifically, what can you do when your clients don't have Python and aren't interested in installing it? Or what if you just want to write and distribute an application in Python, without bothering your users with additional installation requirements?
In this article, I discuss PyInstaller, a cross-platform tool that lets you take a Python program and distribute it to your users, such that they can treat it as a standalone app. I also discuss what it doesn't do, because many people who think about using PyInstaller don't fully understand what it does and doesn't do.
Running Python Code
Like Java and .NET, Python programs are compiled into bytecodes, high-level commands that don't correspond to the instructions of any actual computer, but that reference something known as a "virtual machine". There are a number of substantial differences between Java and Python though. Python doesn't have an explicit compilation phase; its bytecodes are pretty high level and connected to the Python language itself, and the compiler doesn't do that much in terms of optimization. The correspondence between Python source code and the resulting bytecodes is basically one-to-one; you won't find the bytecode compiler doing fancy things like inlining code or optimizing loops.
However, there's no doubt that Python runs bytecode, rather than your source code. You can see this in a number of different ways, the easiest of which is to create a Python module and then import that module. The module is translated into Python bytecodes and then saved to a file with a .pyc suffix. (In Python 3, this is under a directory called __pycache__, with separate byte-compiled versions for different Python versions and architectures.)
What does this all have to do with PyInstaller? Well, if you want to distribute a Python program, it's not enough to provide the byte-compiled output. You also need to provide a copy of Python, and that turns out to be a pain under certain circumstances, as I mentioned previously.
PyInstaller takes your Python code and byte-compiles it. But, then it also creates an executable application that basically loads Python and runs your program. In other words, each application you distribute with PyInstaller has a complete copy of Python within it, including the libraries needed to run your program. Normally, Python includes the entire standard library, but PyInstaller is smart enough to include only those modules it really needs, thus keeping the distribution size within reason.
Note that the copy of Python you have when using PyInstaller is used to create the distributable package. This means if you are running Python 3.4 on Linux, it's that copy of Python 3.4 for Linux that'll be included in your package. In other words, PyInstaller works across platforms, in that you can run it on Linux, Windows, macOS and other systems, but the resulting package is specifically for one architecture. It also means you need to be a bit careful when using PyInstaller on a computer that has multiple Python versions installed.
Installing PyInstaller
PyInstaller is most easily installed on a computer running Python with
the standard
pip command:
pip install -U --user pyinstaller
The
-U flag indicates that you would like to upgrade PyInstaller, in
case you already have installed it and the version on PyPI is newer.
The
--user flag indicates that you don't want to install it in the
system's directories, but rather under your own home directory.
Recently, I've become a fan of installing things with
--user, largely
because it avoids the need to think about permissions. However, it
does mean that you need to add the "bin" directory from the
--user
location to your
PATH.
If you're on a computer that has more than one Python version
installed, it sometimes can be hard to know just which version is
connected to
pip. (Although
pip --version will tell you which
version of Python it's using.) For this reason, I sometimes do
things the long way, as follows:
python3.6 -m pip install -U --user pyinstaller
The
-m flag is sort of like the
import statement in Python;
running things in this way ensures that you're using the version you want.
Now that you've installed PyInstaller, let's use it to create a distributable Python application. I've created a new program called (very creatively) myapp.py. Here's the source code:
#!/usr/bin/env python3.6 import sys print("Hello, and welcome to my app!") print(f"We're running Python {sys.version}") for i in range(10): print(f"{i} ** 2 = {i**2}, {i} ** 3 = {i**3}")
As you can see, this program imports the
sys module, which
provides
access to the Python environment, as well as its variables and settings. I
do this so that I can grab
sys.version and ensure that the correct
version is really running.
Next, I execute a "for" loop, for no reason other than that it gives me some output that I can see on the screen when the program runs.
In both cases, I use one of my favorite features from Python 3.6,
f-strings, which allows me to interpolate expressions inside curly
braces. This is, in my mind, far better than the previous ways this was done in Python, using the "%" operator on strings or (more
recently) the
str.format method.
So, let's assume you want to run this program on a colleague's machine. (Remember that your colleague needs to run the same operating system as you do, because the output from PyInstaller is going to be a binary based on the Python version you've installed.) You can type:
pyinstaller myapp.py
And, you'll get a lot of output. I'm not going to review all of it, but here are some highlights:
468 INFO: PyInstaller: 3.3.1 468 INFO: Python: 3.6.3 470 INFO: Platform: ↪Linux-4.4.0-119-generic-x86_64-with-Ubuntu-16.04-xenial 475 INFO: wrote /root/myapp1/myapp.spec
The file "myapp.spec" describes the application you're creating with PyInstaller. You'll find that this file is created automatically when you run PyInstaller. Normally, PyInstaller is smart enough to figure out what files must be included in the resulting distribution, but in some cases, such as data files and shared libraries, you might have to edit the specfile and add them yourself:
491 INFO: Extending PYTHONPATH with paths ['/root/myapp1', '/root/myapp1']
When you say
import xyz in Python, the language looks (for starters)
in the current directory for "xyz.py". If it doesn't find that (or a
bytecoded variation), it looks through the elements of
sys.path,
one by one, looking for "xyz.py". If you want to tell Python to look
in some additional directories, you can set the
PYTHONPATH environment
variable. Here, PyInstaller is saying that it's modifying
PYTHONPATH so that the program can find modules and packages defined
in the current directory:
491 INFO: checking Analysis
PyInstaller analyzes your code in order to figure out which modules and packages you want to use. Used modules are included in the final distribution, while unused ones are ignored.
The "dist" Directory
There's a lot more to the output, but after running PyInstaller, you'll find that there's a "dist" directory, and that in that directory is another subdirectory with the name of your new application.
This directory contains your new Python application. Now, you can't just run it like that; it's still a bit more complex than your average executable. The idea is that you'll turn the directory into a zipfile, distribute the software to wherever you need it, unzip it on the destination machine, and then run the top-level program.
But what if you use a module that has not only a Python component, but also a compiled C component? PyInstaller handles that automatically. For example, say you're going to use NumPy in your program, how does PyInstaller handle the C portion, which is compiled?
In this case, PyInstaller noticed that you were using a module with a C component. And if you look in the "dist" directory, you'll now see a bunch of additional shared libraries (*.so files).
PyInstaller can't promise to work with all complex packages, but the authors have tried hard to provide a large degree of compatibility. For example, if you use the Cython package (for implementing Python modules in C or providing type hints), you'll find that PyInstaller handles it fine, including the appropriate files in the "dist" directory.
Conclusion
For years, many of my students and consulting clients have wanted to distribute Python code without needing to run the language itself. That's not possible, but PyInstaller does the next best thing, letting you distribute software in a fairly straightforward way. | https://www.linuxjournal.com/content/introducing-pyinstaller | CC-MAIN-2020-29 | en | refinedweb |
[privilege]Set any audio device as connected.
#include <audio/audio_manager_device.h>
int audio_manager_set_device_connected(audio_manager_device_t dev, bool connected)
The type of the audio device.
True, if the given audio device is to be marked as connected; false, otherwise.
The audio_manager_set_device_connected() function sets the connected status of a given audio device to help the audio manager allocate proper audio devices as default.
EOK upon success, negative errno upon failure. | http://www.qnx.com/developers/docs/qnxcar2/topic/com.qnx.doc.audiomanager.lib_ref/topic/audio_manager_set_device_connected.html | CC-MAIN-2020-29 | en | refinedweb |
Today we made a huge step towards RTM. I know this is no news anymore, but well, it has been one of those days 😉
Now please, go get the bits, start creating your models with the designer. Then tweak them with some nice inheritance. Why not, taste a few EntityReaders. Generate some classes and take a look at the generated code. Get familiar with our objects and namespaces! Surround an ObjectContext in a Using statement. Plunk some ObjectQuery<T> inside. Indulge yourself with some LINQ to Entities queries. Change values here and there, add some Entities. Call SaveChanges()…
If you have been waiting to get familiar with the Entity Framework, there is no way and no reason not to start now.
BuildYourSkills() and most of all, SendYourFeedback()! 🙂
Is there a go-live license yet for EF beta 3?
Pat,
To my understanding, the Beta 3 license is less restrictive than previous ones, but it still not quite the same kind that is known as "go-live" licenses. The EULA that accompanies setup contains, in particular in section “3. PRERELEASE SOFTWARE”, a description of the conditions under which you are allowed to use the software. | https://blogs.msdn.microsoft.com/diego/2007/12/07/entity-framework-beta-3-and-entity-designer-ctp2-are-out/ | CC-MAIN-2017-26 | en | refinedweb |
Talk:Wiki gardeners
Embed category lists?
Is it possible to embed category lists in a page? I would like to have the proposed tasks automagically listed at instead of having to keep manually the list.--qgil 12:36, 29 June 2008 (UTC)
- Well, according to this, we definitely need a plugin. Either CategoryTree, which seems to do want we want here, the other option is DynamicPageList, which is more complicated, but is capable of doing a lot more stuff. They seem to be compatible with each other, so installing both seems like a good plan. Anyway, I've filed bugs #3341 and #3342. —GeneralAntilles 12:53, 29 June 2008 (UTC)
Other Language Section
Is it possible to create the Russian-language and other language section of wiki ? We would like to move here wiki.internet-tablet.com materials and translations. --dik 23:58, 30 June 2008 (UTC)
- This may not be super-feasible. Wikipedia does it by providing a nearly-completely separate wiki for each language. We could do it here by providing a namespace for each language, but that is likely to clutter up searches, categories and page lists with non-English results, which is probably not a desired outcome. Will likely need to discuss further. —GeneralAntilles 06:19, 1 July 2008 (UTC)
- Personally, I'm very much against cluttering up the wiki with non-English content. Running a separate mediawiki instance for each language may be the better option (from a wiki-user perspective, anyway), but running a dozen or other instances that are guaranteed to end up as spam repositories isn't something that we need. So, in order to have a language instance added, we need to see a minimum commitment (say, 5 dedicated people that are willing to manage the wiki, patrol for spam, etc). —GeneralAntilles 06:50, 1 July 2008 (UTC)
- hope you won't drag that for ages - community development in non-English languages is no less priority than pushing forward English-only solution. silpol 08:50, 2 July 2008 (UTC)
- Why not elaborating a decent proposal?--qgil 09:33, 2 July 2008 (UTC)
- As GeneralAntilles says, though, it needs commitment from others. There are probably no more than a dozen people regularly tending this wiki and a wiki is like a garden: it needs to be regularly pruned, watered etc. to prevent rotting and weeds. If there's enough commitment and energy for a non-English language wiki, I'd be happy to support it; but I agree with GA: it shouldn't clutter up the English wiki search results and so may have to be an entirely separate instance. --Jaffa 17:11, 2 July 2008 (UTC)
More uploadable file formats
I'm Unable to upload a file to the wiki. This is stopping Task:Components_and_packages. Please let me know whether this can be done or not with the wiki. If not, I will find another place. Thanks!--qgil 08:35, 19 July 2008 (UTC)
- --qgil 15:11, 19 July 2008 (UTC)
- This is definitely a ferenc issue. —GeneralAntilles 20:15, 19 July 2008 (UTC)
Templates
I was trying to make wikipedia like infobox template for software but probably missed some templates as page didn't come out as supposed. OMWeather is page where I was trying to make it. I hope that someone can make that template to work properly. Or was it mistake to copy those templates directly from wikipedia? If so templates I made should probably be deleted.
- This page was last modified on 12 May 2010, at 20:07.
- This page has been accessed 17,987 times. | https://wiki.maemo.org/Talk:Maemowiki_Action_Group | CC-MAIN-2017-26 | en | refinedweb |
I use Android and found such official tutorial and link how to download this lib to the project
but after I have added this line to gradle I still can't use http classes...
I tried to import them to my class but anyway they don't work and marked as
Cannot resolve symbol
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
In your Gradle file, just add the dependency:
apply plugin: 'com.android.application' android { ... useLibrary 'org.apache.http.legacy' ... } | https://codedump.io/share/9wKK7rxxfFUO/1/how-to-connect-orgapachehttp-to-my-project | CC-MAIN-2017-26 | en | refinedweb |
String.IndexOf Method (String, Int32)
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ].Notes to Callers
We recommend that you avoid calling string comparison methods that substitute default values. Instead, call methods that require parameters to be explicitly specified. To find the first index of a substring that occurs after a particular character position by using the comparison rules of the current culture, call the IndexOf method overload with a value of StringComparison.CurrentCulture for its comparisonType parameter.
The following example searches for all occurrences of a specified string within a target string.
using System; public class Example { public static void Demo(System.Windows.Controls.TextBlock outputBlock) { string strSource = "This is the string which we will perform the search on"; outputBlock.Text += String.Format("The search string is:{0}\"{1}\"{0}", "\n", strSource) + "\n"; string strTarget = ""; int found = 0; int totFinds = 0; do { outputBlock.Text += ; outputBlock.Text += String.Format("{0}The search parameter '{1}' was found {2} times.{0}", "\n", strTarget, totFinds) + "\n"; totFinds = 0; } while (true); } } | https://msdn.microsoft.com/library/windows/apps/7cct0x33(v=vs.105).aspx | CC-MAIN-2017-26 | en | refinedweb |
0
Hi all,
I am attempting data binding in WPF. I have a class Recipe and another called RecipeService. There seems a problem with the RecipeService class in terms of compatibility with the Recipe class as when I add its type to the ObjectDataProvider in the XAML file, I get an error that RecipeList type is not found. Any suggestions?
Furthermore, I am using Visual Studio.Net and the "Recipe" text in "public List<Recipe> GetRecipeList()" should be highlighted to Blue if accurate, however it is not.
Your suggestions are appreciated.
The code is below...
/*C# code*/ using System.Collections.Generic; namespace TestApp { public class Recipe { private int _id; private string _title; //can be used as recipe name private string _mealType; public Recipe(int id, string title, string _mealType) { _id = id; _title = title; _mealType = mealType; } public int Id { get { return _id; } set { _id = value; } } public string Title { get { return _title; } set { _title = value; } } public string MealType { get { return _mealType; } set { _mealType = value; } } } class RecipeService { public List<Recipe> GetRecipeList() { Recipe pasta = new Recipe(1, "Pasta", "Lunch"); Recipe toast = new Recipe(2, "Toast", "Breakfast"); List<Recipe> recipeList = new List<Recipe>(); recipeList.Add(pasta); recipeList.Add(toast); return recipeList; } } } <!--Some part of the code in the XAML File--> <StackPanel> <StackPanel.Resources> <ObjectDataProvider x:</ObjectDataProvider> </StackPanel.Resources> </StackPanel>
<!--Here is the error message-->
error MC3050: Cannot find the type 'svc:RecipeService'. Note that type names are case sensitive.
Edited by Dani: Formatting fixed | https://www.daniweb.com/programming/software-development/threads/316273/c-and-xaml | CC-MAIN-2017-26 | en | refinedweb |
Please let me know if I should make something more clear
1. Each item in list contains a tuple with its name -> ((value, work), 'name')
2. the function "sort" below sorts the list of subjects by "value" in descending order
3. I get: TypeError: 'int' object is unsubscriptable (occurs after looping a few times)
It shouldn't be the logic of the sorting method as it works elsewhere
Could the problem be due to how the list is created? (see under sort function)
def sortj(list): for i in range(1, len(list)): value = list[ i ][ 0 ][ 0 ] ## integer j = i - 1 done = False while not done: if value > list[ j ][ 0 ][ 0 ]: # error occurs ( list [ j ] [ 0 ] [ 0 ] is the problem) list[ j + 1 ] = list[ j ] j -= 1 if j < 0: done = True else: done = True list[ j + 1 ] = value
after list is created by the following process, the sorting above is attempted
(Why does the first item appear to be an empty list in the finished product of "sortedj" ?)
# this is gathering the tuples that contain j amount of work from a list of subjects in a dictionary
for j in workCaps: # the range of max work sortedj = [] for i in subIndexes: if j <= maxWork: if subjects[names[i]][1] == j: ## if work = sortedj.append((subjects[names[i]], names[i]))
Thanks for any help
Edited by old_kid: n/a | https://www.daniweb.com/programming/software-development/threads/344036/typeerror-int-object-is-unsubscriptable | CC-MAIN-2017-26 | en | refinedweb |
Since bug 183794 has been implemented there is an asymetry between the way people register new actions (annotation) and the way they reference them (layer). For the sake of usability, it is desirable to provide some annotation based way of creating references.
Proposal is part of
Let's keep things simple and add org.openide.awt.ActionReference annotation.
Need to see a proposed patch incl. nontrivial uses to really evaluate, especially with subtle parts like name() and id(). Some of the issues brought up in are handled by a separate @ActionID & @ActionRegistration and use of package annotations.
[JG01] While a generic @ActionReference is useful for extensibility to unforeseen domains such as the Projects tab context menu, the current proposal forces people to remember, and type, magic strings like "Toolbars" (capitalized differently from "JToolBar" by the way!). If you are opposed to having @ActionMenuReference etc. then at least introduce some constants into ActionReference, e.g.:
/** Main menu bar. Path will be a menu code name, possibly with submenus. */
String MENU = "Menu/";
/** Main tool bar set. Path will be a toolbar code name. */
String TOOLBARS = "Toolbars/";
so you can write e.g.
@ActionReference(path=ActionReference.TOOLBARS + "Edit", position=123)
I would suggest a special annotation for Shortcuts, e.g.
import static java.awt.event.KeyEvent.*;
import static ActionShortcutReference.Stroke.*;
import static ActionShortcutReference.Modifiers.*;
@ActionShortcutReference({@Stroke(key=VK_X, modifiers=CTRL), @Stroke(key=VK_WINDOWS)})
since the syntax is rather complex and it is easy to make typos. But if generic @ActionReference is to be used for this as well then there must be a SHORTCUTS constant whose Javadoc carefully describes the required name() syntax, {@link}ing to appropriate specifications such as KeyEvent and Utilities.stringToKeys.
The processor for a generic annotation could also hardcode syntax checks for certain well-known locations. For example, require and try to parse name() if in Shortcuts; or verify that paths under Toolbars specify no subfolder; or require a position attribute for menu items. This is not as nice as a custom annotation but better than nothing.
[JG02] Would be useful to have position-valued attributes separatorBefore() and separatorAfter(), which would require position(). These are very commonly needed for menu registrations (also possible for toolbar registrations), and specifying separators in a layer is cumbersome.
Builder is on:
First set of changes too:
Re. JG01 The problem without multiple difference annotations is that I don't see easy way to incorporate them into @ActionReferences(value={}). I understand that it is necessary to provide some guidance when typing the path. Rather than the tricks mentioned in JG01, I'd like to use getCompletions and provide either hardcoded or real hints.
(In reply to comment #3)
> The problem without multiple difference annotations is that I don't
> see easy way to incorporate them into @ActionReferences(value={}).
You wouldn't need to; you would have multiple top-level annotations. You only need @Somethings if you would otherwise need to have more than one @Something. (Would be nicer if JSR 175 were amended so you could repeat a given annotation, if the annotation were meta-annotated to allow this.)
> use getCompletions and provide either hardcoded or real hints
Better than nothing.
BTW String.isEmpty is easier to read than .equals("").
Is there no ActionReference.name() as in wiki, needed for shortcuts? This is why I wanted to see some representative uses in various modules.
ElementType.PACKAGE was forgotten in @Target on @ActionReference, and the processor fails to handle this case.
Delete empty @return.
Next round. I am dealing with the wizards. I have problems with properly positioning the action. I've added toInteger() method but I am not sure how to implement it:
Separators are also not handled. Simplest thing is to leave them in XML file. Still todo.
Re. "ElementType.PACKAGE was forgotten". It does not make much sense to put just one @ActionReference on package, usually you want to put there more. So I left out the element intentionally.
Do not use Proxy in createActionReference. This is too complicated. Simply define a small struct class with the desired getters for use from FreeMarker.
Regarding toPosition - you would I think need to duplicate code from CreatedModifiedFiles.orderLayerEntry. Needs to find the surrounding FileObject's and pick a position between them.
Ability to add just a single @ActionReference on a package would be consistent with other package annotations which permit both the single and multiple forms. Not a major issue to omit it.
Version which imho misses only better getCompletions in the annotation processor. Shows sample usage, properly generates separators (in layer), positions the actions fine:!?
Please notice also one additional contract between openide.awt and apisupport.project:
It is not working properly yet as the IDE's code completion support needs a bit of time to settle down. Regardless of that I'd like to integrate tomorrow. We'll deal with the proper behaviour of code completion in default branch.
(In reply to comment #9)
> Please notice also one additional contract between openide.awt and
> apisupport.project:
This looks like a lot more trouble than it's worth. If this level of code completion were really necessary (and I don't think it is, since new actions are usually placed by wizard) it would be better to look up the available layer positions from the classpath (probably processor path) inside ActionProcessor.
The project owner may be null, etc.
Also please do not use Thread.CCL to find a module class. It is unreliable and will not work at all in OSGI mode.
I still think specifying separators in the annotation is valuable. This is a very common requirement.
I also think that defining constants for well-known action locations, and providing warnings or errors for definite violations of semantics (such as malformed shortcut names), is a higher priority than code completion.
(In reply to comment #8)
>!?
Because the code is needlessly complex and hard to track. Would be simpler and clearer to define a small struct.
As nobody questioned the fast status of the review, I am going to integrate now.
I believe the API is minimalistic, but useful as it is right now. We can certainly work on improvements (like the separator stuff; but it is not clear how to do it best. Should we mimic layer based solution or should we rather use some group="...." attribute which seems to be standard in the other IDEs? Anyway that is a matter for separate issue).
I plan to improve the live getCompletions from layers with Dušan Bálek. I believe it is going to be beneficial for the IDE support for Processor.getCompletions in general. If there are unavoidable issues with that approach, we can indeed easily turn it off.
Re. "hard to track code" - but the code is tested and I prefer consistency to easier to implement dual concepts.
Merged as core-main#d1d13a81525d
(In reply to comment #12)
> We can certainly work on improvements (like the separator stuff
Yes, it can be compatibly added. My concern is about modules which migrate to the annotation before then, and newly added actions using wizard; it may be harder to retroactively deal with their separators. This matters mainly if we release the current annotation in 6.10.
> Should we mimic layer based solution or should we rather use
> some group="...." attribute which seems to be standard in the other IDEs?
I thought about group="..." as well. But I cannot think of a way to do this at all compatibly.
(In reply to comment #13)
> it may be
> harder to retroactively deal with their separators. This matters mainly if we
> release the current annotation in 6.10.
I reported it as bug 189848 | https://netbeans.org/bugzilla/show_bug.cgi?id=189558 | CC-MAIN-2017-26 | en | refinedweb |
java.lang.Object org.springframework.util.MethodInvoker org.springframework.beans.support.ArgumentConvertingMethodInvoker org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean
public class MethodInvokingJobDetailFactoryBean
FactoryBean that exposes a JobDetail object that delegates job execution to a specified (static or non-static) method. Avoids the need to implement a one-line Quartz Job that just invokes an existing service method.
Derived from MethodInvoker to share common properties and behavior with MethodInvokingFactoryBean.
Supports both concurrently running jobs and non-currently running ones through the "concurrent" property.
Note: JobDetails created via this FactoryBean are not serializable and thus not suitable for persistent job stores. You need to implement your own Quartz Job as a thin wrapper for each case where you want a persistent job to delegate to a specific service method.
MethodInvoker.setTargetObject(java.lang.Object),
MethodInvoker.setTargetMethod(java.lang.String),
setConcurrent(boolean),
MethodInvokingFactoryBean
public MethodInvokingJobDetailFactoryBean()
public void setName(String name)
JobDetail.setName(java.lang.String)
public void setGroup(String group)
JobDetail.setGroup(java.lang.String),
Scheduler.DEFAULT_GROUP
public void setConcurrent(boolean concurrent)
StatefulJobinterface. More information on stateful versus stateless jobs can be found here.
The default setting is to run jobs concurrently.
concurrent- whether one wants to execute multiple jobs created by this bean concurrently
public void setJobListenerNames(String[] names)
A JobListener name always refers to the name returned by the JobListener implementation.
SchedulerFactoryBean.setJobListeners(org.quartz.JobListener[]),
JobListener.getName()
public void setBeanName(String beanName)
BeanNameAware
Invoked after population of normal bean properties but before an init callback like InitializingBean's afterPropertiesSet or a custom init-method.
setBeanNamein interface
BeanNameAware
beanName- the name of the bean in the factory() | https://docs.spring.io/spring-framework/docs/1.2.x/javadoc-api/org/springframework/scheduling/quartz/MethodInvokingJobDetailFactoryBean.html | CC-MAIN-2022-21 | en | refinedweb |
Passing session tags in AWS STS
Session tags are key-value pair attributes that you pass when you assume an IAM role or
federate a user in AWS STS. You do this by making an AWS CLI or AWS API request through AWS STS or
through your identity provider (IdP). When you use AWS STS to request temporary security
credentials, you generate a session. Sessions expire and have credentials, such as an access key pair and a
session token. When you use the session credentials to make a subsequent request, the request context includes the
aws:PrincipalTag context key. You can
use the
aws:PrincipalTag key in the
Condition element of your policies
to allow or deny access based on those tags.
When you use temporary credentials to make a request, your principal might include a set of tags. These tags come from the following sources:
Session tags – The tags passed when you assume the role or federate the user using the AWS CLI or AWS API. For more information about these operations, see Session tagging operations.
Incoming transitive session tags – The tags inherited from a previous session in a role chain. For more information, see Chaining roles with session tags later in this topic.
IAM tags – The tags attached to your IAM assumed role.
Topics
- Session tagging operations
- Things to know about session tags
- Permissions required to add session tags
- Passing session tags using AssumeRole
- Passing session tags using AssumeRoleWithSAML
- Passing session tags using AssumeRoleWithWebIdentity
- Passing session tags using GetFederationToken
- Chaining roles with session tags
- Using session tags for ABAC
- Viewing session tags in CloudTrail
Session tagging operations
You can pass session tags using the following AWS CLI or AWS API operations in AWS STS. The AWS Management Console Switch Role feature does not allow you to pass session tags.
You can also set the session tags as transitive. Transitive tags persist during role chaining. For more information, see Chaining roles with session tags.
Operations that support session tagging can fail under the following conditions:
You pass more than 50 session tags.
The plaintext of your session tag keys exceeds 128 characters.
The plaintext of your session tag values exceeds 256 characters.
The total size of the plaintext of session policies exceeds 2048 characters.
The total packed size of the combined session policies and tags is too large. If the operation fails, the error message shows how close the policies and tags combined come to the upper size limit, by percentage.
Things to know about session tags
Before you use session tags, review the following details about sessions and tags.
When using session tags, trust policies for all roles connected to the identity provider (IdP) passing tags must have the sts:TagSession permission. For roles without this permission in the trust policy, the
AssumeRoleoperation fails.
When you request a session, you can specify principal tags as the session tags. The tags apply to requests that you make using the session's credentials.
Session tags use key-value pairs. For example, to add contact information to a session, you can add the session tag key
johndoe@example.com.
Session tags must follow the rules for naming tags in IAM and AWS STS. This topic includes information about case sensitivity and restricted prefixes that apply to your session tags.
New session tags override existing assumed role or federated user tags with the same tag key, regardless of case.
You cannot pass session tags using the AWS Management Console.
Session tags are valid only for the current session.
Session tags support role chaining. By default, AWS STS does not pass tags to subsequent role sessions. However, you can set session tags as transitive. Transitive tags persist during role chaining and replace matching
ResourceTagvalues during the evaluation of the role trust policy. For more information, see Chaining roles with session tags.
You can use session tags to control access to resources or to control what tags can be passed into a subsequent session. For more information, see IAM tutorial: Use SAML session tags for ABAC.
You can view the principal tags for your session, including the session tags, in the AWS CloudTrail logs. For more information, see Viewing session tags in CloudTrail.
You must pass a single value for each session tag. AWS STS does not support multi-valued session tags.
You can pass a maximum of 50 session tags. The number and size of IAM resources in an AWS account are limited. For more information, see IAM and AWS STS quotas.
An AWS conversion compresses the passed session policies and session tags combined into a packed binary format with a separate limit. If you exceed this limit, the AWS CLI or AWS API error message shows how close the policies and tags combined come to the upper size limit, by percentage.
Permissions required to add session tags
In addition to the action that matches the API operation, you must have the following permissions-only action in your policy:
sts:TagSession
When using session tags, the role trust policies for all roles connected to an identity
provider (IdP) must have the
sts:TagSession permission. The
AssumeRole operation fails for any role connected to an IdP passing session
tags without this permission. If you don't want to update the role trust policy for each
role, you can use a separate IdP instance for passing session tags. Then, add the
sts:TagSession permission to only the roles connected to the separate
IdP.
You can use the
sts:TagSession action with the following condition
keys.
aws:PrincipalTag– Compares the tag attached to the principal making the request with the tag you specified in the policy. For example, you can allow a principal to pass session tags only if the principal making the request has the specified tags.
aws:RequestTag– Compares the tag key-value pair passed in the request with the tag pair you specified in the policy. For example, you can allow the principal to pass the specified session tags, but only with the specified values.
aws:ResourceTag– Compares the tag key-value pair you specified in the policy with the key-value pair attached to the resource. For example, you can allow the principal to pass session tags only if the role they assume includes the specified tags.
aws:TagKeys– Compares the tag keys in a request with the keys you specified in the policy. For example, you can allow the principal to pass only session tags with the specified tag keys. This condition key limits the maximum set of session tags that can be passed.
sts:TransitiveTagKeys- Compares the transitive session tag keys in the request with those specified in the policy. For example, you can write a policy to allow a principal to set only specific tags as transitive. Transitive tags persist during role chaining. For more information, see Chaining roles with session tags.
For example, the following role trust policy
allows the
test-session-tags user to assume the role with the attached policy.
When that user assumes the role, they must use the AWS CLI or AWS API to pass the three
required session tags and the required external ID. Additionally, the user can choose to set the
Project and
Department tags as transitive.
Example role trust policy for session tags
{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowIamUserAssumeRole", "Effect": "Allow", "Action": "sts:AssumeRole", "Principal": {"AWS": "arn:aws:iam::
123456789012:user/
test-session-tags"}, "Condition": { "StringLike": { "aws:RequestTag/
Project": "*", "aws:RequestTag/
CostCenter": "*", "aws:RequestTag/
Department": "*" }, "StringEquals": {"sts:ExternalId": "
Example987"} } }, { "Sid": "AllowPassSessionTagsAndTransitive", "Effect": "Allow", "Action": "sts:TagSession", "Principal": {"AWS": "arn:aws:iam::
123456789012:user/
test-session-tags"}, "Condition": { "StringLike": { "aws:RequestTag/
Project": "*", "aws:RequestTag/
CostCenter": "*" }, "StringEquals": { "aws:RequestTag/
Department": [ "
Engineering", "
Marketing" ] }, "ForAllValues:StringEquals": { "sts:TransitiveTagKeys": [ "
Project", "
Department" ] } } } ] }
What does this policy do?
The
AllowIamUserAssumeRolestatement allows the
test-session-tagsuser to assume the role with the attached policy. When that user assumes the role, they must pass the required session tags and external ID.
The first condition block of this statement requires the user to pass the
Project,
CostCenter, and
Departmentsession tags. The tag values do not matter in this statement, so you can use wildcards (*) for the tag values. This block ensures that user passes at least these three session tags. Otherwise, the operation fails. The user can pass additional tags.
The second condition block requires the user to pass an external ID with the value
Example987.
The
AllowPassSessionTagsAndTransitivestatement allows the
sts:TagSessionpermissions-only action. This action must be allowed before the user can pass session tags. If your policy includes the first statement without the second statement, the user can't assume the role.
The first condition block of this statement allows the user to pass any value for the
CostCenterand
Projectsession tags. You do this by using wildcards (*) for the tag value in the policy, which requires that you use the StringLike condition operator.
The second condition block allows the user to pass only the
Engineeringor
Marketingvalue for the
Departmentsession tag.
The third condition block lists the maximum set of tags you can set as transitive. The user can choose to set a subset or no tags as transitive. They cannot set additional tags as transitive. You can require that they set at least one of the tags as transitive by adding another condition block that includes
"Null":{"sts:TransitiveTagKeys":"false"}.
Passing session tags using AssumeRole
The
AssumeRole operation returns a set of temporary credentials you can use
to access AWS resources. You can use IAM user or role credentials to call
AssumeRole. To pass session tags while assuming a role, use the
--tags AWS CLI option or the
Tags AWS API parameter.
To set tags as transitive, use the
--transitive-tag-keys AWS CLI option or the
TransitiveTagKeys AWS API parameter. Transitive tags persist during role
chaining. For more information, see Chaining roles with session tags.
The following example shows a sample request that uses
AssumeRole. In this
example, when you assume the
my-role-example role, you create a session named
my-session. You add the session tag key-value pairs
Project =
Automation,
CostCenter =
12345, and
Department =
Engineering. You also set the
Project
and
Department tags as transitive by specifying their keys.
Example AssumeRole CLI request
aws sts assume-role \ --role-arn arn:aws:iam::123456789012:role/my-role-example \ --role-session-name my-session \ --tags Key=Project,Value=Automation Key=CostCenter,Value=12345 Key=Department,Value=Engineering \ --transitive-tag-keys Project Department \ --external-id Example987
Passing session tags using AssumeRoleWithSAML
The
AssumeRoleWithSAML operation authenticates with SAML-based federation.
This operation returns a set of temporary credentials you can use to access AWS resources.
For more information about using SAML-based federation for AWS Management Console access, see Enabling SAML 2.0 federated users to
access the AWS Management Console. For details about AWS CLI or AWS
API access, see About SAML 2.0-based federation. For a tutorial on configuring SAML federation for
your Active Directory users, see AWS Federated Authentication with Active Directory Federation Services (ADFS)
As an administrator, you can allow members of your company directory to federate into
AWS using the AWS STS
AssumeRoleWithSAML operation. To do this, you must complete
the following tasks:
AWS includes identity providers with certified end-to-end experience for session tags with their identity solutions. To learn how to use these identity providers to configure session tags, see Integrating third-party SAML solution providers with AWS.
To pass SAML attributes as session tags, include the
Attribute element with
the
Name attribute set to
Use the
{TagKey}
AttributeValue element to specify the value of the tag. Include a
separate
Attribute element for each session tag.
For example, assume that you want to pass the following identity attributes as session tags:
Project:Automation
CostCenter:12345
Department:Engineering
To pass these attributes, include the following elements in your SAML assertion.
Example snippet of a SAML assertion
<Attribute Name=" <AttributeValue>Automation</AttributeValue> </Attribute> <Attribute Name=" <AttributeValue>12345</AttributeValue> </Attribute> <Attribute Name=" <AttributeValue>Engineering</AttributeValue> </Attribute>
To set the preceding tags as transitive, include another
Attribute element
with the
Name attribute set to
Transitive tags persist
during role chaining. For more information, see Chaining roles with session tags.
To set the
Project and
Department tags as transitive, use the
following multi-valued attribute:
Example snippet of a SAML assertion
<Attribute Name=" <AttributeValue>Project</AttributeValue> <AttributeValue>Department</AttributeValue> </Attribute>
Passing session tags using AssumeRoleWithWebIdentity
Use OpenID Connect(OIDC)-compliant web identity federation to authenticate the
AssumeRoleWithWebIdentity operation. This operation returns a set of temporary
credentialsyou can use to access AWS resources. For more information about using web
identity federation for AWS Management Console access, see About web identity federation.
To pass session tags from OpenID Connect (OIDC), you must include the session tags in the
JSON Web Token (JWT). Include session tags in the
namespace in the token when you submit the
AssumeRoleWithWebIdentity request. To learn more about OIDC tokens and claims,
see Using
Tokens with User Pools in the Amazon Cognito Developer
Guide.
For example, the following decoded JWT uses a token to call
AssumeRoleWithWebIdentity with the
Project,
CostCenter, and
Department session tags. The token also sets the
Project and
CostCenter tags as transitive. Transitive tags persist
during role chaining. For more information, see Chaining roles with session tags.
Example decoded JSON Web Token
{ "sub": "johndoe", "aud": "ac_oic_client", "jti": "ZYUCeRMQVtqHypVPWAN3VB", "iss": " "iat": 1566583294, "exp": 1566583354, "auth_time": 1566583292, " { "principal_tags": { "Project": ["Automation"], "CostCenter": ["987654"], "Department": ["Engineering"] }, "transitive_tag_keys": [ "Project", "CostCenter" ] } }
Passing session tags using GetFederationToken
The
GetFederationToken allows you to federate your user. This operation
returns a set of temporary credentials you can use to access AWS resources. To add tags to
your federated user session, use the
--tags AWS CLI option or the
AWS API parameter. You can't set session tags as transitive when you use
GetFederationToken, because you can't use the temporary credentials to assume a
role. You cannot use role chaining in this case.
The following example shows a sample request using
GetFederationToken. In
this example, when you request the token, you create a session named
my-fed-user.
You add the session tag key-value pairs
Project =
Automation and
Department =
Engineering.
Example GetFederationToken CLI request
aws sts get-federation-token \ --name my-fed-user \ --tags key=Project,value=Automation key=Department,value=Engineering
When you use the temporary credentials returned by the
GetFederationToken
operation, the session principal tags include the user tags and the passed session
Chaining roles with session tags
You can assume one role and then use the temporary credentials to assume another role. You can continue from session to session. This is called role chaining. When you pass session tags while assuming a role, you can set the keys as transitive. This ensures that those session tags pass to subsequent sessions in a role chain. You cannot set role tags as transitive. To pass these tags to subsequent sessions, specify them as session tags.
The following example shows how AWS STS passes session tags, transitive tags, and role tags into subsequent sessions in a role chain.
In this example role chaining scenario, you use an IAM user access key in the AWS CLI to
assume a role named
Role1. You then use the resulting session credentials to
assume a second role named
Role2. You can then use the second session credentials
to assume a third role named
Role3. These requests occur as three separate
operations. Each role is already tagged in IAM. And during each request, you pass additional
session tags.
When you chain roles, you can ensure that tags from an earlier session persist to the
later sessions. To do this using the
assume-role CLI command, you must pass the
tag as a session tag and set the tag as transitive. You pass the tag
Star =
1 as a session tag. The command also attaches the tag
Heart =
1 to the role and applies as a principal tag when you use the session. However,
you also want the
Heart =
1 tag to automatically pass to the second
or third session. To do that, you manually include it as a session tag. The resulting session
principal tags include both of these tags, and sets them as transitive.
You perform this request using the following AWS CLI command:
Example AssumeRole CLI request
aws sts assume-role \ --role-arn arn:aws:iam::123456789012:role/Role1 \ --role-session-name Session1 \ --tags Key=Star,Value=1 Key=Heart,Value=1 \ --transitive-tag-keys Star Heart
You then use the credentials for that session to assume
Role2. The command
attaches the tag
Sun =
2 to the second role and applies as a
principal tag when you use the second session. The
Heart and
Star
tags inherits the transitive session tags in the first session. The second session resulting
principal tags are
Heart =
1,
Star =
1,
and
Sun =
2.
Heart and
Star continue to be
transitive. The
Sun tag attached to
Role2 is not marked as
transitive because it is not a session tag. Future sessions do not inherit this tag.
You perform this second request using the following AWS CLI command:
Example AssumeRole CLI request
aws sts assume-role \ --role-arn arn:aws:iam::123456789012:role/Role2 \ --role-session-name Session2
You then use the second session credentials to assume
Role3. The principal
tags for the third session come from any new session tags, the inherited transitive session
tags, and the role tags. The
Heart =
1 and
Star =
1 tags on the second session are inherited from the transitive session tag in
the first session. If you try to pass the
Heart =
3 session tag, the
operation fails. The inherited
Star = 1 session tag overrides the role
Star =
3 tag. In role chaining, the value of a transitive tag
overrides the role matching the
ResourceTag value before the evaluation of the
role trust policy. In this example, if
Role3 uses
Star as a
ResourceTag in the role trust policy, and sets
ResourceTag value
to the transitive tag value from the calling role session. The role
Lightning tag
also applies to the third session, and not set as transitive.
You perform the third request using the following AWS CLI command:
Example AssumeRole CLI request
aws sts assume-role \ --role-arn arn:aws:iam::123456789012:role/Role3 \ --role-session-name Session3
Using session tags for ABAC
Attribute-based access control (ABAC) uses an authorization strategy that defines permissions based on tag attributes.
If your company uses an OIDC or SAML-based identity provider (IdP) to manage user identities, you can configure your assertion to pass session tags to AWS. For example, with corporate user identities, when your employees federate into AWS, AWS applies their attributes to their resulting principal. You can then use ABAC to allow or deny permissions based on those attributes. For details, see IAM tutorial: Use SAML session tags for ABAC.
For more information about using AWS SSO with ABAC, see Attributes for access control in the AWS Single Sign-On User Guide.
Viewing session tags in CloudTrail
You can use AWS CloudTrail to view the requests used to assume roles or federate users. The CloudTrail log file includes information about the principal tags for the assumed-role or federated user session. For more information, see Logging IAM and AWS STS API calls with AWS CloudTrail.
For example, assume that you make an AWS STS
AssumeRoleWithSAML request, pass
session tags, and set those tags as transitive. You can find the following information in your
CloudTrail log.
Example AssumeRoleWithSAML CloudTrail log
"requestParameters": { "sAMLAssertionID": "_c0046cEXAMPLEb9d4b8eEXAMPLE2619aEXAMPLE", "roleSessionName": "MyRoleSessionName", "principalTags": { "CostCenter": "987654", "Project": "Unicorn" }, "transitiveTagKeys": [ "CostCenter", "Project" ], "durationSeconds": 3600, "roleArn": "arn:aws:iam::123456789012:role/SAMLTestRoleShibboleth", "principalArn": "arn:aws:iam::123456789012:saml-provider/Shibboleth" },
You can view the following example CloudTrail logs to view events that use session tags. | https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html | CC-MAIN-2022-21 | en | refinedweb |
Bootstrap Structure, Is this possible ?
What I want to do is have a button that will hide FORM1 and Open FORM2, then another button on FORM2 that will hide FORM2 and Show Form1 again.
I also want to separate the database functions using a .pro file but to reuse the instance. I wish to call the same reuseable custom functions in the sqlite database.
I can do this very easily in C# but I am struggling with Qt and C++.
I was thinking I could do something like this.
bootstrap->Form1->Hide()
bootstrap->Form2->show();
or
bootstrap->Database->function1() from either form1 or form2
Thanks in advance.
- kshegunov Moderators last edited by
class BootstrapOrWe { public: void showFirst(); void showSecond(); private: Form1Class Form1; Form2Class Form2; }; inline void BootstrapOrWe::showFirst() { Form2.hide(); Form1.show(); } inline void BootstrapOrWe::showSecond() { Form1.hide(); Form2.show(); }
Note:
It's rather poor habit to mix capital and lower leading letters for variable names (and or classes). You should adopt a consistent style and stick to it. For example - classes (and/or types) will start will capital letter while variables will start with a lower letter, and words will be camelcased (how Qt does it).
Kind regards.
- Shahazan Ali last edited by VRonin
#include <QPushButton> #include <QApplication> class Form : public QWidget { Q_OBJECT public: Form(QWidget* p = 0) : QWidget(p) { QPushButton * btn = new QPushButton("Hide Me and Show Other one", this); connect(btn, SIGNAL(clicked(bool)), this, SIGNAL(hideMeAndShowOtherOne())); } signals: void hideMeAndShowOtherOne(); }; int main(int argc, char *argv[]) { QApplication app(argc, argv); Form form1, form2; QObject::connect(&form1, SIGNAL(hideMeAndShowOtherOne()), &form2, SLOT(show())); QObject::connect(&form2, SIGNAL(hideMeAndShowOtherOne()), &form1, SLOT(show())); form1.show(); return app.exec(); }
Here is my final output.
Thanks for your help. I am still learning, and this is more trial and error for me.. If you see where I can improve let me know.
I tried 3 ways...
I tried first by including Form1 into Form 2 and Form 2 into Form 1, this worked but did not allow a manageable solution.
I tried to use signal and slots to manage and call the other forms which worked well but I am new to Signal and Slots and it seemed like a lot of work to emit signals and catch slots for every little small action I wanted to take. This was probably the best way but it really seemed confusing if I added to many actions.
I just included the bootstrap class in Form1 and Form2 and referenced the bootstrap class header file. This third option seems more manageable and it's very easy to add more forms or objects such as a database.
If you have a suggestion please let me know. | https://forum.qt.io/topic/73273/bootstrap-structure-is-this-possible | CC-MAIN-2022-21 | en | refinedweb |
A markdown editor component for your SwiftUI apps.
Either use Xcode to add the package dependency or add the following dependency to your Package.swift:
.package(url: " from: "0.2.1"),
import SwiftDown import SwiftUI struct ContentView: View { @State private var text: String = "" var body: some View { SwiftDownEditor(text: $text) .insetsSize(40) .theme(Theme.BuiltIn.defaultDark.theme()) } }
SwiftDown supports theming by using config
.json files as this one
Then init your custom theme as below.
Theme(themePath: Bundle.main.path(forResource: "my-custom-theme", ofType: "json"))
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics | https://swiftpack.co/package/qeude/SwiftDown | CC-MAIN-2022-21 | en | refinedweb |
How to Create a Swing CRUD Application on NetBeans Platform 6.8
How to Create a Swing CRUD Application on NetBeans Platform 6.8
Join the DZone community and get the full member experience.Join For Free
Get the Edge with a Professional Java IDE. 30-day free trial.:
Wrapping.
Integrating CRUD Functionality
In order to create CRUD functionality that integrates smoothly with the NetBeans Platform, some very specific NetBeans Platform coding patterns need to be implemented. The sections that follow describe these patterns in detail.
Read
In this section, you change the JTextArea, introduced in the previous section, for a NetBeans Platform explorer view. NetBeans Platform explorer views are Swing components that integrate better with the NetBeans Platform than standard Swing components do. Among other things, they support the notion of a context, which enables them to be context sensitive.
Representing your data, you will have a generic hierarchical model provided by a NetBeans Platform Node class, which can be displayed by any of the NetBeans Platform explorer views. This section ends with an explanation of how to synchronize your explorer view with the NetBeans Platform Properties window.
-:
import demo.Customer;
import java.beans.IntrospectionException;
import java.util.List;
import org.openide.nodes.BeanNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
public class CustomerChildFactory extends ChildFactory<Customer> {
private List<Customer> resultList;
public CustomerChildFactory(List<Customer> resultList) {
this.resultList = resultList;
}
@Override
protected boolean createKeys(List<Customer> list) {
for (Customer customer : resultList) {
list.add(customer);
}
return true;
}
@Override
protected Node createNodeForKey(Customer c) {
try {
return new BeanNode(c);
} catch (IntrospectionException ex) {
Exceptions.printStackTrace(ex);
return null;
}
}
}
- Back in the CustomerTopComponent, use the ExplorerManager to pass the result list from the JPA query in to the Node:
EntityManager entityManager = Persistence.createEntityManagerFactory("CustomerLibraryPU").createEntityManager();
Query query = entityManager.createQuery("SELECT c FROM Customer.
Now you are able to view your data in a tree hierarchy, as you would be able to do with a JTree. However, you're also able to swap in a different explorer view without needing to change the model at all because the ExplorerManager mediates between the model and the view. Finally, you are now also able to synchronize the view with the Properties window.
Update.
- Create a new module, named CustomerEditor, with org.shop.editor as its code name base.
- Right-click the CustomerEditor module and choose New | Window Component. Make sure to specify that the window should appear in the editor position and that it should open when the application starts. In the final panel of the wizard, set "Editor" as the class name prefix.
- Use the Palette (Ctrl-Shift-8) to add two JLabels and two JTextFields to the new window. Set the texts of the labels to "Name" and "City" and set the variable names of the two JTextFields to jTextField1 and jTextField2.
In the GUI Builder, the window should now look something like this:
- Go back to the CustomerViewer module and change its layer.xml file to specify that the CustomerTopComponent window will appear in the explorer mode.
Note: Right-click the application project and choose "Clean", after changing the layer.xml file. Why? Because whenever you run the application and close it down, the window positions are stored in the user directory. Therefore, if the CustomerViewer was initially displayed in the editor mode, it will remain in the editor mode, until you do a "Clean", thus resetting the user directory (i.e., thus deleting the user directory) and enabling the CustomerViewer to be displayed in the position currently set in the layer.xml file.
- Run the application and make sure that you see the following when the application starts up:
- Now we can start adding some code. Firstly, we need to show the currently selected Customer object in the editor:
- Start by tweaking the CustomerViewer module so that the current Customer object is added to the viewer window's Lookup whenever a new Node is selected. Do this by creating an AbstractNode, instead of a BeanNode, in the CustomerChildFactory class. That enables you to add the current Customer object to the Lookup of the Node, as follows (note the "Lookups.singleton(c)" below):
@Override
protected Node createNodeForKey(Customer c) {
Node node = new AbstractNode(Children.LEAF, Lookups.singleton(c));
node.setDisplayName(c.getName());
node.setShortDescription(c.getCity());
return node;
// try {
// return new BeanNode(c);
// } catch (IntrospectionException ex) {
// Exceptions.printStackTrace(ex);
// return null;
// }
}
- Let's now change the editor module in such a way that its window will end up listening for Customer objects being added to the Lookup. First, set a dependency in the editor module on the module that provides the entity class, as well as the module that provides the persistence JARs.
- Next, change the EditorTopComponent class signature to implement LookupListener:
public final class EditorTopComponent extends TopComponent implements LookupListener
- Override the resultChanged so that the JTextFields are updated whenever a new Customer object is introduced into the Lookup:
@Override
public void resultChanged(LookupEvent lookupEvent) {
Lookup.Result r = (Lookup.Result) lookupEvent.getSource();
Collection<Customer> coll = r.allInstances();
if (!coll.isEmpty()) {
for (Customer cust : coll) {
jTextField1.setText(cust.getName());
jTextField2.setText(cust.getCity());
}
} else {
jTextField1.setText("[no name]");
jTextField2.setText("[no city]");
}
}
- Now that the LookupListener is defined, we need to add it to something. Here, we add it to the Lookup.Result obtained from the global context. The global context proxies the context of the selected Node. For example, if "Ford Motor Co" is selected in the tree hierarchy, the Customer object for "Ford Motor Co" is added to the Lookup of the Node which, because it is the currently selected Node, means that the Customer object for "Ford Motor Co" is now available in the global context. That is what is then passed to the resultChanged, causing the text fields to be populated.;
}
- Finally, declare the result variable at the top of the class, like this:
private Lookup.Result result = null;
- Run the application again and notice that the editor window is updated whenever you select a new Node:
However, notice.
Now, whenever a new Node is created, which happens when the user selects a new customer in the viewer, a new Customer object is added to the Lookup of the Node.
Since the editor window is opened when the application starts, the LookupListener is available at the time that the application starts up.
Rewrite this line:
result = Utilities.actionsGlobalContext().lookupResult(Customer.class);
To this:
result = WindowManager.getDefault().findTopComponent("CustomerTopComponent").getLookup().lookupResult(Customer.class);
The string "CustomerTopComponent" is the ID of the CustomerTopComponent, which is a string constant that you can find in the source code of the CustomerTopComponent. One drawback of the approach above is that now our EditorTopComponent only works if it can find a TopComponent with the ID "CustomerTopComponent". Either this needs to be explicitly documented, so that developers of alternative editors can know that they need to identify the viewer TopComponent this way, or you need to rewrite the selection model, as described here by Tim Boudreau.
If you take one of the above approaches, you will find that the context is not lost when you switch the focus to the EditorTopComponent, as shown below:
Note: Since you are now using AbstractNode, instead of BeanNode, no properties are shown in the Properties window. You need to provide these yourself, as described in the Nodes API Tutorial.
- Secondly, let's work on the Undo/Redo functionality. What we'd like to have happen is that whenever the user makes a change to one of the JTextFields, the "Undo" button and the "Redo" button, as well as the related menu items in the Edit menu, become enabled. To that end, the NetBeans Platform makes the UndoRedo.Manager available.
- Declare and instantiate a new UndoRedoManager at the top of the EditorTopComponent:
private UndoRedo.Manager manager = new UndoRedo.Manager();
- Next, override the getUndoRedo() method in the EditorTopComponent:
@Override
public UndoRedo getUndoRedo() {
return manager;
}
- In the constructor of the EditorTopComponent, add a KeyListener to the JTextFields and, within the related methods that you need to implement, add the UndoRedoListeners:
jTextField1.getDocument().addUndoableEditListener(manager);
jTextField2.getDocument().addUndoableEditListener(manager);
- Run the application and show the Undo and Redo functionality in action, the buttons as well as the menu items. The functionality works exactly as you would expect..
- Thirdly, we need to integrate with the NetBeans Platform's Save functionality:
- By default, the "Save All" button is available in the NetBeans Platform toolbar. In our current scenario, we do not want to save "all", because "all" refers to a number of different documents. In our case, we only have one "document", which is the editor that we are reusing for all the nodes in the tree hirerarchy. Remove the "Save All" button and add the "Save" button instead, by adding the following to the layer file of the CustomerEditor module:
<folder name="Toolbars">
<folder name="File">
<file name="org-openide-actions-SaveAction.shadow">
<attr name="originalFile" stringvalue="Actions/System/org-openide-actions-SaveAction.instance"/>
<attr name="position" intvalue="444"/>
</file>
<file name="org-openide-actions-SaveAllAction.shadow_hidden"/>
</folder>
</folder>
- Set dependencies on the Dialogs API and the Nodes API.
- In the EditorTopCompontn constructor, add a call to fire a method (which will be defined in the next step) whenever a change is detected:
public EditorTopComponent() {
...
...
...
jTextField1.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent arg0) {
fire(true);
}
public void removeUpdate(DocumentEvent arg0) {
fire(true);
}
public void changedUpdate(DocumentEvent arg0) {
fire(true);
}
});
jTextField2 SaveCookieImpl();
//Create a new instance of our dynamic object:
content = new InstanceContent();
//Add the dynamic object to the TopComponent Lookup:
associateLookup(new AbstractLookup(content));
}
...
...
...
- Here are the two methods referred to above. First, the method that is fired whenever a change is detected. An implementation of the SaveCookie from the Nodes API is added to the InstanceContent whenever a change is detected:
public void fire(boolean modified) {
if (modified) {
//If the text is modified,
//we add SaveCookie impl to Lookup:
content.add(impl);
} else {
//Otherwise, we remove the SaveCookie impl from the lookup:
content.remove(impl);
}
}
private class SaveCookieImpl implements SaveCookie {
@Override.
}
}
}
- Run the application and notice the enablement/disablement of the Save button:
- Next, we add JPA code for persisting our change. Do so by replacing the comment "//Implement your save functionality here." The comment should be replaced by all of the following:
EntityManager entityManager = Persistence.createEntityManagerFactory("CustomerLibraryPU").createEntityManager();
entityManager.getTransaction().begin();
Customer c = entityManager.find(Customer.class, customer.getCustomerId());
c.setName(jTextField1.getText());
c.setCity(jTextField2.getText());
entityManager.getTransaction().commit();
When you now run the application, you will see a different icon in the toolbar. Instead of the "Save All" button, you now have the "Save" button available.
Note: Right now, nothing happens when you click OK in the dialog above. In the next step, we add some JPA code for handling persistence of our changes.
Note: The "customer" in customer.getCustomerId() is currently undefined. Add the line "customer = cust;" in the resultChanged (as shown;
jTextField1.setText(customer.getName());
jTextField2.setText(customer.getCity());
}
} else {
jTextField1.setText("[no name]");
jTextField2.setText("[no city]");
}
}
- Run the application and change some data. Currently, we have no "Refresh" functionality (that will be added in the next step) so, to see the changed data, restart the application. Here, for example, the tree hierarchy shows the persisted customer name for "Toyota Motor Co":
- Fourthly,.
- In the main package of the CustomerViewer module, create a new Node, which will replace the AbstractNode that we are currently using as the root of the children in the viewer. Note that we also bind a "Refresh" action to our new root node.
public class CustomerRootNode extends AbstractNode {
public CustomerRootNode(Children kids) {
super(kids);
setDisplayName("Root");
}
@Override
public Action[] getActions(boolean context) {
Action[] result = new Action[]{
new RefreshAction()};
return result;
}
private final class RefreshAction extends AbstractAction {
public RefreshAction() {
putValue(Action.NAME, "Refresh");
}
public void actionPerformed(ActionEvent e) {
CustomerTopComponent.refreshNode();
}
}
}
- Add this method to the CustomerTopComponent, for refreshing the view:)));
}
- In your save functionality, add the call to the method above so that, whenever data is saved, an automatic refresh takes place. You can take different approaches when implementing this extension to the save functionality. For example, you might want to create a new module that contains the refresh action. That module would then be shared between the viewer module and the editor module, providing functionality that is common to both.
- Run the application again and notice that you have a new root node, with a "Refresh" action:
- Make a change to some data, save it, invoke the Refresh action, and notice that the viewer is updated.
Now replace the code above in the constructor of the CustomerTopComponent with a call to the above. As you can see, we are now using our CustomerRootNode instead of the AbstractNode. The CustomerRootNode includes the "Refresh" action, which calls the code above.
Also check that the BeanTreeView in the CustomerViewer will stretch horizontally and vertically when the user resizes the application. Check this by opening the window, selecting the BeanTreeView, and then clicking the arrow buttons in the toolbar of the GUI Builder..
Create
In this section, you allow the user to create a new entry in the database.
- Right-click the CustomerEditor module and choose "New Action". Use the New Action wizard to create a new "Always Enabled" action. The new action should be displayed anywhere in the toolbar and/or anywhere in the menu bar. In the next step of the wizard, call the action NewAction.
Note: Make sure that you have a 16x16 icon available, which the wizard forces you to select if you indicate that you want the action to be invoked from the toolbar.
- In the New action, let the TopComponent be opened, together with emptied JTextFields:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public final class NewAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
EditorTopComponent tc = EditorTopComponent.getDefault();
tc.resetFields();
tc.open();
tc.requestActive();
}
}
Note: The action implements the ActionListener class, which is bound to the application via entries in the layer file, put there by the New Action wizard. Imagine how easy it will be when you port your existing Swing application to the NetBeans Platform, since you'll simply be able to use the same Action classes that you used in your original application, without needing to rewrite them to conform to Action classes provided by the NetBeans Platform!
- In the SaveCookie, ensure that a return of null indicates that a new entry is saved, instead of an existing entry being updated:);
EntityManager entityManager = Persistence.createEntityManagerFactory("CustomerLibraryPU").createEntityManager();
entityManager.getTransaction().begin();
if (customer.getCustomerId() != null) {
Customer c = entityManager.find(Customer.class, cude.getCustomerId());
c.setName(jTextField1.getText());
c.setCity(jTextField2.getText());
entityManager.getTransaction().commit();
} else {
Query query = entityManager.createQuery("SELECT c FROM Customer c");
List<Customer> resultList = query.getResultList();
customer.setCustomerId(resultList.size()+1);
customer.setName(jTextField1.getText());
customer.setCity(jTextField2.getText());
//add more fields that will populate all the other columns in the table!
entityManager.persist(customer);
entityManager.getTransaction().commit();
}
}
}
- Run the application again and add a new customer to the database.
In the EditorTopComponent, add the following method for resetting the JTextFields and creating a new Customer object:
public void resetFields() {
customer = new Customer();
jTextField1.setText("");
jTextField2.setText("");
}
In this section, let the user delete a selected entry in the database. Using the concepts and code outlined above, implement the Delete action yourself.
- Create a new action, DeleteAction. Decide whether you want to bind it to a Customer node or whether you'd rather bind it to the toolbar, the menu bar, keyboard shortcut, or combinations of these. Depending on where you want to bind it, you will need to use a different approach in your code. Read the article again for help, especially by looking at how the "New" action was created, while comparing it to the "Refresh" action on the root node.
- Get the current Customer object, return an 'Are you sure?' dialog, and then delete the entry. For help on this point, read the article again, focusing on the part where the "Save" functionality is implemented. Instead of saving, you now want to delete an entry from the database.
See Also
This concludes the article. You have learned how to create a new NetBeans Platform application with CRUD functionality for a given database. You have also seen many of the NetBeans APIs in action. For more information about creating and developing applications on the NetBeans Platform, see the following resources: }} | https://dzone.com/articles/crud-on-netbeans-platform | CC-MAIN-2018-30 | en | refinedweb |
Spring Security Run-As example using annotations and namespace configuration
Spring Security Run-As example using annotations and namespace configuration
Join the DZone community and get the full member experience.Join For Free
Learn more about how CareerBuilder was able to resolve customer issues 5x faster by using Scalyr, the fastest log management tool on the market.
Spring Security offers an authentication replacement feature, often referred to as Run-As, that can replace the current user's authentication (and thus permissions) during a single secured object invocation. Using this feature makes sense when a backend system invoked during request processing requires different privileges than the current application.
For example, an application might want to expose a financial transaction log to the currently logged in user, but the backend system that provides it only permits this action to the members of a special "auditor" role. The application can not simply assign this role to the user as that would potentially permit them to execute other restricted actions. Instead, the user can be given this right exclusively for viewing their transaction log.
Only two classes are used to implement this feature. Instances of
RunAsManager are tasked with producing the actual replacement authentication tokens. A sensible default implementation is already provided by Spring Security. As with other types of authentication, it is also necessary to register an instance of an appropriate
AuthenticationProvider.
<bean id="runAsManager" class="org.springframework.security.access.intercept.RunAsManagerImpl"> <property name="key" value="my_run_as_key"/> </bean> <bean id="runAsAuthenticationProvider" class="org.springframework.security.access.intercept.RunAsImplAuthenticationProvider"> <property name="key" value="my_run_as_key"/> </bean>
runAsManagerare signed with the provided key (
my_run_as_keyin the example above) and are later checked against the same key by
runAsAuthenticationProvider, in order to mitigate the risk of fake tokens being provided. These keys can have any value, but need to be the same in both objects. Otherwise,
runAsAuthenticationProviderwill reject the produced tokens as invalid.
If an instance is registered,
RunAsManager will be invoked by
AbstractSecurityInterceptor for every intercepted object invocation for which the user has already been given access. If
RunAsManager returns a token, this token will be used be used instead of the original one for the duration of the invocation, thus granting the user different privileges. There are two key points here. In order for the authentication replacement feature to do anything, the call has to actually be secured (and thus intercepted), and the user has to already have been granted access.
To register a
RunAsManager instance with the method security interceptor, something similar to the following is needed:
<global-method-security
Now, all methods secured by the
@Secured annotation will be able to trigger
RunAsManager. One important point here is that
global-method-security will only work in the Spring context in which it is defined. In Spring MVC applications, there usually are two Spring contexts: the parent context, attached to
ContextLoaderListener, and the child context, attached
toDispatcherServlet. To secure
Controller methods in this way,
global-method-security must be added to
DispatcherServlet's context. To secure methods in beans not in this context,
global-method-security should also be added to
ContextLoaderListener's context. Otherwise, security annotations will be ignored.
The default implementation of
RunAsManager (
RunAsManagerImpl) will inspect the secured object's configuration and if it finds any attributes prefixed with
RUN_AS_, it will create a token identical to the original, with the addition of one new
GrantedAuthorty per
RUN_AS_ attribute found. The new
GrantedAuthority will be a role (prefixed by
ROLE_ by default) named like the found attribute without the
RUN_AS_ prefix.
So, if a user with a role
ROLE_REGISTERED_USER invokes a method annotated with
@Secured({"ROLE_REGISTERED_USER","RUN_AS_AUDITOR"}), e.g.
@Controller public class TransactionLogController { @Secured({"ROLE_REGISTERED_USER","RUN_AS_AUDITOR"}) //Authorities needed for method access and authorities added by RunAsManager prefixed with RUN_AS_ @RequestMapping(value = "/transactions", method = RequestMethod.GET) //Spring MVC configuration. Not related to security @ResponseBody //Spring MVC configuration. Not related to security public List<Transaction> getTransactionLog(...) { ... //Invoke something in the backend requiring ROLE_AUDITOR { ... //User does not have ROLE_AUDITOR here }
the resulting token created by
RunAsManagerImpl with be granted
ROLE_REGISTERED_USER and
ROLE_AUDITOR. Thus, the user will also be allowed actions, normally reserved for
ROLE_AUDITOR members, during the current invocation, permitting them, in this case, to access the transaction log.To enable
runAsAuthenticationProvider, register it as usual:
<authentication-manager <authentication-provider ... other authentication-providers used by the application ... </authentication-manager>
This is all that is necessary to have the default implementation activated.
Still, this setting will not work for methods secured by
@PreAuthorize and
@PostAuthorize annotations as their configuration attributes are differently evaluated (they are SpEL expressions and not a simple list or required authorities like with
@Secured) and will not be recognized by
RunAsManagerImpl. For this scenario to work, a custom
RunAsManager implementation is required, as, at least at the time of writing, no applicable implementation is provided by Spring.
A custom
RunAsManager implementation for use with
@PreAuthorize/
A convenient implementation relying on a custom annotation is provided below:
public class AnnotationDrivenRunAsManager extends RunAsManagerImpl { @Override public Authentication buildRunAs(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { if(!(object instanceof ReflectiveMethodInvocation) || ((ReflectiveMethodInvocation)object).getMethod().getAnnotation(RunAsRole.class) == null) { return super.buildRunAs(authentication, object, attributes); } String roleName = ((ReflectiveMethodInvocation)object).getMethod().getAnnotation(RunAsRole.class).value(); if (roleName == null || roleName.isEmpty()) { return null; } GrantedAuthority runAsAuthority = new SimpleGrantedAuthority(roleName); List<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>(); // Add existing authorities newAuthorities.addAll(authentication.getAuthorities()); // Add the new run-as authority newAuthorities.add(runAsAuthority); return new RunAsUserToken(getKey(), authentication.getPrincipal(), authentication.getCredentials(), newAuthorities, authentication.getClass()); } }
This implementation will look for a custom
@RunAsRole annotation on a protected method (e.g.
@RunAsRole("ROLE_AUDITOR")) and, if found, will add the given authority (
ROLE_AUDITOR in this case) to the list of granted authorities.
RunAsRole itself is just a simple custom annotation:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface RunAsRole { String value(); }
This new implementation would be instantiated in the same way as before:
<bean id="runAsManager" class="org.springframework.security.access.intercept.RunAsManagerImpl"> <property name="key" value="my_run_as_key"/> </bean>
And registered in a similar fashion:
<global-method-security <expression-handler </global-method-security>
The expression-handler is always required for pre-post-annotations to work. It is a part of the standard Spring Security configuration, and not related to the topic described here. Both
pre-post-annotations and
secured-annotations can be enabled at the same time, but should never be used in the same class. The protected controller method from above could now look like this:
@Controller public class TransactionLogController { @PreAuthorize("hasRole('ROLE_REGISTERED_USER')") //Authority needed to access the method @RunAsRole("ROLE_AUDITOR") //Authority added by RunAsManager @RequestMapping(value = "/transactions", method = RequestMethod.GET) //Spring MVC configuration. Not related to security @ResponseBody //Spring MVC configuration. Not related to security public List<Transaction> getTransactionLog(...) { ... //Invoke something in the backend requiring ROLE_AUDITOR { ... //User does not have ROLE_AUDITOR here }
Find out more about how Scalyr built a proprietary database that does not use text indexing for their log management tool.
Published at DZone with permission of Bojan Tomić . See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/spring-security-run-example | CC-MAIN-2018-30 | en | refinedweb |
MOUNT_HFS(8) BSD System Manager's Manual MOUNT_HFS(8) NAME mount_hfs — mount an HFS/HFS+ file system SYNOPSIS mount_hfs [-e encoding] [-u uid] [-g gid] [-m mask] [-o options] [-w] [-x] special | node DESCRIPTION The mount_hfs command attaches the HFS file system residing on the device special to the global file system namespace at the location indicated by node. This command is normally executed by mount(8) at boot time. The options are as follows: -e encoding (standard HFS volumes only) Specify the Macintosh encoding. The following encodings are sup‐ ported: Arabic, ChineseSimp, ChineseTrad, Croatian, Cyrillic, Greek, Hebrew, Icelandic, Japanese, Korean, Roman (default), Romanian, Thai, Turkish ‐. -o Options are specified with a -o flag followed by a comma sepa‐ rated string of options. See the mount(8) man page for possible options and their meanings. [top] | http://www.polarhome.com/service/man/?qf=mount_hfs&tf=2&of=OpenDarwin&sf=8 | CC-MAIN-2018-30 | en | refinedweb |
I immediately bought the other day bicycle motor-wheel . It has long dreamed of , and here it is, in all its glory !
The DC motor , valve , 48V , 500vat . The Chinese have promised an efficiency of about 85 % , which is not bad for such a moschnosti.K it was complete controller 800 watts, the throttle and brakes. The battery pack - 4 pieces , 12c , 9a/chasov and charger to them acquired separately .
I gathered all this stuff on my old mountain is great
First impressions of the electric drive train just beyond words ! Maximum torque right from the start ( accelerate faster than 50cc scooter ) , the maximum speed of 45 km / h.
Break in this whole thing , I wanted to tie it to some kind of feature, that realties to indicate the cost of energy. Then he asked for a digital power meter.
In the previous article we learned how to measure the voltage voltage and current. To measure the power consumption should be multiplied by the current voltage : W = B * A. In fact, the power meter - is ammeter and voltmeter in a single device . Let us join the scheme ammeter and voltmeter as described in previous articles, and obtain the circuit power meter :
Power meter is built on the microcontroller atmega8, which is deserved status of people . Current, voltage and power output to the display Lcd- 16x2.
Resistors R8, R9 built a voltage divider with a division factor 11 , a voltage reference is made in a regulated and TL431 zener voltage is set to 5.12 volt.Tok is measured by measuring the voltage drop across the shunt R2, further shunt voltage is amplified by the operational amplifier Lm358 and the input of the ADC adc0.
The program is written CodeVisionAVR
# include <mega8.h>
# include <delay.h>
# include <stdio.h> // library which contains the function sprintf
// Alphanumeric LCD Module functions
# asm
. equ __ lcd_port = 0x12; PORTD
# endasm
# include <lcd.h>
# define ADC_VREF_TYPE 0x00
// Read the AD conversion result
unsigned int read_adc (unsigned char adc_input)
{
ADMUX = adc_input | (ADC_VREF_TYPE & 0xff);
// Delay needed for the stabilization of the ADC input voltage
delay_us ( 10 );
// Start the AD conversion
ADCSRA | = 0x40;
// Wait for the AD conversion to complete
while ((ADCSRA & 0x10) == 0 );
ADCSRA | = 0x10;
return ADCW;
}
void main (void)
{
char buffer [ 32 ] ; // variable which will form the string for output to lcd
unsigned long int u; // variable to store the voltage in millivolts
unsigned long int a; // variable to store the current
unsigned long int w; // variable to store the values of power consumption
PORTB = 0x00;
DDRB = 0x00;
// Port C initialization
PORTC = 0x00;
DDRC = 0x00;
// Port D initialization
PORTD = 0x00;
DDRD = 0x00;
// Timer / Counter 0 initialization
TCCR0 = 0x00;
TCNT0 = 0x00;
// Timer / Counter 1 initialization;
// Timer / Counter 2 initialization
ASSR = 0x00;
TCCR2 = 0x00;
TCNT2 = 0x00;
OCR2 = 0x00;
// External Interrupt (s) initialization
MCUCR = 0x00;
// Timer (s) / Counter (s) Interrupt (s) initialization
TIMSK = 0x00;
// Analog Comparator initialization
ACSR = 0x80;
SFIOR = 0x00;
// ADC initialization
// ADC Clock frequency: 500,000 kHz
// ADC Voltage Reference: AREF pin
ADMUX = ADC_VREF_TYPE & 0xff;
ADCSRA = 0x81;
// LCD module initialization
lcd_init ( 16 );
while (1 )
{
a = read_adc ( 0 ) // read ADC value from port 0
u = read_adc ( 1 ) // read ADC value from port 1
/*
1. Measure current
The current flowing through the shunt , vichislyaetsya by Ohm's law : I = U / R
R = 0,1 Ohm , a U ( voltage drop across the shunt ) will be measured .
Since the ADC have a 10-bit , the maximum number that the function will return read_adc, ()
will be equal to 1024, this number is equivalent to the input voltage adc0.
For example, if read_adc () returned 512 then it means that the input adc0 E filed half a reference voltage
To calculate the actual stress , we need to make a proportion :
reference voltage - 1024
the desired voltage - a
We reference voltage = 5.12
The required voltage = 5.12 * a/1024, or Seeking voltage = 0,005 * a
For simplicity translate volts in millivolts by multiplying by 1000
The required voltage = 0,005 * a * 1000
Everything is good here , but we do not take into account the coefficient of op amp
calculated by the formula : Gain = 1 + R1/R2. Substituting , we get :
Gain = (1 + 4) = 5
The actual voltage = 0,005 * a * 1000/5 , we get just a
2. Measure voltage
Next measure the voltage across the resistor divider
We form a proportion , as described above, and we get :
The required voltage = 0,005 * u * 1000
We must also take into account the coefficient of the resistor voltage divider
We it is Kdel = (R1 + R2) / R2. Substituting , we get :
Kdel = (10 +1 ) / 1 = 11
The actual voltage = 0,005 * u * 1000 * 11
*/
u = 55 * u; // calculate the voltage in millivolts
a = a * 10 // calculate the current value according to Ohm's law : I = U / R = a/100 * 1000 = a * 10 miliamperah
w = a * u; // calculate the power consumption
sprintf (buffer, "I =% u,% u U =% u,% u W =% u,% lu",
a/1000, // The whole honor current
(a% 1000) / 10 // The fractional part of the current
u/1000, // integer part of voltage
(u% 1000) / 10 // The fractional part of the voltage
w/1000000, // Integer part of the power
(w% 1000000) / 10000
) // Form a line to output
lcd_clear (); // clean the screen before displaying
lcd_puts (buffer); // deduce the formation of the string to display
delay_ms ( 100), // make the delay
};
}
The project is in the Proteus and the source code of the program in the archive Watmeter.rar
Комментарии - (8) | http://articles.greenchip.com.ua/3-0-31-2.html | CC-MAIN-2018-30 | en | refinedweb |
US9438588B2 - Passporting credentials between a mobile app and a web browser - Google PatentsPassporting credentials between a mobile app and a web browser Download PDF
Info
- Publication number
- US9438588B2US9438588B2 US14530329 US201414530329A US9438588B2 US 9438588 B2 US9438588 B2 US 9438588B2 US 14530329 US14530329 US 14530329 US 201414530329 A US201414530329 A US 201414530329A US 9438588 B2 US9438588 B2 US 9438588B2
- Authority
- US
- Grant status
- Grant
- Patent type
-
- Prior art keywords
- session
- web
- device
- app
-67/00—Network-specific arrangements or communication protocols supporting networked4/00—Services specially adapted for wireless communication networks; Facilities therefor
-
Description
This application is a continuation of, and claims the benefit of priority from, co-pending U.S. patent application Ser. No. 13/162,842, filed Jun. 17, 2011, which is hereby incorporated by reference in its entirety.
1. Technical Field
The present disclosure generally relates to providing secure communications for users of electronic devices running native apps and, more particularly, for facilitating authenticated communication sessions from a client device using both native applications and web browsers concurrently from the same device.
2. Related Art
Consumer mobile devices—such as smart phones, personal digital assistants, note pads, web-enabled pods, and players—and other devices—such as point of sale (POS) terminals and ticket kiosks—may provide functionality to the user of the device by executing application software, known as “apps”. A “native” app—which may be downloadable or may come pre-packaged with hardware or an operating system, for example—is typically a software application specially designed to execute on a particular device, and there are many well-known apps for various particular mobile devices. Functionality may also be provided via what may be known as a “web app”, which is not a piece of downloadable software, but actually a web site that is optimized for viewing, for example, on a particular mobile device, such as an iPhone®. For a software developer, creating a true native app (e.g., application programming interface (API)-based module) may take anywhere from 5 to 20 times more effort to implement and push to production than re-using an already built and available web-based functionality.
Both native apps and web apps may provide relative advantages, however, depending on the functionality desired to be obtained. For example, use of a native app may be better for situations in which the functionality of the app needs to take advantage of features built into a device, such as motion detection, voice recording, voice recognition, camera, and global positioning system (GPS). A native app may be better if it is desired for the content or service provided by the app to be available offline (e.g., in the absence of an Internet connection). On the other hand, use of a web app may be better for situations in which a web site and its content already exists and it is desired to provide the same content to many users, optimized for viewing by users of many different types of devices.
According to one or more embodiments of the present invention, methods and systems for passporting credentials provide a mechanism by which a native app on a device can invoke a service provider's core web site web addresses (usually specified using a “uniform resource locator” or. Broadly, the mechanism provides the user authentication session ID to the embedded browser—also referred to as “web view control”—to access a web site's URL for a specific web command, view, or flow that requires the user's credentials to be used. The unique session identifier may be passed into the browser in place of the user's credentials to allow for the continuation of the authenticated session. The embedded browser is now the primary means of the user's interaction and this keeps the session current (e.g., not timed-out), allowing the user to continue using the web interface. Communication from the browser back to the native app may be accomplished by the native app monitoring URLs requested by the embedded browser, with requests for certain URLs indicating particular actions to be taken by the native app. Once the web portion of the flow is done the user returns to the native app, and the session keeps going in the native app context of the existing session. Embodiments may allow for better user experience as the users will not need to re-authenticate themselves when continuing the same session on the same device.
In one or more embodiments, a system includes: a client device executing a native app and an embedded web browser, in which the native app has a device session token that provides a session authentication with a server for a device session between the native app and the server, in which the session authentication is based on credentials for authenticating a user; and the native app invokes the embedded web browser, providing the embedded web browser with the device session token based on the credentials, in which the device session token provides authentication for the session on the embedded web browser.
In another embodiment, a computer-implemented method includes: authenticating a device session from a native app executing on a client device; producing a device session token from the authentication; passing the device session token to authenticate a user when entering a web flow; and entering the web flow on an embedded browser driven by the native app, in which a web flow session continues the device session based on the authentication provided from the device session token.
In a further embodiment, a computer program product comprises a non-transitory computer readable medium having computer readable and executable code for instructing a processor to perform a method that includes: authenticating a device session from a native app executing on a client device; producing a device session token from the authentication; passing the device session token to authenticate a user when entering a web flow; and entering the web flow on an embedded browser invoiced by the native app, in which a web flow session continues the device session based on the authentication provided from the device session token.
In accordance with embodiments of the present invention, passporting credentials is a mechanism by which a native app can invoke core web site uniform resource locators (or URLs) of an entity while keeping an existing user session active and keeping the session shared between the two user experiences (native app and web site) so that the user doesn't need to re-login at each context switch between native app and web site.
In some situations, it may be desirable to try to combine the advantages of both native apps and web apps by accessing a web site from within a native app. When authentication is needed, e.g., the user signs in to an account with a user identification (ID) and then provides a password to access the account, security may require that a separate, new authenticated session be started for the web app when the user enters the web app from the native app. A best practice for maintaining security is that the newly authenticated session in the web app may entail termination of the authenticated session in the native app to avoid running parallel authenticated sessions. Thus, when the user finishes with the web app portion of the functionality, the user may be required to log back in from within the native app to continue with the native app portion of the functionality. Such a user experience may be disruptive for the user and may effectively prevent or make impractical the use of many desirable and possible types of functionalities.
The entity providing a web site may be, for example, a financial service provider (FSP)—such as PayPal, Inc. of San Jose, Calif.—in which a consumer or vendor using the service may have an account with the FSP (referred to as an “FSP account”). The user may log in to the user's account by providing user credentials, such as a user name and password, that can be used to generate a user authentication session ID. The user authentication session ID may be provided to the embedded web browser (also referred to as “web view control”) to access the entity's web site URL for a specific web command, view, or flow that requires the user's credentials to be used. The unique session identifier is passed into the browser in place of the user's credentials to allow for the continuation of the authenticated session between the native app and the browser. The browser may become the primary means of the user's interaction and the passported session identifier keeps the session current (not timed-out) allowing the user to continue utilizing the web interface. Once the web portion of the flow is done the user may return to native app and the session may keep going in the existing session context that exists in the native app.
Passporting credentials in accordance with one or more embodiments may allow for better user experience as users would not need to re-authenticate themselves when continuing the same session (from native app to embedded browser or vice versa) on the same device. For example, an authenticated session may be initiated when the user starts a native app and provides authentication credentials to an application programming interface (API) for authentication, and the authentication API returns a session token back to the native app. That session token is conventionally used as a mechanism by which the native app authenticates itself in all the subsequent API calls. That session token conventionally is refreshed with each and every API call made. If the user then launches a web site, the user would need to provide the same set of credentials, and a new session would be started for the web browser, which is separate from the session started on the app. (Conventionally, security concerns may then dictate terminating the native app session.) One embodiment may instead continue the previously started session and port its credentials into the web browser, allowing the user to seamlessly continue with the user interface (UI) flow without the need for the user to re-authenticate. Ideally, an average user would not notice a difference in experience when jumping from a native app UI into a web flow and back into the native app's UI.
By providing seamless transitioning to already built and available web-based functionality, one or more embodiments may allow an entity such as an FSP to provide their apps with a richer feature set for users much earlier than by the more usual means of creating a true native app API-based module, which may take anywhere from 5 to 20 times more effort to implement and push to production than re-using an already built and available web-based functionality. For example, the way native mobile apps are developed at one FSP may be heavily geared towards replicating functionality that exists on the FSP's main web site and “porting” it to the new app. As simple as it may seem on the surface, the process usually requires new APIs to be created to allow mobile app access to core FSP data and services. This approach generally provides no new functionality (albeit there's a new UI and a native app experience) and unnecessarily pollutes the API namespace with too many utility functions while accelerating the addition of those new APIs, thus further compounding the problem of the API set growing too fast and uncontrollably. The approach enabled by one or more embodiments may re-use the existing rich web functionality and allow seamless transitioning between native app's UI and the web site. A critical factor in this experience is that the user does not need to re-login when switching between the native app and the web site, which provides the desired non-disruptive user experience.
Client device 104 may include an application 114 (also referred to as “app”) and a web browser 116 (which may be embedded in app 114) that execute on client device 104. Client device 104 may provide an ability to support HTTP protocol in a code which may be, for example, either running inside the application's memory space or in an external module that is directly controlled (driven) by the application, for example, in cases where the operating system (OS) or device or mobile device platform may support a type of cross-application control where the driven app is running outside the driver app's memory space. For example, app 114 may drive the execution of embedded browser 116 via execution flow 115 in which a “Mobile flow URL” and a “token” are two pieces of data sent into embedded web browser 116 so that embedded browser 116 knows: a) which URL to request; and b) what authentication data to provide. Execution flow 115 may be transparent (e.g., not noticeable) to the user and may include the passing of various foams of information back and forth between app 114 and embedded web browser 116, such as URLs and tokens, as shown in
The entity's (or FSP's, for example) infrastructure 102 may include a server 106, a common gateway interface (CGI) 108 serving web traffic, and a database 110. Server 106 may enable communication 107 between infrastructure 102 and application 114 (also referred to as “app”) executing on client device 104. The expression “native app” generally may be used to describe that application 114 may be in some sense “optimized” to run on client device 104.
CGI 108 may be a process executing on a computer in the infrastructure 102 belonging to an entity such as an FSP. The CGI 108 may comprise binary code that is proprietary to the entity and may handle web page processing for the entity. CGI 108 may enable communication 109 between infrastructure 102 and embedded web browser 116 executing on client device 104. For example, when a user of client device 104 fills out a form on a web page and sends it in, it usually needs to be processed by an application program (residing in infrastructure 102, for example). A web server (which may be included in infrastructure 102) may pass the form information to the application program that processes the data and which may send back a response message. This method or convention for passing data back and forth between the web server and the (infrastructure) application may be provided by the CGI 108.
Both server 106 and CGI 108 may have access to and be in communication with database 110, as shown in
At step 152, the device session token may be passed into embedded browser 116 as one of the hypertext transfer protocol or secure hypertext transfer protocol (HTTP or HTTPS) GET parameters at execution flow 115 and, subsequently, may be passed to the infrastructure 102 into CGI 108 for processing.
At step 153, the CGI 108 may decode, decrypt, and unpack the passed-in session token and retrieve from database 110 the stored session data that includes, among other things, an authorization object referred to as a “UserAuthToken”. Different user auth token objects may have different timestamps, permissions, and life cycles independently from each other and from the original device session token. Different user auth token objects may be related to one another in that multiple tokens can point to the same user or device session. In this regard, a device token and a web token may be two separate objects that may differ quite substantially yet share the same underlying user or device session. For example, one token may become invalid (expired) while the other token and the user session both remain valid.
At step 154, the UserAuthToken authorization object may be used to authenticate the web session on browser 116, effectively achieving a seamless continuation (e.g., requiring no user re-login at this point) of the already active session running from app 114. For example, the user auth token may be re-packaged (by CGI 108, for example) as a web token sharing the same underlying device session, as described above. In other words, the initial auth token (e.g., the passed-in session token) may be passed into the web flow where it can either be used directly as the web flow's auth token or the initial auth token may be re-packaged into a new auth token that is related to the initial auth token and can be used as the web flow's auth token so long as both tokens share the same underlying user or device session. The second token (e.g., the web token or web auth token) is not required to share the same characteristics as the first token (e.g., the device session token or user auth token) and may have different and independent access rights, lifespan, or other properties.
At step 155, while the web flow (e.g., the continued session from app 114 to embedded browser 116) is in active use (e.g., every new page request is done within the token expiration timeframe) the underlying user session (e.g., the session on app 114 or device session) remains active. For example, the native app 114 may keep refreshing its session token (the device session token, see step 151) by monitoring URL requests from the embedded web browser 116. Thus, if a user is currently logged in with the native app, the web flow session on the embedded browser continues the device session without requiring the user to re-login so that the user encounters a single shared session running at least two parallel secure communication interactions (e.g., communications 107, 109) with the infrastructure 102.
At step 156, once the flow of execution and user interaction returns back into native app 114, the recently refreshed (in app 114) device session token may continue to be valid (e.g., the token has not timed out in the web flow itself) and may be usable to make API calls into the server 106. For example, to ensure the app's device session token (of app 114) is current a call to an appropriate process (e.g., a process tracking the account balance of the user associated with the device session token) running on server 106 may be made every time the embedded browser 116 requests a new URL. Alternatively, a generic “keep-alive” technique may be used in which a call may be made to a low-cost or a specialized keep-alive API to keep refreshing the token.
In general, when a user opens a web app, or an interactive web page from a browser, and performs some operations—such as transferring money between accounts with an FSP—the operations may be built in the form of a web flow. In other words, when the user moves from one operation to another, there is a flow of events and user interaction. The user may sometimes enter sub-flows; for example, when sending money from an FSP account, the user may find there is not enough in one account and may decide to add access to another bank account to fund the transaction (sending money). So then the user may enter a sub-flow for adding access to the bank account and then return to the web flow for sending money and continue with that same web flow. In computer parlance, the flows may be kept track of on a stack (e.g., a “navigation” stack), and when the user is finished with the adding-bank account sub-flow, that sub-flow is “popped” off the stack so that the user returns to the previous web flow.
Any entity—such as an FSP—providing a system 100 having an infrastructure 102 may provide a framework for its web flows in which each web page may include multiple pieces, e.g., states of a process that can be described using a state-transition diagram. A web flow framework may be executed, for example, by CGI 108. For example, there may be a state (or step of a process) for a user to enter a “send money” flow, a state that shows whether a user has someone in a contacts list, a state that shows this contacts list to select someone to send money to, and so forth. Likewise, there may also be subsets of states that correspond to various sub-flows. There may be many states or steps for each web page; some steps may be for displaying or changing the display on the web page, for example, and some steps may function, for example, to make a decision what to do next. Such a decision state may be provided by flow entry point step 204 of process 200 shown in
At step 202, a native app (e.g., app 114) may invoke an embedded browser (e.g., embedded browser 116 running on client device 104 either inside the app's memory space or directly driven by the app) and provide a URL along with one parameter (e.g., the encrypted device session token) to the web flow entry point 204 (e.g., entry point for a web page or service provided by the entity, e.g., an FSP, of infrastructure 102). For example, the device session token may provide a CGI parameter that includes information for CGI 108 to find the correct flow entry point step 204 for a desired web flow to be continued from a point in the execution of app 114.
At step 204, labeled “flow entry point”, a CGI (e.g., CGI 108) may decide whether the passed-in device session token is valid and whether the user's session appears to be still active or whether the session has expired. For example, the CGI may decode, decrypt, and unpack the passed-in device session token and retrieve from database 110 the stored session data that includes an authorization object, e.g., a user authorization token. Based on all the information, the web flow may recognize that the user is logged in and continue on branch 206. If not, the flow may continue on branch 208, as shown.
At branch 206, if the user is logged in (e.g., the native app session is still valid and not expired) the CGI (e.g., CGI 108) may re-package the authorization object (e.g., the user authorization token) to be used as an authorization session token for the web flow. For example, the CGI may extract credentials and other information from the authorization object and add other information—such as key information for accessing database 110 to find information associated with the current session—to re-package the authorization object as a web auth token. The re-packaged authorization object, for example, may be passed to web browser 116 via communication 109 shown in
Branch 208—user not logged in—may be taken, for example, if there is a fatal error, such as the device session token passed at step 202 was for any reason not good enough—e.g., garbled, bogus, empty, or the session had expired—to be able to proceed. At branch 208, if the user is not logged in, then the web flow may begin to dispatch the user into a web login sub-flow, at step 212.
At step 214, the native app (e.g., app 114) that's driving the execution of the embedded browser 116 may intercept the URL (e.g., the URL passed at execution flow 115) and instead navigate the user into an in-app (e.g., in application 114) login dialog, leaving the embedded browser frame. Once logged in (for example, via the native app's 114 dialog) the user may have an option to re-enter the same web flow. Alternatively, the driver app 114 may be smarter (e.g., include additional logic) and first make sure either that the device session token has indeed expired (and then direct the user into a login screen) or that an unrecoverable fatal error has occurred (and then, for example, display an appropriate message to the user, e.g., “try again later”).
Once the application 114 has invoked the web browser 116, however, communication in the direction from web browser 116 to application 114 may be limited. In other words, there may be no direct way for the web flow to signal back to a native app that an error has occurred because the web flow may be completely ignorant of whether or not it has even been invoked by an app. For example, if there is a fatal error in processing a user's request in a web flow—for example, the database is down—the application 114 would not know that the embedded web page failed to render because the web flow will render something (one way or another), and the application 114 will not have capability to check the text of what was rendered to make sure the text was correct (because, for example, the text may vary every time). So, in one or more embodiments, communication back to the driver application (e.g., the application 114 that invoked embedded browser 116) may be implemented by the driver application 114 monitoring the URLs being requested by the browser 116. For example, an embedded web flow may signal events, such as an error condition or exit from the web flow, by requesting pre-defined URLs that are being watched by the driver application. Once one or more of these special, pre-defined URLs is requested, the driver application may intercept the pre-defined special URL and act accordingly.
There are generally two types of errors: system errors that are fatal (non-recoverable) and user errors (recoverable). The web flow should handle the user (recoverable) errors gracefully without help from the driver application.
In case of an unrecoverable fatal error (e.g., internal error or system error) the web flow should redirect the user into the device login URL to signal the driver application 114 that the web flow has encountered an unrecoverable error and must be closed. The user should be able to navigate into the web flow anew, as if it is the first time the flow is being entered, as described below, at step 216.
The rationale behind choosing a login URL for this fatal error condition is as follows: in case there's a (separate) bug in the driver app and the URL interception fails, there is at least a device-specific-skinned web page that takes the device's capabilities (e.g., screen resolution) into account that is being presented to the user. For example, on client device 104 a web page optimized for a mobile device may be presented if client device 104 is a mobile device). For another example, if client device 104 is a voice terminal for blind people, an “audio page” may be the device-specific presentation—which might otherwise have been just a regular block of text—of the information presented to the user on client device 104.
Also in case of tampering with the calling parameters or evidence of corrupted data being sent to the server, it is a standard security measure to send the user back to the login step if the authenticity cannot be verified.
For exit from the web flow, a URL may be registered for an embedded web flow to use that can be recognized by the driver application as an “exit” signal. Once the web flow requests that URL, the driver application may close the embedded web browser, moving the user “back” in the driver application's navigation stack.
Once logged in (via the native app's dialog) the user may, at step 216, have an option to re-enter the same web flow (for example, by passing the same URL and a valid device session token to browser 116 at step 202)..
In this regard, a computer system may include a bus or other communication mechanism for communicating information, which interconnects subsystems and components, such as processing component (e.g., processor, micro-controller, digital signal processor (DSP), etc.), system memory component (e.g., RAM), static storage component (e.g., ROM), disk drive component (e.g., magnetic or optical), network interface component (e.g., modem or Ethernet card), display component (e.g., CRT or LCD), input component (e.g., keyboard or keypad), and/or cursor control component (e.g., mouse or trackball). In one embodiment,.
In various embodiments, execution of instruction sequences for practicing the invention may be performed by a computer system. In various other embodiments, a plurality of computer systems coupled by communication link (e.g., LAN, WLAN, PTSN, or various other wired or wireless networks) may perform instruction sequences to practice the invention in coordination with one another.
Computer system may transmit and receive messages, data, information and instructions, including one or more programs (i.e., application code) through communication link and communication interface. Received program code may be executed by processor as received and/or stored. | https://patents.google.com/patent/US9438588B2/en | CC-MAIN-2018-30 | en | refinedweb |
Talk:Key:ref
Contents
- 1 ref & nat_ref
- 2 Multiple tags
- 3 Spaces
- 4 Standard for the US
- 5 Roads signed as leading to a particular ref
- 6 Names and References
- 7 ref for roles
- 8 Spaces in e-roads
- 9 ref for branch or franchise reference
- 10 GNIS id values
- 11 ids from other web services?
- 12 nation wide refs
- 13 reference to an external collection
- 14 On the ground verifiability of ref tags on roads
ref & nat_ref
Does it make sense to have both tags (ref and nat_ref) defined? At the moment I see a lot of use of nat_ref, where it is used for the street reference number of that country, for example in Germany:
- key="name" value="A123"
- key="highway" value="motorway"
- key="oneway" value="true"
- key="nat_ref" value="A123"
So, does it make sense to have both tags, ref and nat_ref?
Or in the case above, should one use "ref" instead of "nat_ref"?
RalfZ 13:08, 19 September 2006 (BST)
I can't see either way if it's allowed or not to use more than one ref for a way. There are places where two ways run on the same stretch of road for a while - the E6 and E20, for instance, is the same road between Helsingborg and Malmö in Sweden. --KristianThy 13:54, 10 December 2006 (UTC)
Spaces
in Germany, all street references have spaces between the letters and the numbers in the official version -- even the international street references; e.g. the motorway A 61 with the international reference E 31; what about official notation in other countries; the notation privat enterprises use in their maps is not meant here--privat companies often don't care about these things; there also seem to be dashes as a possibilty ... and of course we have some different writing systems in the world - any thoughts about this? -- Schusch 22:40, 5 May 2008 (UTC)
Standard for the US
How should these be used in the US? Should it be a unified scheme with the state abbreviation for state routes (e.g. IN-XX, MI-XX) and I-XX for interstate, US-XX for US highways? Or should we vary by state (Michigan state routes would use M-XX, Interstates would use IH-XX in Texas, many states use something like SR or SH for state routes) Random832 16:33, 18 September 2008 (UTC)
- I follow the scheme outlined in United_States_roads_tagging. So Michigan state route would be ref="US:MI XX" Alexrudd 21:47, 21 December 2008 (UTC)
- That leads to some rather clumsy labeling in the current Mapnik and Osmarender renderers. If these renderers are reconfigured to display this information more elegantly, maybe more people would follow the "US:XX ##" convention. Vid the Kid 16:56, 24 December 2008 (UTC)
For that matter, how should county road numbers be marked? There are some places where the county road number is displayed just as prominently as a state or US route marker. The "conventional" approach of "name=CR ##" works in places where that really is the road's only name, but what about counties that have actual names for roads, in addition to well-signed county road numbers? Vid the Kid 16:56, 24 December 2008 (UTC)
- If there's no ref=, there's no ref=. There's a few state highways in Oregon that don't have a name or a ref! Paul Johnson 20:38, 31 May 2009 (UTC)
Roads signed as leading to a particular ref
Likely in other countries some major but unnumbered roads have signposts guiding to a numbered road, i.e. the other roads number surrounded by a dashed line vs. solid line. I've now tagged these as leads_to_ref=*, in part just to discourage others from tagging these with a wrong ref=*. Mostly this happens where an arterial road leading out of a city center isn't a numbered road for the first kilometers. Any better suggestions? Alv 10:18, 20 September 2008 (UTC)
- I wouldn't think this is appropriate information for OSM. It's not really needed for routing applications, and this kind of information is typically not explicitly shown on maps, as it can be pretty easily seen from the map that such roads lead to such other highways already. If it were actually to be tagged, however, I would suggest something like ref:to=* or ref=TO *. Vid the Kid 17:01, 24 December 2008 (UTC)
Names and References
Many highways can be tagged with a matching name and reference. For example, name="United States Highway xx", ref="US xx". This is redundant, and I think the name tag can be removed. Is it strictly necessary to include the name tag in this case? --Elyk 02:30, 30 September 2008 (UTC)
- I think this particular phenomenon of redundancy comes not from someone deciding it should be that way, but from the TIGER database. It would seem that the name was carried over unchanged, and the ref was (for US and Interstate highways) derived from the name. It would have been extra work in the import process to then delete the longer name information, had anyone thought of it. I say, feel free to remove the "name" of such highways if they only duplicate/expand the information in the "ref" tag. Check and see if the road has an actual local name that you can put in the "name" tag, though. Vid the Kid 17:07, 24 December 2008 (UTC)
ref for roles
how can we state that a ref is only valid in a certain role?
for example, for a way that is both a highway=track and piste:type=downhill, the ref in that case only refers to usage as a piste; in this example, we have a "blue piste 10", but the underlying track has no ref (or at least, it's not '10').
can this be resolved without switching everything there to Relations/Routes? --Osm6150856065 09:57, 29 August 2009 (UTC)
Spaces in e-roads
There are some confusion as to whether or not there are spaces in e-road refs or not. Some countries have signes with spaces, some don't. The ref tag have a rule: map what is on the ground. But this can not apply to the int_ref tag as this have differant standards. int_ref needs one standard and in the case of e-roads this is the UNECE witch consistently writes "E ##" or "E ###". So no matter how the way is signed the int_ref is written with a space and two or three digits on e-roads. Other road networks might differ. --Gnonthgol 11:09, 8 March 2010 (UTC)
- The discussion was started long ago at Talk:WikiProject_Europe/E-road_network. Alv 11:20, 8 March 2010 (UTC)
ref for branch or franchise reference
In the context of
86215972 (iD, JOSM, Potlatch2, history, XML), I've used ref=Bear Branch Office to indicate the identity of a bank branch, where name=Artisans' Bank. --Ceyockey 04:20, 8 July 2011 (BST)
GNIS id values
I have used ref=GNIS:* in a few cases to indicate reference id in the United States Geograhical Service Geographic Names Information System resource. Is this a useful item to put under either the main table or "Special uses"? --Ceyockey 18:26, 14 August 2011 (BST)
- Maybe ref:GNIS=* would be better. Using ref=GNIS:* prevents using this tag for an other more general purpose. FrViPofm 11:08, 5 June 2012 (BST)
ids from other web services?
can this also be used to map places/features from other web services like facebook or foursquare? like this:
ref:facebook=325001280021 ref:foursquare=4adcda7af964a520e84621e3
--Shmias 14:09, 4 June 2012 (BST)
nation wide refs
In France, we aim using ref:FR:*=* for references applying to our country. Is it possible to use the principle for the other countries with tags such as ref:DE:*=* ref:UK:*=* and patiently to change the existing tags ? --FrViPofm (talk) 00:34, 20 February 2013 (UTC)
- I completely agree with such guideline. It shouldn't only apply to countries but to any extent when refs aren't regarding whole world.
- I'm willing to use ref:EU:*=* to references for Europe only.
- Nevertheless it may be hard to convert existing references with several thousand of uses (as usual). Fanfouer (talk) 12:52, 7 June 2015 (UTC)
reference to an external collection
Speaking about `natural:tree`, I'm participating to the insertion of trees in the Parque Centenario in Cartagena de Indias, Colombia. These trees are being inserted in a botanical database as well, and each of them receives an "Accession number" (consider this a code identifying the plant data).
We were discussing how to add this reference. The accession number has now been added to the OSM objects under the key `ref`, while I had been advocating using `ref` as a namespace prefix, where the tag name would be composed of three parts:
- the `ref` prefix,
- the name of the collection,
- the `accno` suffix.
I generally prefer not to fix things that work, but I foresee conflicts, and I would like to hear other thoughts. --Mariotomo (talk) 14:48, 9 February 2017 (UTC)
As routing software uses the ref-tag on roads to give instructions, shouldn't we be more strict that on roads the ref-tag is what is actually signed along the road. It is no use to have the GPS tell you turn into BD8975b when there is no sign that the road has that ref. And I'm not talking about that a particular intersection doesn't happen to be signed, I'm talking of roads that have similar refs entered in OSM where that ref does not occur anywhere along the entire length of the road!
• ref should be the signed ref as seen on signs along the road
• official_ref or unsigned_ref should be used for the official ref used by the road administration but that is not signed along the road
--Cohan (talk) 09:42, 24 August 2017 (UTC) | https://wiki.openstreetmap.org/wiki/Talk:Key:reference | CC-MAIN-2018-30 | en | refinedweb |
The board game scrabble works by assigning points to wooden tiles arranged in cells on a board. It's described here:. We'll simplify this considerably, and consider the following question. We begin with the letter-scoring scheme from Scrabble: a = 1, b = 3, c = 3, d = 2, ..., z = 10. Given a text file - a novel for example, and a word size, say 7 characters, what is the highest-(or a highest-) scoring word in the the file of that word size?
Your solution should include two files: A driver, which we provide below, and which you must use, and a file called Scrabble.java, which does the heavy lifting for the application. The Scrabble file should extend Echo, in the standard way we've indicated (it can also extend the LineReader class from Chapter 11 of the text).
Tips:
Make sure you read Chapter 10 of the text as a prelude to doing this problem.
Here is a list from a to z of the letter scores from Scrabble:
{1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10}
It's far easier to convert lines of text to lowercase before processing.
Use a StringTokenizer object to chop up a line into words.
Handle characters that show up inside words, such as apostrophe and hyphen this way: treat a word like "can't" as a five character word, and score the apostrophe as 0. Also, use this String as the second parameter to your StringTokenizer constructor: ",.?! {}[];:". The result of using this String will mean that a word like "students'" (note apostrophe at end) should have length 9.
This is the driver they have given us to use:
import java.util.*; import java.io.*; public class ScrabbleDriver{ public static void main(String args[]) { try{ Scanner s = new Scanner(System.in); System.out.println("enter file name, then word size"); String f = s.next(); int size = s.nextInt(); Scrabble scrab = new Scrabble(f,size); scrab.readLines(); scrab.reportWinner(); } catch(Exception e) {System.out.println(e);} } }
I am not sure how to go about coding this so if anyone could help that would be great. | https://www.daniweb.com/programming/software-development/threads/277249/scrabble-class | CC-MAIN-2018-30 | en | refinedweb |
After the new model was implemented, all of my websites now belong to individual Resource Groups called "Default-Web-East" and all of my SQL databases belong to individual Resource Groups called "Default-SQL-East".
This is confusing to say the least.
I would like to rename the groups to have some semantic meaning. I would also like to group the associated SQL database and Web Site in the same Resource Group.
However, I do not see anyway to do either. Is this possible?
1) Rename the Resource Group? 2) Combine an existing SQL DB and Website together into one Resource Group?
No, you cannot rename an Azure Resource Group, all you can do is move an existing resource group to a new resource group.
In the case of Azure Web Apps, you can only move all websites related resources in one invocation. This "all websites related resources" includes all websites, app hosting platforms, and certificates.
From the Portal
Use the "Move" tab for viewing resource groups
Clicking the "Move" tab will show this, which allow you to choose or create a new group: Now Using Azure Powershell
use the Move-AzureRmResource powershell cmdlet.
The command for this:
Get-AzureRmResource -ResourceGroupName <sourceResourceGroupName> | Move-AzureRmResource -DestinationResourceGroupName <destResourceGroupName>
Using the Rest API:
Another way to is you use the MoveResource Rest API or an ArmClient.
This is how you will make an API call:
https://<endpoint>/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/moveResources?api-version={api-version}
Where {resourceGroupName} is the source resource group. If you are using the ArmClient tool, then it will just take care of the endpoint.
Request Body:
{ "targetResourceGroup": "/subscriptions/{subscriptionId}/resourceGroups/{targetResourceGroupNameName}", "resources": [ "/subscriptions/{id}/resourceGroups/{source}/providers/{namespace}/{type}/{name}", "/subscriptions/{id}/resourceGroups/{source}/providers/{namespace}/{type}/{name}" ]}
{
"targetResourceGroup": "/subscriptions/{subscriptionId}/resourceGroups/{targetResourceGroupNameName}",
"resources":
[
"/subscriptions/{id}/resourceGroups/{source}/providers/{namespace}/{type}/{name}",
"/subscriptions/{id}/resourceGroups/{source}/providers/{namespace}/{type}/{name}"
]
}
You cannot rename existing resources. If you're trying to standardize existing resources, it becomes impossible to adopt a universal naming convention. To an extent, this makes sense. In many cases, the object name becomes a DNS name and is referenced in the object's resource ID.
You cannot change the name of your resource group, but you can surely move your resources to a new one, in the following way (Azure Portal): | https://intellipaat.com/community/2574/how-do-i-change-the-name-of-an-azure-resource-group?show=4600 | CC-MAIN-2019-51 | en | refinedweb |
Plugins
Amplify Plugin Platform
Plugins are explicitly managed in the Amplify CLI pluggable platform.
The Amplify CLI Core maintains a
plugins.json file to store the plugin management configuration settings and information of all the installed plugins.
Each Amplify CLI plugin
Plugin Commands
The following is the suite of the commands under the
amplify plugin:
- amplify plugin configure
- amplify plugin scan
- amplify plugin add
- amplify plugin remove
- amplify plugin list
- amplify plugin init
- amplify plugin verify
- amplify plugin help
configure
amplify plugin configure is used to configure the following settings in the
plugins.json file:
plugin-directories: contains the directories that plugin packages are searched for during a plugin scan.
plugin-prefixes: contains the plugin package name prefixes. A package named with such prefix is considered a plugin candidate and checked during a plugin scan. If
plugin-prefixesis empty, all packages inside the scanned directories will be checked.
max-scan-interval-in-seconds: the Amplify CLI Core will scan again if the last scan time has passed for longer than
max-scan-interval-in-seconds. Setting this value to 0 will result in fresh scan at the beginning of each Amplify CLI command execution. The default value is 1 day.
scan
amplify plugin scan will start a fresh scan for plugins in the local environment. A configurable set of directories specified in
plugin-directories, such as the global node_modules, are scanned for plugins.
Execution of this command will completely update the contents of the
plugins field in the
plugins.json.
The
last-scan-time field in the
plugins.json is the time stamp of the last plugin scan.
Note that, other than manually started by this command, a plugin scan can also be triggered by a regular amplify command execution, for example if the Amplify CLI Core noticed something is incorrect, or the last scan time has passed for longer than
max-scan-interval-in-seconds(set to be one day by default).
add
amplify plugin add will prompt you to select a previously removed plugin (see below), or enter the full path of a local package to be added as a plugin into the Amplify CLI. The Amplify CLI Core verifies the existence and validity of the plugin package during execution of the this command. You can use this command to add a plugin that will not be found by the plugin scan process, e.g. if it is not in one of the
plugin-directories, or its package name does not have the proper prefix as specified in the
plugin-prefixes.
remove
amplify plugin remove will prompt you with the list of all the currently active plugins, and allow you to select the ones that you do not want to be included in the Amplify CLI. The Amplify CLI Core will remove the manifest of those plugins from the
plugins field, so they will NOT be counted as active plugins anymore and will NOT be loaded during command executions.
If a removed plugin is in one of the directories specified in the
plugin-directories, and its package name has the prefix as specified in the
plugin-prefixes, it is then inserted in the
excluded field of the
plugins.json file. This will not be inserted back to the
plugins field in the next plugin scan.
The actual plugin packages themselves are not removed from your computer, and they can be added back as active plugins by
amplify plugin add.
list
amplify plugin list lists all the active plugins, along with other information of the local Amplify CLI plugin platform.
init
The Amplify CLI provides the command
amplify plugin init (with alias
amplify plugin new) for the development of plugins.
This command first collects the requirements from you and then creates the skeleton of the plugin package for you to start the development. The newly created plugin package is added to your local Amplify CLI platform, so you can conveniently test its functionalities while it is being developed. It can be easily removed from the platform with the
amplify plugin remove command and added back with the
amplify plugin add command.
verify
The Amplify CLI provides the utility command
amplify plugin verify to verify that:
- The package implements the required interface methods for plugins.
- The
commandsfield contains all the required commands for the type of the plugin.
amplify plugin verifycommand treats the folder where it is executed as the root directory of the plugin package. The command can be executed manually. Its functionality is also invoked by the
amplify plugin scanand
amplify plugin addcommands.
Prints out help information for the commands under
amplify plugin.
List of existing 3rd party CLI Plugins
Plugins enable you to add additional commands and functionality to existing Amplify CLI. This section goes through the steps to create, publish, consume a plugin package, explains the folder structure, and key files in the plugin package. Click here for detailed explanations of the Amplify CLI plugin architecture, plugin types and plugin platform events.
Authoring a CLI Plugin
The Amplify CLI provides the command
amplify plugin init (with alias
amplify plugin new) for the development of plugins. This command first collects requirements, and then creates the skeleton of the plugin package for you to start the development. The newly created plugin is added to your local Amplify CLI plugin platform, so you can conveniently test its functionalities while it is being developed. It can be easily removed form the local plugin platform with the
amplify plugin remove command, and added back with the
amplify plugin add command.
Step 1: Install Amplify CLI
$ npm install -g @aws-amplify/cli
Step 2: Run
amplify plugin init
$ amplify plugin init
You will be prompted to enter the plugin name, then select the plugin type, and event subscriptions. The CLI will then create a plugin package for you and add it to the local Amplify CLI plugin platform.
Step 3: Test your plugin
The newly created plugin package is already added to the local Amplify CLI, so you can start testing it immediately.
Let’s say you have chosen to use the default plugin name:
my-amplify-plugin
$ amplify my-amplify-plugin help help command to be implemented.
You will see that the default help message is printed out.
At this point, there are only two sub commands in the plugin package,
help and
version, with dummy implementations. If you try to execute any other command, it will trigger the Amplify CLI plugin platform to perform a fresh scan, and then after it failed to find the command, it will print out the default help message.
From here, you can start to develop the plugin package. See below for the detailed explanation of the package structure.
Step 4: Publish to NPM
After the completion of one development cycle and you are ready to release your plugin to the public, you can publish it to the NPM:
Step 4: Install and Use
Once your plugin is published to the NPM, other developers can install and use it
$ npm install -g my-amplify-plugin $ amplify plugin add my-amplify-plugin $ amplify my-amplify-plugin help
Plugin Package Structure
Here’s the plugin package directory structure
|_my-amplify-plugin/ |_commands/ | |_ help.js | |_ version.js | |_event-handlers | |_handle-PostInit.js | |_handle-PostPush.js | |_handle-PreInit.js | |_handle-PrePush.js | |_amplify-plugin.json |_index.js |_package.json
### amplify-plugin.json
The
amplify-plugin.json file is the plugin’s manifest file, it specifies the plugin’s name, type, commands and event handlers. The Amplify CLI uses it to verify and add the plugin package into its plugin platform.
Here’s the contents of the file when it’s first generated by the
amplify plugin init command for a util plugin.
{ "name": "my-amplify-plugin", "type": "util", "commands": [ "version", "help" ], "eventHandlers": [ "PreInit", "PostInit", "PrePush", "PostPush" ] }
index.js
The
"main" file specified in the
package.json is the Amplify CLI’s entry to invoke the plugin’s functionalities specified in the manifest file
amplify-plugin.json.
Here’s the contents of the file when it’s first generated by the
amplify plugin init command for a util plugin.
const path = require('path'); async function executeAmplifyCommand(context) { const commandsDirPath = path.normalize(path.join(__dirname, 'commands')); const commandPath = path.join(commandsDirPath, context.input.command); const commandModule = require(commandPath); await commandModule.run(context); } async function handleAmplifyEvent(context, args) { const eventHandlersDirPath = path.normalize(path.join(__dirname, 'event-handlers')); const eventHandlerPath = path.join(eventHandlersDirPath, `handle-${args.event}`); const eventHandlerModule = require(eventHandlerPath); await eventHandlerModule.run(context, args); } module.exports = { executeAmplifyCommand, handleAmplifyEvent, };
commands
The
commands folder contains files that implement the
commands specified in the manifest file
amplify-plugin.json.
event-handlers
The
event-handlers folder contains files that implement the
eventHandlers specified in the manifest file
amplify-plugin.json.
Custom GraphQL Transformers
This section outlines the process of writing custom GraphQL transformers. The
graphql-transform package serves as a lightweight framework that takes as input a GraphQL SDL document
and a list of GraphQL Transformers and returns a cloudformation document that fully implements the data model defined by the input schema. A GraphQL Transformer is a class the defines a directive and a set of functions that manipulate a context and are called whenever that directive is found in an input schema.
For example, the AWS Amplify CLI calls the GraphQL Transform like this:
import GraphQLTransform from 'graphql-transformer-core' import DynamoDBModelTransformer from 'graphql-dynamodb-transformer' import ModelConnectionTransformer from 'graphql-connection-transformer' import ModelAuthTransformer from 'graphql-auth-transformer' import AppSyncTransformer from 'graphql-appsync-transformer' import VersionedModelTransformer from 'graphql-versioned-transformer' // Note: This is not exact as we are omitting the @searchable transformer. const transformer = new GraphQLTransform({ transformers: [ new AppSyncTransformer(), new DynamoDBModelTransformer(), new ModelAuthTransformer(), new ModelConnectionTransformer(), new VersionedModelTransformer() ] }) const schema = ` type Post @model { id: ID! title: String! comments: [Comment] @connection(name: "PostComments") } type Comment @model { id: ID! content: String! post: Post @connection(name: "PostComments") } ` const cfdoc = transformer.transform(schema); const out = await createStack(cfdoc, name, region) console.log('Application creation successfully started. It may take a few minutes to finish.')
As shown above the
GraphQLTransform class takes a list of transformers and later is able to transform
GraphQL SDL documents into CloudFormation documents.
The Transform Lifecycle
At a high level the
GraphQLTransform takes the input SDL, parses it, and validates the schema
is complete and satisfies the directive definitions. It then iterates through the list of transformers
passed to the transform when it was created and calls
.before() if it exists. It then walks the parsed AST
and calls the relevant transformer methods (e.g.
object(),
field(),
interface() etc) as directive matches are found.
In reverse order it then calls each transformer’s
.after() method if it exists, and finally returns the context’s finished template.
Here is pseudo code for how
const cfdoc = transformer.transform(schema); works.
function transform(schema: string): Template { // ... for (const transformer of this.transformers) { // Run the before function one time per transformer. if (isFunction(transformer.before)) { transformer.before(context) } // Transform each definition in the input document. for (const def of context.inputDocument.definitions as TypeDefinitionNode[]) { switch (def.kind) { case 'ObjectTypeDefinition': this.transformObject(transformer, def, context) // Walk the fields and call field transformers. break case 'InterfaceTypeDefinition': this.transformInterface(transformer, def, context) // Walk the fields and call field transformers. break; case 'ScalarTypeDefinition': this.transformScalar(transformer, def, context) break; case 'UnionTypeDefinition': this.transformUnion(transformer, def, context) break; case 'EnumTypeDefinition': this.transformEnum(transformer, def, context) break; case 'InputObjectTypeDefinition': this.transformInputObject(transformer, def, context) break; // Note: Extension and operation definition nodes are not supported. default: continue } } } // After is called in the reverse order as if they were popping off a stack. let reverseThroughTransformers = this.transformers.length - 1; while (reverseThroughTransformers >= 0) { const transformer = this.transformers[reverseThroughTransformers] if (isFunction(transformer.after)) { transformer.after(context) } reverseThroughTransformers -= 1 } // Return the template. // In the future there will likely be a formatter concept here. return context.template }
The Transformer Context
The transformer context serves like an accumulator that is manipulated by transformers. See the code to see what methods are available to you.
For now, the transform only support cloudformation and uses a library called
cloudformto create cloudformation resources in code. In the future we would like to support alternative deployment mechanisms like terraform.
Example
As an example let’s walk through how we implemented the @versioned transformer. The first thing to do is to define a directive for our transformer.
const VERSIONED_DIRECTIVE = ` directive @versioned(versionField: String = "version", versionInput: String = "expectedVersion") on OBJECT `
Our
@versioned directive can be applied to
OBJECT type definitions and automatically adds object versioning and conflict detection to an APIs mutations. For example, we might write
# Any mutations that deal with the Post type will ask for an `expectedVersion` # input that will be checked using DynamoDB condition expressions. type Post @model @versioned { id: ID! title: String! version: Int! }
Note: @versioned depends on @model so we must pass
new DynamoDBModelTransformer()before
new VersionedModelTransformer(). Also note that
new AppSyncTransformer()must go first for now. In the future we can add a dependency mechanism and topologically sort it ourselves.
The next step after defining the directive is to implement the transformer’s business logic. The
graphql-transformer-core package makes this a little easier
by exporting a common class through which we may define transformers. User’s extend the
Transformer class and implement the required functions.
export class Transformer { before?: (acc: TransformerContext) => void after?: (acc: TransformerContext) => void object?: (definition: ObjectTypeDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void interface?: (definition: InterfaceTypeDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void field?: ( parent: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode, definition: FieldDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void argument?: (definition: InputValueDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void union?: (definition: UnionTypeDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void enum?: (definition: EnumTypeDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void enumValue?: (definition: EnumValueDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void scalar?: (definition: ScalarTypeDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void input?: (definition: InputObjectTypeDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void inputValue?: (definition: InputValueDefinitionNode, directive: DirectiveNode, acc: TransformerContext) => void }
Since our
VERSIONED_DIRECTIVE only specifies
OBJECT in its on condition, we only *NEED to implement the
object function. You may also
implement the
before and
after functions which will be called once at the beginning and end respectively of the transformation process.
/** * Users extend the Transformer class and implement the relevant functions. */ export class VersionedModelTransformer extends Transformer { constructor() { super( 'VersionedModelTransformer', VERSIONED_DIRECTIVE ) } /** * When a type is annotated with @versioned enable conflict resolution for the type. * * Usage: * * type Post @model @versioned(versionField: "version", versionInput: "expectedVersion") { * id: ID! * title: String * version: Int! * } * * Enabling conflict resolution automatically manages a "version" attribute in * the @model type's DynamoDB table and injects a conditional expression into * the types mutations that actually perform the conflict resolutions by * checking the "version" attribute in the table with the "expectedVersion" passed * by the user. */ public object = (def: ObjectTypeDefinitionNode, directive: DirectiveNode, ctx: TransformerContext): void => { // @versioned may only be used on types that are also @model const modelDirective = def.directives.find((dir) => dir.name.value === 'model') if (!modelDirective) { throw new InvalidDirectiveError('Types annotated with @versioned must also be annotated with @model.') } const isArg = (s: string) => (arg: ArgumentNode) => arg.name.value === s const getArg = (arg: string, dflt?: any) => { const argument = directive.arguments.find(isArg(arg)) return argument ? valueFromASTUntyped(argument.value) : dflt } const versionField = getArg('versionField', "version") const versionInput = getArg('versionInput', "expectedVersion") const typeName = def.name.value // Make the necessary changes to the context this.augmentCreateMutation(ctx, typeName, versionField, versionInput) this.augmentUpdateMutation(ctx, typeName, versionField, versionInput) this.augmentDeleteMutation(ctx, typeName, versionField, versionInput) this.stripCreateInputVersionedField(ctx, typeName, versionField) this.addVersionedInputToDeleteInput(ctx, typeName, versionInput) this.addVersionedInputToUpdateInput(ctx, typeName, versionInput) this.enforceVersionedFieldOnType(ctx, typeName, versionField) } // ... Implement the functions that do the real work by calling the context methods. } | https://aws-amplify.github.io/docs/cli-toolchain/plugins?sdk=js | CC-MAIN-2019-51 | en | refinedweb |
Hide Forgot
Possible use after free vulnerability via namespace nodes in XPointer ranges was found.
Upstream patch:
Created libxml2 tracking bugs for this issue:
Affects: fedora-all [bug 1384427]
Created mingw-libxml2 tracking bugs for this issue:
Affects: fedora-all [bug 1384429]
Affects: epel-7 [bug 1384430]
(In reply to Adam Mariš from comment #0)
> Possible use after free vulnerability via namespace nodes in XPointer ranges
> was found.
>
> Upstream patch:
>
>
> ?id=c1d1f7121194036608bf555f08d3062a36fd344b
Hello Adam,
We have been monitoring the URL for the latest release of the official patch of libxml2 containing the patches for the bugs associated with the CVE-2016-4658, CVE-2016-9318 and CVE-2016-9597, but have observed that no binary files have been released yet.
From the URL we found that a RPM file has been released, but as our requirement is a binary version we can't go for the RPM version.
Could you kindly confirm the ETA for the release of the official libxml2 2.9.4-3.1 binary package containing all the above mentioned patches?
Kind regards,
Maumita Mandal
Is this still being considered for a fix? Please let me know. | https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=1384424 | CC-MAIN-2019-51 | en | refinedweb |
This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of C++14 status.
Section: 20.11.4 [util.smartptr.weak], 20.11.4.5 [util.smartptr.weak.obs] Status: C++14 Submitter: Ai Azuma Opened: 2011-09-06 Last modified: 2016-02-10
Priority: Not Prioritized
View all other issues in [util.smartptr.weak].
View all issues with C++14 status.
Discussion:
Is there any reason why weak_ptr::owner_before member function templates are not const-qualified?
Daniel Krügler:
I don't think so. To the contrary, without these to be const member function templates, the semantics of the specializations owner_less<weak_ptr<T>> and owner_less<shared_ptr<T>> described in 20.11.5 [util.smartptr.ownerless] is unclear.It is amusing to note that this miss has remain undetected from the accepted paper n2637 on. For the suggested wording changes see below.
[2012, Kona]
Move to Ready.
[2012, Portland: applied to WP]
Proposed resolution:
This wording is relative to the FDIS.
Change the class template weak_ptr synopsis in 20.11.4 [util.smartptr.weak] as indicated:
namespace std { template<class T> class weak_ptr { public: typedef T element_type; […] template<class U> bool owner_before(shared_ptr<U> const& b) ; template<class U> bool owner_before(weak_ptr<U> const& b) ; }; […] }
Change the prototypes in 20.11.4.5 [util.smartptr.weak.obs] before p6 as indicated:
template<class U> bool owner_before(shared_ptr<U> const& b) ; template<class U> bool owner_before(weak_ptr<U> const& b) ; | https://cplusplus.github.io/LWG/issue2083 | CC-MAIN-2019-51 | en | refinedweb |
- Type:
Bug
- Status: Reported
- Priority:
P4: Low
- Resolution: Unresolved
- Affects Version/s: 5.12.5, 5.12, 5.13.1
- Fix Version/s: None
- Component/s: Core: Filesystem watching, Core: I/O
- Labels:None
- Environment:macOS 10.15 and 10.14
- Platform/s:
QStorageInfo.mountedVolumes() does not detect volumes mounted via /etc/fstab or /etc/auto_master. As far as I can it only detects network mounts created via Finder.
Here is a link to the relative section of code.
The problem is in the option kCFURLEnumeratorSkipInvisibles. Using virtually any other option in the CFURLEnumeratorOptions results in a complete listing of mounts.
I was able to recreate the Qt behavior in a Swift playground file with the following contents
import Cocoa let options = CFURLEnumeratorOptions.skipInvisibles let volumes = CFURLEnumeratorCreateForMountedVolumes(nil, options, nil)! var paths = [CFString]() var result = CFURLEnumeratorResult.success var urlProperty : Unmanaged<CFURL>? var errorProperty : Unmanaged<CFError>? repeat { result = CFURLEnumeratorGetNextURL(volumes, &urlProperty, &errorProperty) if result == CFURLEnumeratorResult.success { if urlProperty != nil { let unpackagedUrl = urlProperty!.takeRetainedValue() as CFURL let urlString = CFURLCopyFileSystemPath(unpackagedUrl, CFURLPathStyle.cfurlposixPathStyle) paths.append(urlString!) } } } while result != CFURLEnumeratorResult.end print(paths)
Here is a link to all the possible options that CFUrlEnumeratorCreateForMountedVolumes can be called with:
I suggest a different option is considered such as skipPackageContents.
Another quick sanity check is to mount a network share via /etc/fstab or /etc/auto_master and then run mount from the terminal, and compare that to the output of QStorageInfo.mountedVolumes(). | https://bugreports.qt.io/browse/QTBUG-79409 | CC-MAIN-2019-51 | en | refinedweb |
IOS Multitasking on iPad
I'm considering picking up the Pythonista app so that I can learn python while I'm on the move. Does anyone know if the app supports iOS multitasking? I'd like to have both Pythonista and my Python book at the same time.
The app keeps running in the background for a while after you close it, so there should be no issues switching back and forth between the book and Pythonista. Even if the app stops running, it will save all open files and remembers which tabs you had, so even if that happens you won't lose anything.
I can't say anything about the new multitasking features in iOS 9 (split screen and such) because Apple decided that my device is too old for that. Someone else probably knows.
- Webmaster4o
Pythonista does not support multitasking, I don't think. I don't have a split-view enabled device, but I know it doesn't support slide-over. However, if your book is web-based, you can open that in a side pane as a built-in feature of pythonista. It will appear as the same width as a slide-over on the right, but you'll be able to focus on and work in both simultaneously, i.e. you don't have to close the book to write code.
If you want to do this once you buy it (if you buy it), simply open the console,
import webbrowser;webbrowser.open("")and then put the console in "docked" mode. You should also be able to do this with PDF files, if that's what your book is.
Pythonista is a great app, definately worth the purchase. I'd definately recommend it.
Thanks for your suggestion. Opening the book (PDF) in the console sounds like a decent enough workaround. If it does support split-view, I'll be sure to come back and reply here.
@dranobob I can help you with that, it may not be completely straightforward. If it's a file that isn't online publicly, you'll have to import it into the Pythonista file system before opening it. That takes a little effort, but nothing too bad.
As to original question:
You can have the narrow band on the side but not the iPad 50/50 multitasking split screen. I recall (but cannot retrieve details) that omz chose not to implement multitasking in 2.0 because that would limit Pythonista's game-playing capabilities
@dranobob If your PDF is in iBooks, iBooks has very limited sharing options for PDFs. The simplest way I've found to import from iBooks is to email it to myself from iBooks, and then Mail has the option to open in Pythonista. A real inconvenience, but I have no power over iBooks 🙃
Once you have it imported, you can use something like
import webbrowser,os webbrowser.open("file://"+os.path.expanduser("~/Documents/book.pdf"))
If the PDF is online, it's much simpler. Without any importing, this will work:
import webbrowser webbrowser.open("")
Once you put the console in "docked" mode, it will look something like this:
I am fully able to type in the code field without closing my book. That book is "Programming Computer Vision with Python," the free PDF of which I've imported to Pythonista locally as a file.
You can zoom, in case that looks horrendously small to you.
@Webmaster4o, I wasn't completely sure, so I checked. It's on Twitter and mentions split screen, not multitasking, making is less easy to find, but I found it via @viticci review
@Webmaster4o, ah, the ambiguity of "it" ;-)
I can have Pythonista as the main on the ¾ left-hand side of my iPad Air 2, and any (multitasking-capable) other app on the ¼ right-hand. Not the other way around, as only multitasking-capable apps can do so, and Pythonista isn't (as per previous post).
However, your solution inside Pythonista is better as that remains if you return to the code, whereas the other way it disappears.
@Olaf ah, clear now. I was looking between "Pixelmator" and "Reminders" and not seeing anything :) If this is true, that's a great alternative to docked console. That will be way better.
On my Pythonista version 2.0.1 (201000) on iOS 9.2.1 on a 64-bit iPad5,4 with a screen size of (1024 x 768) * 2
@ccc this is SlideOver. We were talking about full multitasking with a 3:1 ratio. SlideOver is not ideal, because one cannot type code without closing the book. | https://forum.omz-software.com/topic/2665/ios-multitasking-on-ipad/ | CC-MAIN-2019-51 | en | refinedweb |
I have read this tutorial for working with
Less in Asp.Net MVC5.
To integrate LESS in ASP.NET MVC, I download and install the dotless NuGet package.
And then added this bundle:
var lessBundle = new Bundle("~/Less").Include("~/Content/Less/*.less"); lessBundle.Transforms.Add(new LessTransform()); lessBundle.Transforms.Add(new CssMinify()); bundles.Add(lessBundle);
Here is the
LessTransform:
public class LessTransform : IBundleTransform { public void Process(BundleContext context, BundleResponse response) { response.Content = dotless.Core.Less.Parse(response.Content); response.ContentType = "text/css"; } }
So far so good. Everything works as it is expected.
Here is the part from my
.less file:
@CustomMessageBackgroundColor: #65B6A7; div.custom-dialog { ... background: @CustomMessageBackgroundColor; }
Now, I want to change the value of this variable from
.js file dynamically:
less.modifyVars({ '@CustomMessageBackgroundColor': 'blue' }); less.refreshStyles();
But, this is not working. I have read all SO questions and as I understand this must work.
Thanks. | https://www.howtobuildsoftware.com/index.php/how-do/oj2/c-aspnet-mvc-aspnet-mvc-5-less-dotless-lessmodifyvars-not-working-in-aspnet-mvc | CC-MAIN-2019-51 | en | refinedweb |
3.6. Implementation of Softmax Regression from Scratch¶
Just as we implemented linear regression from scratch, we believe that multiclass logistic (softmax) regression is similarly fundamental and you ought to know the gory details of how to implement it yourself. As with linear regression, after doing things by hand we will breeze through an implementation in Gluon for comparison. To begin, let’s import the familiar packages.
import d2l from mxnet import autograd, np, npx, gluon from IPython import display npx.set_np()
We will work with the Fashion-MNIST dataset, just introduced in Section 3.5, setting up an iterator with batch size \(256\).
batch_size = 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
3.6.1. Initializing Model Parameters¶
As in our linear regression example, each example here will be represented by a fixed-length vector. Each example in the raw data is a \(28 \times 28\) image. In this section, we will flatten each image, treating them as \(784\) 1D vectors. In the future, we will talk about more sophisticated strategies for exploiting the spatial structure in images, but for now we treat each pixel location as just another feature.
Recall that in softmax regression, we have as many outputs as there are categories. Because our dataset has \(10\) categories, our network will have an output dimension of \(10\). Consequently, our weights will constitute a \(784 \times 10\) matrix and the biases will constitute a \(1 \times 10\) vector. As with linear regression, we will initialize our weights \(W\) with Gaussian noise and our biases to take the initial value \(0\).
num_inputs = 784 num_outputs = 10 W = np.random.normal(0, 0.01, (num_inputs, num_outputs)) b = np.zeros(num_outputs)
Recall that we need to attach gradients to the model parameters. More literally, we are allocating memory for future gradients to be stored and notifiying MXNet that we will want to calculate gradients with respect to these parameters in the future.
W.attach_grad() b.attach_grad()
3.6.2. The Softmax¶
Before implementing the softmax regression model, let’s briefly review
how operators such as
sum work along specific dimensions in an
ndarray. Given a matrix
X we can sum over all elements (default)
or only over elements in the same axis, i.e., the column (
axis=0)
or the same row (
axis=1). Note that if
X is an array with shape
(2, 3) and we sum over the columns (
X.sum(axis=0), the result
will be a (1D) vector with shape
(3,). If we want to keep the number
of axes in the original array (resulting in a 2D array with shape
(1, 3)), rather than collapsing out the dimension that we summed
over we can specify
keepdims=True when invoking
sum.
X = np.array([[1, 2, 3], [4, 5, 6]]) print(X.sum(axis=0, keepdims=True), '\n', X.sum(axis=1, keepdims=True))
[[5. 7. 9.]] [[ 6.] [15.]]
We are now ready to implement the softmax function. Recall that softmax
consists of two steps: First, we exponentiate each term (using
exp).
Then, we sum over each row (we have one row per example in the batch) to
get the normalization constants for each example. Finally, we divide
each row by its normalization constant, ensuring that the result sums to
\(1\). Before looking at the code, let’s recall what this looks
expressed as an equation:
The denominator, or normalization constant, is also sometimes called the partition function (and its logarithm is called the log-partition function). The origins of that name are in statistical physics where a related equation models the distribution over an ensemble of particles).
def softmax(X): X_exp = np.exp(X). Note that while this looks correct mathematically, we were a bit sloppy in our implementation because failed to take precautions against numerical overflow or underflow due to large (or very small) elements of the matrix, as we did in Section 17.9.
X = np.random.normal(size=(2, 5)) X_prob = softmax(X) X_prob, X_prob.sum(axis=1)
(array([[0.22376052, 0.06659239, 0.06583703, 0.29964197, 0.3441681 ], [0.63209665, 0.03179282, 0.194987 , 0.09209415, 0.04902935]]), array([1. , 0.99999994]))
3.6.3. The Model¶
Now that we have defined the softmax operation, we can implement the
softmax regression model. The below code defines the forward pass
through the network. Note that we flatten each original image in the
batch into a vector with length
num_inputs with the
reshape
function before passing the data through our model.
def net(X): return softmax(np.dot(X.reshape(-1, num_inputs), W) + b)
3.6.4. The Loss Function¶
Next, we need to implement the cross-entropy loss function, introduced in Section 3.4. This may be the most common loss function in all of deep learning because, at the moment, classification problems far outnumber regression problems.
Recall that cross-entropy takes the negative log likelihood of the
predicted probability assigned to the true label
\(-\log P(y \mid x)\). Rather than iterating over the predictions
with a Python
for loop (which tends to be inefficient), we can use
the
pick function which allows us to easily select the appropriate
terms from the matrix of softmax entries. Below, we illustrate the
pick function on a toy example, with \(3\) categories and
\(2\) examples.
y_hat = np.array([[0.1, 0.3, 0.6], [0.3, 0.2, 0.5]]) y_hat[[0, 1], [0, 2]]
array([0.1, 0.5])
Now we can implement the cross-entropy loss function efficiently with just one line of code.
def cross_entropy(y_hat, y): return - np.log(y_hat[range(len(y_hat)), y])
3.6.5. Classification Accuracy¶
Given the predicted probability distribution
y_hat, we typically
choose the class with highest predicted probability whenever we must
output a hard prediction. Indeed, many applications require that we
make a choice. Gmail must categorize an email into Primary, Social,
Updates, or Forums. It might estimate probabilities internally, but at
the end of the day it has to choose one among the categories.
When predictions are consistent with the actual category
y, they are
correct. The classification accuracy is the fraction of all predictions
that are correct. Although it can be difficult optimize accuracy
directly (it is not differentiable), it is often the performance metric
that we care most about, and we will nearly always report it when
training classifiers.
To compute accuracy we do the following: First, we execute
y_hat.argmax(axis=1) to gather the predicted classes (given by the
indices for the largest entires each row). The result has the same shape
as the variable
y. Now we just need to check how frequently the two.
# Saved in the d2l package for later use def accuracy(y_hat, y): if y_hat.shape[1] > 1: return float((y_hat.argmax(axis=1) == y.astype('float32')).sum()) else: return float((y_hat.astype('int32') == y.astype('int32')).sum())\).
y = np.array([0, 2]) accuracy(y_hat, y) / len(y)
0.5
Similarly, we can evaluate the accuracy for model
net on the dataset
(accessed via
data_iter).
# Saved in the d2l package for later use def evaluate_accuracy(net, data_iter): metric = Accumulator(2) # num_corrected_examples, num_examples for X, y in data_iter: metric.add(accuracy(net(X), y), y.size) return metric[0] / metric[1]
Here
Accumulator is a utility class to accumulated sum over multiple
numbers.
# Saved in the d2l package for later use class Accumulator(object): """Sum a list of numbers over time""" def __init__(self, n): self.data = [0.0] * n def add(self, *args): self.data = [a+b for a, b in zip(self.data, args)] def reset(self): self.data = [0] * len(self.data) def __getitem__(self, i): return self.data[i]
Because we initialized the
net model with random weights, the
accuracy of this model should be close to random guessing, i.e.,
\(0.1\) for \(10\) classes.
evaluate_accuracy(net, test_iter)
0.0811
3.6.6. Model Training¶
The training loop for softmax regression should look strikingly familiar
if you read through our implementation of linear regression in
Section 3.2. Here we refactor the implementation to
make it reusable. First, we define a function to train for one data
epoch. Note that
updater is general function to update the model
parameters, which accepts the batch size as an argument. It can be
either a wrapper of
d2l.sgd or a Gluon trainer.
# Saved in the d2l package for later use def train_epoch_ch3(net, train_iter, loss, updater): metric = Accumulator(3) # train_loss_sum, train_acc_sum, num_examples if isinstance(updater, gluon.Trainer): updater = updater.step for X, y in train_iter: # Compute gradients and update parameters with autograd.record(): y_hat = net(X) l = loss(y_hat, y) l.backward() updater(X.shape[0]) metric.add(float(l.sum()), accuracy(y_hat, y), y.size) # Return training loss and training accuracy return metric[0]/metric[2], metric[1]/metric[2]
Before showing the implementation of the training function, we define a utility class that draw data in animation. Again, it aims to simplify the codes in later chapters.
# Saved in the d2l package for later use class Animator(object): def __init__(self, xlabel=None, ylabel=None, legend=[], xlim=None, ylim=None, xscale='linear', yscale='linear', fmts=None, nrows=1, ncols=1, figsize=(3.5, 2.5)): """Incrementally plot multiple lines.""" d2l.use_svg_display() self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize) if nrows * ncols == 1: self.axes = [self.axes, ] # Use a lambda to capture arguments self.config_axes = lambda: d2l.set_axes( self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend) self.X, self.Y, self.fmts = None, None, fmts def add(self, x, y): """Add multiple data points into the figure.""" if not hasattr(y, "__len__"): y = [y] n = len(y) if not hasattr(x, "__len__"): x = [x] * n if not self.X: self.X = [[] for _ in range(n)] if not self.Y: self.Y = [[] for _ in range(n)] if not self.fmts: self.fmts = ['-'] * n for i, (a, b) in enumerate(zip(x, y)): if a is not None and b is not None: self.X[i].append(a) self.Y[i].append(b) self.axes[0].cla() for x, y, fmt in zip(self.X, self.Y, self.fmts): self.axes[0].plot(x, y, fmt) self.config_axes() display.display(self.fig) display.clear_output(wait=True)
The training function then runs multiple epochs and visualize the training progress.
# Saved in the d2l package for later use def train_ch3(net, train_iter, test_iter, loss, num_epochs, updater): animator = Animator(xlabel='epoch', xlim=[1, num_epochs], ylim=[0.3, 0.9], legend=['train loss', 'train acc', 'test acc']) for epoch in range(num_epochs): train_metrics = train_epoch_ch3(net, train_iter, loss, updater) test_acc = evaluate_accuracy(net, test_iter) animator.add(epoch+1, train_metrics+(test_acc,))
Again, we use the minibatch stochastic gradient descent to optimize the
loss function of the model. Note that the number of epochs
(
num_epochs), and learning rate (
lr) are both adjustable
hyper-parameters. By changing their values, we may be able to increase
the classification accuracy of the model. In practice we will want to
split our data three ways into training, validation, and test data,
using the validation data to choose the best values of our
hyperparameters.
num_epochs, lr = 10, 0.1 def updater(batch_size): return d2l.sgd([W, b], lr, batch_size) train_ch3(net, train_iter, test_iter, cross_entropy, num_epochs, updater)
3.6.7. Prediction¶
Now that training is complete, our model is ready to classify some images. Given a series of images, we will compare their actual labels (first line of text output) and the model predictions (second line of text output).
# Saved in the d2l package for later use def predict_ch3(net, test_iter, n=6): for X, y in test_iter: break trues = d2l.get_fashion_mnist_labels(y) preds = d2l.get_fashion_mnist_labels(net(X).argmax(axis=1)) titles = [true+'\n' + pred for true, pred in zip(trues, preds)] d2l.show_images(X[0:n].reshape(n, 28, 28), 1, n, titles=titles[0:n]) predict_ch3(net, test_iter)
3.6.8. Summary¶
With softmax regression, we can train models for multi-category classification. The training loop is very similar to that in linear regression: retrieve and read data, define models and loss functions, then train models using optimization algorithms. As you will soon find out, most common deep learning models have similar training procedures.
3.6.9. Exercises? | https://d2l.ai/chapter_linear-networks/softmax-regression-scratch.html | CC-MAIN-2019-51 | en | refinedweb |
sample data in a clip.
The samples should be floats ranging from -1.0f to 1.0f (exceeding these limits will lead to artifacts and undefined behaviour).
The sample count is determined by the length of the float array.
Use offsetSamples to write into a random position in the clip. If the length from the offset is longer than the clip length, the write will wrap around
and write the remaining samples from the start of the clip.
Note that for compressed audio, the sample data can only be set when the Load Type is set to Decompress on Load in the audio importer.
using UnityEngine;
public class Example : MonoBehaviour { // Read all the samples from the clip and half the gain void Start() { AudioSource audioSource = GetComponent<AudioSource>(); float[] samples = new float[audioSource.clip.samples * audioSource.clip.channels]; audioSource.clip.GetData(samples, 0);
for (int i = 0; i < samples.Length; ++i) { samples[i] = samples[i] * 0.5f; }
audioSource.clip.SetData(samples, 0); } }
Did you find this page useful? Please give it a rating: | https://docs.unity3d.com/ScriptReference/AudioClip.SetData.html | CC-MAIN-2019-51 | en | refinedweb |
Here I would like to share how to consume the Web Service in .Net application.
I have come across the situation where I have the Web Service wrote during the
VB 6.0 using the Soap Toolkit from the COM component, I want to consume the Web
Service from the .Net Application (C# or ASP.net). There are few ways to consume
the Web Service either wrote from .Net version or any other application.
Here I would like to share how to consume the Web Service in .Net application.
As most of us know what is Web Service so I will not go deep into that.
I have generated the WSDL (Web Service Descriptor Language) from the COM (+)
component using the SOAP Toolkit. SOAP will generate the .WSDL, .WSMX and .asp
file which we can use to access the Web Service. Step 1:
Now you have the Web reference added to your application. You can now access the
Web Service and exposed API's of that Web Service.
Open the form and add the button. On Button click event will access the Web
Service and Its Function.
To access the Web Service we have to create the Instance from the Web Reference
name. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml;
namespace ConsumeWebService
{
public partial class Form1 :
Form {
public Form1()
{
InitializeComponent();
}
private void
btnShow_Click(object sender,
EventArgs e)
{
CallWS.EyrAPIEnterprise call =
new CallWS.EyrAPIEnterprise();
call.Url = "";
//If you are using the Default Credential
then set this property to true. //call.UseDefaultCredentials =
true; //If you are using Windows (NTLM)
authetication then set the below property. call.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
string systemID =
string.Empty;
XmlDocument doc =
new XmlDocument();
string xmlString = ((System.Xml.XmlNode[])call.GetSystems())[0].OuterXml;
doc.LoadXml(xmlString);
textBox1.Text = xmlString;
//You can get the value from the XML
output using the XPath
}
}
} How to consume the ASP.net Web Service
Now in .net we can have the Web Service written in ASP.net (.asmx) and use that
in ASP.net or C# (windows) application.
First we will create the Web Service using ASP.net. You can create using the VS
IDE or Simple in any text editor. A Web Service Example
In the following example we will use ASP.NET to create a simple Web Service that
converts the temperature from Fahrenheit to Celsius, and vice versa: public class WebService : System.Web.Services.WebService
{
public WebService () {
//Uncomment the following line if using
designed components //InitializeComponent(); }
[WebMethod]
public string
HelloWorld() {
return
"Hello World";
}
[WebMethod]
public int
FahrenheitToCelsius(int far)
{
return ((((far) - 32) / 9) * 5);
}
[WebMethod]
public int
CelsiusToFahrenheit(int cel)
{
return ((((cel) * 9) / 5) + 32);
}
}
This document is saved as an .asmx file. This is the ASP.NET file extension for
XML Web Services.
So when you open the Web Service from the browser using the following
You will see the below list of the methods which we made as the Web Method. This
the web methods exposed by the Web Service. Now for to test, you can click on
any method for e.g. CelciusToFarheneit, it will show you the next part where you
can input the number and click on the Invoke button.
The Web service will then take that Input and convert the value from celcius to
Far as show below in the next picture. Output How to Call the Web Service from ASP.net Application
To access the Web Service and exposed function, I am going to use the same
approach as I did first time when accessing SOAP Web service. There are few
other ways also but just to keep in sync I am using the same one.
You have to follow the Step 1 of the first section, and the following code using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml;
private void
btnShow_Click(object sender,
EventArgs e)
{
localhost.WebService call =
new localhost.WebService();
call.Url = "";
int far =
call.CelsiusToFahrenheit(30);
int cel =
call.FahrenheitToCelsius(86);
StringBuilder result =
new StringBuilder();
result.Append("30 Celcius = " +
far + " Fahrenheit");
result.AppendLine();
result.Append("86 Fahrenheit = "
+ cel + " Celcius");
textBox1.Text = result.ToString();
}
}
}
View All | https://www.c-sharpcorner.com/uploadfile/kaps_deo/how-to-consumeuse-the-web-service-from-application/ | CC-MAIN-2019-47 | en | refinedweb |
Find an item in the hwinfo structure
#include <hw/sysinfo.h> unsigned hwi_find_item( unsigned start, ... );)..);
QNX Neutrino
hwi_find_tag(), hwi_off2tag(), hwi_tag2off()
“Structure of the system page” in the Customizing Image Startup Programs chapter of Building Embedded Systems | http://www.qnx.com/developers/docs/6.5.0/topic/com.qnx.doc.neutrino_lib_ref/h/hwi_find_item.html | CC-MAIN-2019-47 | en | refinedweb |
Fun talk:Zombie Disco Squad
From RationalWiki
I may come back and add to this later, as well as create articles on other musicians and bands.--Graham 18:26, 25 September 2007 (EDT)
- Can you add categories as well please. Genghis Khant 18:42, 25 September 2007 (EDT)
- Done sir--Graham 19:01, 25 September 2007 (EDT)
--> Fun?[edit]
Susantalk to me 20:18, 25 September 2007 (EDT)
Perhaps. If you guys don't see any point to such articles then delete them, I do not mind.--Graham 02:28, 26 September 2007 (EDT)
- It's just that we're not an encyclopædia - anything not related to our mission is put in namespace "Fun" - no offence intended. Susantalk to me 02:33, 26 September 2007 (EDT)
No offence taken. I write sincerely by default and genuinely do not care what happens to work I author on this site considering that we opperate under mob rule.--Graham 11:53, 26 September 2007 (EDT)
There's two or three with a music bias - all have been moved to Fun - don't let it stop you, will you. Susantalk to me 12:11, 26 September 2007 (EDT) | https://rationalwiki.org/wiki/Fun_talk:Zombie_Disco_Squad | CC-MAIN-2019-47 | en | refinedweb |
If you ever faced the issue of content going below the screen in your Android or iOS application.
If we talk about Android we use ScrollView, our parent element is ScrollView and anything which is under ScrollView becomes scrollable.
In iOS, we set content size of UiScrollView.
Using Flutter we have SingleChildScrollView Widget.
We will have Column widget in our example app.
Our Column will have 1 Image, 1 Heading Text and 1 Description text (which will be lengthy text).
If We don’t wrap everything (image, 2 text widgets) inside SingleChildScrollView we will get ‘BOTTOM OVERFLOWED BY XX PIXELS’ error in our Flutter app.
SingleChildScrollView Example Code
import 'package:flutter/material.dart'; class ScrollView extends StatelessWidget { @override Widget build(BuildContext context) { return new Material( child: new Container( child: new SingleChildScrollView( child: new ConstrainedBox( constraints: new BoxConstraints(), child: new Column(children: <Widget>[ new Image.network( '', ), new Container( padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0), color: Colors.grey, child: new Text( 'Cast Light life style Here', textDirection: TextDirection.ltr, style: new TextStyle( fontSize: 40.0, fontWeight: FontWeight.bold, color: Colors.black, ), ), ), new Container( child: new Text( 'Hi There ? this is sample plaid app using flutter sdk and dart programming language, devceloper is Hammad Tariq' 'this is sample Flutter app example Code' 'Flutter Column Widget scrollable using SingleChildScrollView' 'I am just loving Flutter SDK' 'Flutter scrollview example using Single Child Scroll View' 'flutter fixing bottom overflow by xx pixels in flutter' 'Flutter scrollable layout example' 'Flutter app SingleChildScrollView Example ', textDirection: TextDirection.ltr, style: new TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.pink, ), ), ) ]), )))); } }
The output of above code:
Conclusion:
In this article, We have learned
- How to make layout scrollable in Flutter.
- How to make child widgets inside Column Scrollable using SingleChildScrollView.
One thought on “Flutter Scrollable layout using SingleChildScrollView Example”
Why did you wrapped the SingleChildScrollView in a Container? | http://developine.com/flutter-scrollable-layout-using-singlechildscrollview-scrollview/ | CC-MAIN-2019-47 | en | refinedweb |
abstract class defined API for attribute data More...
#include <vtkGenericAttribute.h>
abstract class defined API for attribute data
vtkGenericAttribute is an abstract class that defines an API for attribute data. Attribute data is data associated with the topology or geometry of a dataset (i.e., points, cells, etc.). vtkGenericAttribute is part of the adaptor framework (see GenericFiltering/README.html).
vtkGenericAttribute provides a more general interface to attribute data than its counterpart vtkDataArray (which assumes a linear, contiguous array). It adopts an iterator interface, and allows attributes to be associated with points, edges, faces, or edges.
Definition at line 50 of file vtkGenericAttribute.h.
Definition at line 53 of file vtkGenericAttribute.h.
Return 1 if this class is the same type of (or a subclass of) the named class.
Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h.
Reimplemented from vtkObjectBase.
Name of the attribute.
(e.g. "velocity")
Is the attribute centered either on points, cells or boundaries?
Type of the attribute: scalar, vector, normal, texture coordinate, tensor.
Type of the components of the attribute: int, float, double.
Number of tuples.
Size in kibibytes (1024 bytes) taken by the attribute.
Range of the attribute component ‘component’.
If ‘component’==-1, it returns the range of the magnitude (euclidean norm). It returns double, even if GetType()==VTK_INT. NOT THREAD SAFE
Range of the attribute component ‘component’.
If ‘component’==-1, it returns the range of the magnitude (euclidean norm). THREAD SAFE
Return the maximum euclidean norm for the tuples.
Attribute at all points of cell ‘c’.
Put attribute at all points of cell ‘c’ in ‘tuple’.
Attribute at all points of cell ‘c’.
Put attribute at all points of cell ‘c’ in ‘tuple’.
Value of the attribute at position ‘p’.
Put the value of the attribute at position ‘p’ into ‘tuple’.
Put component ‘i’ of the attribute at all points of cell ‘c’ in ‘values’.
Value of the component ‘i’ of the attribute at position ‘p’.
Recursive duplication of ‘other’ in ‘this’.
Update ‘this’ using fields of ‘other’. | https://vtk.org/doc/nightly/html/classvtkGenericAttribute.html | CC-MAIN-2019-47 | en | refinedweb |
I have an audio clip that plays when my game starts up, but it doesn't loop. I'm not sure why it doesn't loop.
Here's the code exactly as it stands, it's not too complicated.
#pragma strict
function Start () {
AudioSource.PlayClipAtPoint(audio.clip, Camera.main.transform.position);
}
function Update () {
// Play the audio for this image
if (audio.isPlaying != true)
AudioSource.PlayClipAtPoint(audio.clip, Camera.main.transform.position);
Debug.Log(audio.loop);
}
The Debug.Log line is reporting true. My music ends, and the sound does not get played again. How do I get my sound to loop?
Answer by hijinxbassist
·
Mar 21, 2012 at 09:02 AM
Have you actually physically checked that the audio sources loop is set to true(box with check mark). If not, un click "Maximize On Play" and look at the offending audio source while the game is playing.
Also, keep looking at the audio source after the sound has finished. This will help determine what is wrong. Just for testing, add this new line to your script....
function Start ()
{
AudioSource.PlayClipAtPoint(audio.clip, Camera.main.transform.position);
transform.GetComponent(AudioSource).audio.loop=true;
}
Is the source parented to your camera, if not...then this is the problem. There needs to be an AudioListener in range of the AudioSource. If this is its own GameObject, parent it to the camera. Simple as that, the more i think about it, the more i think this is the issue. You have it play at the cameras position, but then you move and no longer hear it(i cant say for sure without seeing actual game play).
Thanks, attaching the audio source and script to my camera -- instead of my background game object -- made it actually loop after the sound finished playing.
I'm also really happy that this led to me being able to use "audio.Play()" as advertised. It wouldn't work, before, likely because of some camera hijinx that I don't know about.
Please don't reply to a 2 year old thread. Instead, make your own. :)
Don't use Debug.Log() for this because it will keep echoing over-and-over and dropping the framerate.
Answer by Kryptos
·
Mar 21, 2012 at 04:36 PM
You can't loop sounds started with AudioSource.PlayClipAtPoint. This method doesn't use the AudioSource component of your object but instead creates a temporary (and hidden) object. This is the intended behaviour.
As mentioned in documentation, you can use an alternative method. See for more details.
Answer by theropodx
·
Jun 29, 2012 at 02:12 AM
Strange, the "alternative method" from that link has disappeared. Maybe Unity removed that function in the latest build? Anyway, it's missing from the doc link above now.
Answer by Vetpetmon
·
Nov 29, 2014 at 02:09 AM
When I used the code it would also try to crash my computer with it spamming 379 messages saying "True" per 30 seconds, any fixes? It lagged so badly it dropped me down to 0 Frames Per Second, I spent 10 minuets to restore my computer's memory usage to normal. EDIT: Now it's spamming the music! EDIT:IT WORKS!!!:
#pragma strict
function Start () {
AudioSource.PlayClipAtPoint(audio.clip, Camera.main.transform.position);
transform.GetComponent(AudioSource).audio.loop=true;
}
function Update () {
// Play the audio for this image
if (audio.isPlaying != true)
AudioSource.PlayClipAtPoint(audio.clip, Camera.main.transform.position);
}
Thanks, that helped a lot.
Answer by kfirmon
·
Oct 03, 2015 at 02:38 PM
The problem might be a result of using "Play on awake". I attached a script to the Audio Source instead and it solved the problem.
using UnityEngine;
using System.Collections;
public class MusicPlayer : MonoBehaviour
{
public AudioClip clip; // Drag the clip here on the editor
private AudioSource au;
void Start()
{
au = GetComponent<AudioSource>();
au.loop = true;
au.
Trigger audio loop on beat with PlayScheduled
1
Answer
How can I loop a song from a specific point?
1
Answer
Why can't I hear my audio?
5
Answers
How to start/stop/loop different music tracks
0
Answers
How To trim audio run time in game?
1
Answer | https://answers.unity.com/questions/230066/why-doesnt-my-music-loop.html | CC-MAIN-2019-47 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.