text
stringlengths 20
1.01M
| url
stringlengths 14
1.25k
| dump
stringlengths 9
15
⌀ | lang
stringclasses 4
values | source
stringclasses 4
values |
|---|---|---|---|---|
Application.Startup Event
Microsoft Silverlight will reach end of support after October 2021. Learn more.
Occurs when an application is started.
Namespace: System.Windows
Assembly: System.Windows (in System.Windows.dll)
Syntax
'Declaration Public Event Startup As StartupEventHandler
public event StartupEventHandler Startup
<Application Startup="eventhandler"/>
Remarks.
Examples
The following code shows how to handle the Startup event.
Partial Public Class App Inherits Application public Sub New() InitializeComponent() End Sub Private Sub Application_Startup(ByVal o As Object, _ ByVal e As StartupEventArgs) Handles Me.Startup ' Detect when the application starts up. End Sub End Class
using System.Windows; // Application, StartupEventArgs namespace SilverlightApplication { public partial class App : Application { public App() { this.Startup += this.Application_Startup; InitializeComponent(); } private void Application_Startup(object sender, StartupEventArgs e) { // Detect when the application starts up. } } }
|
https://docs.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/ms588007(v=vs.95)?redirectedfrom=MSDN
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
kdevelop/kdevplatform/interfaces
#include <itestsuite.h>
Detailed Description
A unit test suite class.
Definition at line 37 of file itestsuite.h.
Member Enumeration Documentation
Specifies how much output a test job should produce.
Definition at line 45 of file itestsuite.h.
Constructor & Destructor Documentation
Destructor.
Definition at line 24 of file itestsuite.cpp.
Member Function Documentation
- Returns
- the list of all test cases in this suite.
The location in source code where the test suite is declared.
If no such declaration can be found, an invalid declaration is returned.
Return a job that will execute all the test cases in this suite.
The implementation of this class is responsible for creating the job and interpreting its results. After the job is finished, the test results should be made available to the result() function.
Starting the job is up to the caller, usually by registering it with the run controller.
- Parameters
-
- Returns
- a KJob that will run only
testCase.
- See also
- launchAllCases()
- Parameters
-
- Returns
- a KJob that will run the specified
testCases.
- See also
- launchAllCases()
- Returns
- the display name of this suite. It has to be unique within a project.
Get the project to which this test suite belongs.
Since all suites must have a project associated, this function should never return 0.
- Returns
- the test suite's project.
The documentation for this class was generated from the following files:
Documentation copyright © 1996-2019 The KDE developers.
Generated on Mon Nov 11 2019 07:28:49 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online.
|
https://api.kde.org/extragear-api/kdevelop-apidocs/kdevelop/kdevplatform/interfaces/html/classKDevelop_1_1ITestSuite.html
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
Thus far in this series on Effects, we've discussed building and using Effects that have a single "texture" or "sampler" as input to them. In the Beta of .NET 3.5 SP1, that's all that was available. With the RTM release, we've added the ability to provide multiple samplers as input to the pixel shaders that drive Effects, thus substantially increasing the flexibility of what can be done with Effects.
In this post, I'll show a very simple example of multi-input effects. The result isn't anything particularly useful from a UI construction perspective, but it shows the general technique that can be used in more UI-relevant ways. In fact, in the next post I do, I'll show something that's quite a bit more interesting from a UI perspective.
The result
I'll demonstrate a simple shader that just combines, via pixel addition, two images. This lets me take these two images:
and create a little app that can produce these sorts of combinations of the two:
The code
Let's first look at the XAML needed to build this. This example, in fact, has no code at all... it's all XAML. (At least the program that consumes the Effect... the Effect definition itself requires code.)
<Window ... >
<Window.Resources>
<ImageBrush x:
</Window.Resources>
<StackPanel>
<Image Source="toucan.jpg" Width="1024" Height="768">
<Image.Effect>
<eff:SimpleMultiInputEffect
</Image.Effect>
</Image>
<StackPanel Margin="10" Orientation="Horizontal">
<Slider Minimum="-0.5" Maximum="1" SmallChange="1" LargeChange="1" Value="0.5" Name="slider1" Width="289" />
<Label HorizontalAlignment="Left" Name="label1" VerticalAlignment="Bottom" Width="120" Content="{Binding ElementName=slider1, Path=Value}" />
</StackPanel>
</StackPanel>
</Window>.
Next, the <Image> displays the Toucan image, and we apply our custom "SimpleMultiInputEffect" to the <Image>. Here, we set a property, Input2, as a reference to our ImageBrush holding the tree. We also set a double-valued property MixInAmount, which is bound to the slider value. The Effect itself lets MixInAmount control the amount of blending that Input2 will do against the primary input.
Moving to the Effect definition itself. In the C# for the Effect, the only thing notable is that we define another Brush-valued DependencyProperty:
public Brush Input2
{
get { return (Brush)GetValue(Input2Property); }
set { SetValue(Input2Property, value); }
}
public static readonly DependencyProperty Input2Property =
ShaderEffect.RegisterPixelShaderSamplerProperty("Input2", typeof(SimpleMultiInputEffect), 1);
The "1" provided as the last argument to RegisterPixelShaderSamplerProperty() indicates that this Brush's realization will be available in sampler register "1" in the pixel shader.
The HLSL gets a little more interesting:
//-----------------------------------------------------------------------------------------
// Shader constant register mappings (scalars - float, double, Point, Color, Point3D, etc.)
//-----------------------------------------------------------------------------------------
float mixInAmount : register(C0);
//--------------------------------------------------------------------------------------
// Sampler Inputs (Brushes, including ImplicitInput)
//--------------------------------------------------------------------------------------
sampler2D input1 : register(S0);
sampler2D input2 : register(S1);
//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 main(float2 uv : TEXCOORD) : COLOR
{
float4 color1 = tex2D(input1, uv);
float4 color2 = tex2D(input2, uv);
return color1 + mixInAmount * color2;
}
This is also very simple. All that's happening here is that color1 and color2 are being sampled from the two input samplers (the Toucan and the Tree images, in our application), and combined according to the value of mixInAmount. When that value is 0, we end up with pure Toucan . When it's positive, we're adding Tree in. When negative, we're subtracting Tree out. All on a per-pixel basis.
More explanation
There are a few more details worth expanding on here:
- The secondary inputs get sized to the rendered size of the UIElement that the effect is being applied to. Thus, when they make it into the shader, all the sampler inputs are the same pixel size. You can use transforms on the incoming brushes, or viewport/viewbox, to manipulate different portions of the brush into place for finer control. (In the above example, both the toucan image and the tree image are the same size, so it didn't matter here.)
- You might be wondering how the initial sampler input gets its value, since we never assigned in Brush-valued resources through XAML or code in previous examples. That's because the default for all samplers (registered via RegisterPixelShaderSamplerProperty) is a special Brush that you get from accessing Effect.ImplicitInput. ImplicitInput just means "construct a brush from the image resulting from rendering the UIElement that this Effect is being applied to". So, in the case above, this is the <Image> element that we have the Toucan in. If we were applying the Effect to a Button, it'd be the rasterization of the Button.
That's it
That's it for now. I've attached the solution that demonstrates this. To build it, it requires the Shader Build Task that I had previously written about. Next time I'll show a use of multiple effects that has a more practical use for UIs than the simple blending demonstrated above.
SimpleMultiInputEffect.zip
PingBack from
Greg – Does SP1 support more than shader model 2.0? I created some effects with pre-RTM and was hitting the 96 instruction (?) limit without much effort.
FYI I attempted to implement a chroma-key effect; the idea being to selectively replace shades of green with equivalent levels of transparency to allow the background to show through (with some semblance of anti-aliasing). It worked, but not as well as I’d hoped. To improve it I tried to convert the colors to HSV first, but that’s when I hit the shader 2.0 limits.
Using multi-input, is it possible to chain effects? I’m wondering about having a few effects; one to cnovert to HSV, one to apply the transparency, then one to convert back to RGBA. Any comments? (suggestions on better ways to implement it would be greatly appreciated). Thanks! :o)
good blog this is . i think u r good in blogging .keep it up.
visit ma blog
wanna blog link exchange contect me at eck.naresh@gmail.com
I appreciate your helpful article – I was actually able to create a working VS 2008 sample from your code with no problem at all!
Question: What do we need to do, to create an Effect that translates the pixels horizontally, and the distance being a function of the frame-rate? My purpose is simply to scroll an image horizontally, with complete smoothness as though it were a video panning. Thank you so very much for your advice and excellent articles,
JH
Chris asked about a couple of things:
1) More than Shader Model 2.0 — no, currently WPF only supports Pixel Shader Model 2.0. This is primarily because the software JITter that we use in the absence of a sufficient GPU only knows about PS2.0 currently.
2) Can effects be chained with multi-input. Yes, but not by an explicit "effect chaining" mechanism. The way you do it is by composing additional controls. For instance, you can wrap a Decorator around your element, and put an Effect on both the Decorator and on the element. That results in what appears to be chained shaders. (Note that it has to render the inner effect to a new surface before can apply the outer effect, so it’s not as efficient as true multipass would be.)
James asked about Effects being able to translate based on frame rate.
Yes, this is absolutely possible. The most direct way of doing this is to register with CompositionTarget.Rendering. This is an event that will be invoked every frame. You can then monitor the frame rate you’re getting, and feed that information back into the shader as a registered DependencyProperty for the shader to use as it needs to.
In my last post , I introduced multi-input effects, where you can send in arbitrary WPF brushes that
GPU-based Effects are a hot new feature in WPF for .NET 3.5 SP1. I’m going to be blogging a series of
Chris Cavanagh with Actionscript layout library, Martin Mihaylov with Voting control, Bart Czernicki
Whilst my day job continues on its ever-accelerating decline 🙂 I thought I’d entertain myself by experimenting…
Artur Żarski u mnie w firmie, od jakiegoś czasu, a dokładniej odkąd zobaczył moje zabawy z Xna męczył
|
https://blogs.msdn.microsoft.com/greg_schechter/2008/09/16/introducing-multi-input-shader-effects/
|
CC-MAIN-2019-47
|
en
|
refinedweb
|
$ cnpm install u-wave-http-api
HTTP API plugin for üWave, the collaborative listening platform.
Getting Started - API - Building - License
Note: üWave is still under development. Particularly the
u-wave-coreand
u-wave-http-apimodules will change a lot before the "official" 1.0.0 release. Make sure to always upgrade both of them at the same time.
npm install u-wave-http-api
The module exports a middleware that can be used with express-style HTTP request handlers.
import { createHttpApi, createSocketServer } from 'u-wave-http-api' const { createHttpApi, createSocketServer } = require('u-wave-http-api')
Creates a middleware for use with Express or another such library. The first parameter is a
u-wave-core instance. Available options are:.
Example
import express from 'express'; import stubTransport from 'nodemailer-stub-transport'; import uwave from 'u-wave-core'; import { createHttpApi } from 'u-wave-http-api'; const app = express(); const secret = fs.readFileSync('./secret.dat'); const uw = uwave({ secret: secret, }); const api = createHttpApi(uw, { secret: secret, // Encryption secret recaptcha: { secret: 'AABBCC...' }, // Optional mailTransport: stubTransport(), // Optional onError: (req, error) => {}, // Optional }); app.use('/v1', api);
Returns a middleware that attaches the üWave core object and the üWave http-api object to the request. The
u-wave-core instance will be available as
req.uwave, and the
u-wave-http-api instance will be available as
req.uwaveHttp. This is useful if you want to access these objects in custom routes, that are not in the
u-wave-http-api namespace. E.g.:
Example
app.use('/api', api); // A custom profile page. app.get('/profile/:user', api.attachUwaveToRequest(), (req, res) => { const uwave = req.uwave; uwave.getUser(req.params.user).then((user) => { res.send(`<h1>Profile of user ${user.username}!</h1>`); }); });
Create the WebSocket server used for realtime communication, like advance notifications and chat messages.
server- An HTTP server instance.
u-wave-http-apiuses WebSockets, and it needs an HTTP server to listen to for incoming WebSocket connections. An example for how to obtain this server from an Express app is shown below.
port- and the
createHttpApifunction.
Example
import express from 'express'; import { createSocketServer } from 'u-wave-http-api'; const app = express(); const server = app.listen(8080); const secret = fs.readFileSync('./secret.dat'); const sockets = createSocketServer(uw, { server, // The HTTP server secret: secret, // Encryption secret }); // ALTERNATIVELY: const sockets = createSocketServer(uw, { port: 6042, // Port to listen on—make sure to configure web clients for this secret: secret, // Encryption secret });
There is a development server included in this repository. To use it, first you have to clone and install u-wave-core.
git clone u-wave-core cd u-wave-core npm install npm link
Then you can clone and install the HTTP API:
git clone u-wave-http-api cd u-wave-http-api npm install # Add our local u-wave-core npm link u-wave-core # & run the server! npm start -- --port 604
|
https://developer.aliyun.com/mirror/npm/package/u-wave-http-api
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
The command line argument is the argument that passed to a program during runtime. It is the way to pass argument to the main method in Java. These arguments store into the String type args parameter which is main method parameter.
To access these arguments, you can simply traverse the args parameter in the loop or use direct index value because args is an array of type String.
For example, if we run a HelloWorld class that contains main method and we provide argument to it during runtime, then the syntax would be like.
java HelloWorld arg1 arg2 ...
We can pass any number of arguments because argument type is an array. Lets see an example.Example
In this example, we created a class HelloWorld and during running the program we are providing command-line argument.
Execute this program as java cmd 10 20 30Execute this program as java cmd 10 20 30
class cmd { public static void main(String[] args) { for(int i=0;i< args.length;i++) { System.out.println(args[i]); } } }
10 20 30
To terminate the program in between based on some condition or program logic, Java provides exit() that can be used to terminate the program at any point. Here we are discussing about the exit() method with the example.
System.exit()Method
In Java,
exit() method is in the java.lang.System class. This method is used to take an exit or terminating from a running program. It can take either zero or non-zero value.
exit(0) is used for successful termination and
exit(1) or
exit(-1) is used for unsuccessful termination. The
exit() method does not return any value.
Example:
In this program, we are terminating the program based on a condition and using
exit() method.
import java.util.*; import java.lang.*; class ExitDemo1 { public static void main(String[] args) { intx[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50}; for (inti = 0; i<x.length; i++) { if (x[i] >= 40) { System.out.println("Program is Terminated..."); System.exit(0); } else System.out.println("x["+i+"] = " + x[i]); } } }
|
https://studytonight.com/java/command-line-argument.php
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
When working with the legacy Ember object model,
EmberObject, there are a number of caveats and limitations you need to be aware of. For today, these caveats and limitations apply to any classes which extend directly from
EmberObject, or which extend classes which themselves extend
EmberObject:
Component – meaning classic Ember components, which imported from
@ember/component, not Glimmer components which are imported from
@glimmer/component and do not extend the
EmberObject base class.
Controller
Helper – note that this applies only to the class form. Function-based helpers do not involve the
EmberObject base class.
Route
Router
Service
Ember Data’s
Model class
Additionally, Ember’s mixin system is deeply linked to the semantics and implementation details of
EmberObject, and it has the most caveats and limitations.
In the future, some of these may be able to drop their
EmberObject base class dependency, but that will not happen till at least the next major version of Ember, and these guides will be updated when that happens.
The Ember mixin system is the legacy Ember construct TypeScript supports least well, as described in Mixins. While this may not be intuitively obvious, the classic class syntax simply is the mixin system. Every classic class creation is a case of mixing together multiple objects to create a new base class with a shared prototype. The result is that any time you see the classic
.extend({ ... }) syntax, regardless of whether there is a named mixin involved, you are dealing with Ember's legacy mixin system. This in turn means that you are dealing with the parts of Ember which TypeScript is least able to handle well.
While we describe here how to use types with classic (mixin-based) classes insofar as they do work, there are many failure modes. As a result, we strongly recommend moving away from both classic classes and mixins, and as quickly as possible. This is the direction the Ember ecosystem as a whole is moving, but it is especially important for TypeScript users.
The Ember Atlas includes guides for migrating from classic classes to native classes, along with a variety of patterns for dealing with specific kinds of mixins in your codebase.
You often need to define
this in actions hashes, computed properties, etc. That in turn often leads to problems with self-referential
this: TypeScript simply cannot figure out how to stop recursing through the definitions of the type.
Additionally, even when you get past the endlessly-recursive type definition problems, when enough mixins are resolved TypeScript will occasionally just give up because it cannot resolve the property or method you're interested in across the many shared base classes.
Finally, when you have "zebra-striping" of your classes between classic classes and native classes, your types will often stop resolving.
In general, we recommend (following the Ember Octane guides) that any class which extends directly from the
EmberObject base class eliminate any use of
EmberObject-specific API and convert to standalone class, with no base class at all. You can follow the ember-classic-decorator workflow to eliminate the base class—switching from
init to
constructor, getting rid of uses of methods like
this.set and
this.get in favor of using standalone
set and
get, and so on.
The framework base classes which depend on
EmberObject cannot follow the exact same path. However, as long as you are using native class syntax, all of these (
Component,
Controller,
Helper, etc.) work nicely and safely with TypeScript. In each of these cases, the same caveats apply as with
EmberObject itself, and you should follow the ember-classic-decorator workflow with them as well if you are converting an existing app or addon. However, because these base classes themselves descend from
EmberObject, you will not be able to remove the base classes as you can with your own classes which descend directly from
EmberObject. Instead, you will continue to extend from the Ember base classes:
import Component from '@ember/component';export default class Profile extends Component {}
import Controller from '@ember/controller';export default class IndexController extends Controller {}
import Helper from '@ember/component/helper';export default class Localize extends Helper {}
import Route from '@ember/routing/route';export default class ApplicationRoute extends Route {}
import EmberRouter from '@ember/routing/router'export default class AppRouter extends EmberRouter {}
import Service from '@ember/service';export default class Session extends Service {}
import Model from '@ember-data/model';export default class User extends Model {}
|
https://docs.ember-cli-typescript.com/legacy/ember-object
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
-XAutoDeriveTypeable fails to generate instances
The following doesn't compile with GHC 7.8.3, but works with GHC HEAD. I couldn't find a matching ticket, so I don't know if this was fixed knowingly or not...
{-# LANGUAGE AutoDeriveTypeable #-} import Data.Typeable (Typeable) data T1 = C1 Int deriving (Eq,Ord) tvoid :: Typeable a => a -> IO () tvoid _ = return () main :: IO () main = tvoid (C1 0)
- ..fails for GHC 7.8.3 with
No instance for (Typeable T1) arising from a use of ‘tvoid’ In the expression: tvoid (C1 0) In an equation for ‘main’: main = tvoid (C1 0)
I'm marking this with high priority, as it makes
-XAutoDeriveTypeable unusable on GHC 7.8.3 as it stands.
|
https://gitlab.haskell.org/ghc/ghc/-/issues/9575
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
- In the last tutorial we have discussed the Dart programming fundamentals.From this post onwards we are going to explore Flutter and we will learn more about Dart when we are continue it by doing.
- In the day0 we have completed to setup of our beautiful editor (VS Code) If you are having pretty heavy machine you can go with Android Studio.
Let's create our first app in Flutter by launching the code editor in our case VS Code and follow the steps.
ctrl+shift+pwill invoke Command Palette.
Type “flutter”, and select the Flutter: New Project.
Enter a project name, such as myapp, and press Enter.
Create or select the parent directory for the new project folder , wait for project creation to complete and the main.dart file to appear.
Whenever we are launching our application in an emulator or in real device
main.dartfile runs first.
Using real device:
How to enable developer options:
- open Settings > About phone > tap on Build number 7 times.
USB debugging:
- Connect your mobile to your computer using USB cable.
- Further you should turn on USB debugging in developer options.
- Open settings > Additional Settings > Developer options > USB debugging >turn on
- If you are using Redmi/Xiaomi mobiles then you should turn off MIUI Optimisation option which is present in developer options (At the end of developer options scroll down).
Using Emulator:
-). 5. Then click Next.
- Click Finish. Wait for Android Studio to install the SDK and create the project.
- Press the Run button.
Creating AVD (Android Virtual Device):
Open Android Studio / IntelliJ head back to AVD Manage on the top-right corner / select Tools> Android > AVD Manager and create one there.
If you want to run the app then press
F5.
Here we go we ready now!
Writing Your First Flutter App::
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Welcome to Flutter', home: Scaffold( appBar: AppBar( title: Text('Flutter'), ), body: Center( child: Text('Welcome to Flutter Development Tutorial'), ), ), ); } }
F5or
fn+F5.It will run the code and launch the app in your Emulator/Real Device.
In Flutter everything is a Widget.
Ex. Text is a Widget, Center is a Widget,Scaffold is also a Widget like in Android everything is a View.
Here are some the basic Widgets that everyone must know.
First of all
importthe material package as it contains all the Widgets and Methods to use.
MaterialApp
- Material App is the basic Widget which holds all the views.We have to wrap the main app with Material App because it gives us the default view of the app.
Scaffold:
- Scaffold gives us default structure of the app by providing an AppBar and a Body.
- Implements the basic Material Design visual layout structure. This class provides APIs for showing drawers, snack bars, and bottom sheets.
Appbar:
- A Material Design app bar. An app bar consists of a toolbar and potentially other widgets, such as a Tab Bar and a Flexible Space Bar.
Container:
- A convenience widget that combines common positioning of the widgets.
Row:
- Layout a list of child widgets in the horizontal direction.
Column:
- Layout a list of child widgets in the vertical direction.
Text:
- A run of text with a single style.
Image:
- A widget that displays an image.
Icon:
- A Material Design icon.
Raised Button:
A Material Design raised button. A raised button consists of a rectangular piece of material that hovers over the interface.
Here I am using VS code because it is lightweight and I am testing my app in real device because emulator is very slow in my laptop because I'm using some old stuff.Hope you can understand that.Past I used emulator but now I'm using my real device.
If you wish to use your real device then don't forget to turn on USB degugging
in developer options
Discussion
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/bugudiramu/flutter-development-day-2-41e6
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
This is unfortunately more of a hack than a solution, but I thought I would share it any way. I had the situation where I needed to validate the entered time into a masked textbox. The masked textbox is a Windows Form control, but I hosted it within a WPF window using the WIndowsFormsHost element. Lastly, for some reason I could not get the Leave event to fire, so I opted to use the TextChanged event with some additional logic, checking the length of the entered value before validating it.
Initially, for validating the time I tried using the Regex class found within the System.Text.RegularExpressions namespace. However, after more research I discovered the TryParseExact method within the TimeSpan class. I validate the time entered into the masked textbox like below.
TimeSpan time;
bool valid = TimeSpan.TryParseExact(theTime, "g",
CultureInfo.CurrentCulture, out time);
Where “theTime” is a string formatted like “hh:mm”. Works perfectly.
The TextChanged event fires when I set the mask for the textbox. Initially, I had set the mask via the XAML, however I wanted to prevent the time validation check from running unnecessarily. Therefore, I set the mask within Windows_Loaded event and stopped the TextChange event from firing before the mask was set. The below code was added to the Window_Loaded event of the window and is shown below how I did disabled and re-enabled the event.
maskedTimeTextBox.TextChanged -= new EventHandler(maskedTimeTextBox _TextChanged);
maskedTimeTextBox.Mask = "00:00";
maskedTimeTextBox.TextChanged += new EventHandler(maskedTimeTextBox _TextChanged);
I created a method called ValidateTime() and called it from the TextChanged event and later from the method where I save the value to the database.
try
{
if (maskedTimeTextBox.Text.Length > 4)
{
TimeSpan time;
bool success = TimeSpan.
TryParseExact(theTime, "g",
CultureInfo.CurrentCulture,
out time);
if(TimeSpan.TryParseExact(theTime, "g",
CultureInfo.CurrentCulture,
out time))
{
return success;
}
else
{
MessageBox.Show("Please enter time in hh:mm format.",
"Error", MessageBoxButton.OK,
MessageBoxImage.Error);
maskedTimeTextBox.Text = "";
return false;
}
}
return false;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message,
"Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
As I could not get the Leave event to fire, nor could I find another event to use that would occur once the entire time was entered and the user either entered Save or the control lost focus, I used the above logic within the TextChanged event.
I know that a valid time, in my context, will be 5 characters long as shown above, 11:55 is greater than 4 characters and only 5 are allowed due to the mask. So the validation will only happen if the time entered into the masked textbox is greater than 4.
I am thinking that I may need to bind the masked textbox Windows Form control to the WPF window in some way to get the Leave event to fire. However, like most developers we have deadlines and other constraints that keep us, on many occasions, from implementing the correct implementation. Nonetheless, the code does not fire unless required and the validation only checks when the entered time is likely to pass. The point it, the implementation may not be perfect but the ineffeciencies of this implementation have been overcome by some additional logic added to the Window_Loaded event and the ValidateTime() method.
If you can think of a better solution I’d like to hear from you, please leave a comment. If I find a better one in the future I will make the edit.
|
https://www.thebestcsharpprogrammerintheworld.com/2012/09/10/validating-time-using-a-masked-textbox-within-a-wpf-window-using-c/
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
Man pages for fortran
Project description
Man pages for fortran
Development of Fortran man pages happens on Github.
Installation
To install the latest released version of Fortran man pages, run this command in your terminal:
$ pip install fortranman
This is the preferred method to install Fortran man pages, as it will always install the most recent stable release.
If you don’t have pip installed, this Python installation guide can guide you through the process.
To install the latest development version of Fortran man pages from Github.
$ pip install git+
Usage
To use Fortran man pages in a project:
import fortranman
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/fortranman/
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
In this post I lay the groundwork for creating a custom implementation of
DfaGraphWriter.
DfaGraphWriter is public, so you can use it in your application as I showed in my previous post, but all the classes it uses are marked
internal. That makes creating your own version problematic. To work around that, I use an open source reflection library, ImpromptuInterface, to make creating a custom
DfaGraphWriter implementation easier.
We'll start by looking at the existing
DfaGraphWriter, to understand the
internal classes it uses and the issues that causes us. Then we'll look at using some custom interfaces and the
ImpromptuInterface library to allow us to call those classes. In the next post, we'll look at how to use our custom interfaces to create a custom version of the
DfaGraphWriter.
Exploring the existing
DfaGraphWriter
The
DfaGraphWriter class lives inside one of the "pubternal" folders in ASP.NET Core. It's registered as a singleton and uses an injected
IServiceProvider to retrieve the helper service,
DfaMatcherBuilder:
public class DfaGraphWriter { private readonly IServiceProvider _services; public DfaGraphWriter(IServiceProvider services) { _services = services; } public void Write(EndpointDataSource dataSource, TextWriter writer) { // retrieve the required DfaMatcherBuilder var builder = _services.GetRequiredService<DfaMatcherBuilder>(); // loop through the endpoints in the dataSource, and add them to the builder var endpoints = dataSource.Endpoints; for (var i = 0; i < endpoints.Count; i++) { if (endpoints[i] is RouteEndpoint endpoint && (endpoint.Metadata.GetMetadata<ISuppressMatchingMetadata>()?.SuppressMatching ?? false) == false) { builder.AddEndpoint(endpoint); } } // Build the DfaTree. // This is what we use to create the endpoint graph var tree = builder.BuildDfaTree(includeLabel: true); // Add the header writer.WriteLine("digraph DFA {"); // Visit each node in the graph to create the output tree.Visit(WriteNode); //Close the graph writer.WriteLine("}"); // Recursively walks the tree, writing it to the TextWriter void WriteNode(DfaNode node) { // Removed for brevity - we'll explore it in the next post } } }
The code above shows everything the graph writer's
Write method does, but in summary:
- Fetches a
DfaMatcherBuilder
- Writes all of the endpoints in the
EndpointDataSourceto the
DfaMatcherBuilder.
- Calls
BuildDfaTreeon the
DfaMatcherBuilder. This creates a graph of
DfaNodes.
- Visit each
DfaNodein the tree, and write it to the
TextWriteroutput. We'll explore this method in the next post.
The goal of creating our own custom writer is to customise that last step, by controlling how different nodes are written to the output, so we can create more descriptive graphs, as I showed previously:
Our problem is that two key classes,
DfaMatcherBuilder and
DfaNode, are
internal so we can't easily instantiate them, or write methods that use them. That gives one of two options:
- Reimplement the
internalclasses, including any further
internalclasses they depend on.
- Use reflection to create and invoke methods on the existing classes.
Neither of those are great options, but given that the endpoint graph isn't a performance-critical thing, I decided using reflection would be the easiest. To make things even easier, I used the open source library, ImpromptuInterface.
Making reflection easier with ImpromptuInterface
ImpromptuInterface is a library that makes it easier to call dynamic objects, or to invoke methods on the underlying object stored in an
object reference. It essentially adds easy duck/structural typing, by allowing you to use a stronlgy-typed interface for the object. It achieves that using the Dynamic Language Runtime and
Reflection.Emit.
For example, lets take the existing
DfaMatcherBuilder class that we want to use. Even though we can't reference it directly, we can still get an instance of this class from the DI container as shown below:
// get the DfaMatcherBuilder type - internal, so needs reflection :( Type matcherBuilder = typeof(IEndpointSelectorPolicy).Assembly .GetType("Microsoft.AspNetCore.Routing.Matching.DfaMatcherBuilder"); object rawBuilder = _services.GetRequiredService(matcherBuilder);
The
rawBuilder is an
object reference, but it contains an instance of the
DfaMatcherBuilder. We can't directly call methods on it, but we can invoke them using reflection by building
MethodInfo and calling
Invoke directly.
ImpromptuInterface makes that process a bit easier, by providing a static interface that you can directly call methods on. For example, for the
DfaMatcherBuilder, we only need to call two methods,
AddEndpoint and
BuildDfaTree. The original class looks something like this:
internal class DfaMatcherBuilder : MatcherBuilder { public override void AddEndpoint(RouteEndpoint endpoint) { /* body */ } public DfaNode BuildDfaTree(bool includeLabel = false) }
We can create an interface that exposes these methods:
public interface IDfaMatcherBuilder { void AddEndpoint(RouteEndpoint endpoint); object BuildDfaTree(bool includeLabel = false); }
We can then use the ImpromptuInterface
ActLike<> method to create a proxy object that implements the
IDfaMatcherBuilder. This proxy wraps the
rawbuilder object, so that when you invoke a method on the interface, it calls the equivalent method on the underlying
DfaMatcherBuilder:
In code, that looks like:
// An instance of DfaMatcherBuilder in an object reference object rawBuilder = _services.GetRequiredService(matcherBuilder); // wrap the instance in the ImpromptuInterface interface IDfaMatcherBuilder builder = rawBuilder.ActLike<IDfaMatcherBuilder>(); // we can now call methods on the builder directly, e.g. object rawTree = builder.BuildDfaTree();
There's an important difference between the original
DfaMatcherBuilder.BuildDfaTree() method and the interface version: the original returns a
DfaNode, but that's another
internal class, so we can't reference it in our interface.
Instead we create another
ImpromptuInterface for the
DfaNode class, and expose the properties we're going to need (you'll see why we need them in the next post):
public interface IDfaNode { public string Label { get; set; } public List<Endpoint> Matches { get; } public IDictionary Literals { get; } // actually a Dictionary<string, DfaNode> public object Parameters { get; } // actually a DfaNode public object CatchAll { get; } // actually a DfaNode public IDictionary PolicyEdges { get; } // actually a Dictionary<object, DfaNode> }
We'll use these properties in the
WriteNode method in the next post, but there's some complexities. In the original
DfaNode class, the
Parameters and
CatchAll properties return
DfaNode objects. In our
IDfaNode version of the properties we have to return
object instead. We can't reference a
DfaNode (because it's
internal) and we can't return an
IDfaNode, because
DfaNode doesn't implement
IDfaNode, so you can't you can't implicitly cast the
object reference to an
IDfaNode. You have to use ImpromptuInterface to explicitly add a proxy that implements the interface.
For example:
// Wrap the instance in the ImpromptuInterface interface IDfaMatcherBuilder builder = rawBuilder.ActLike<IDfaMatcherBuilder>(); // We can now call methods on the builder directly, e.g. object rawTree = builder.BuildDfaTree(); // Use ImpromptuInterface to add an IDfaNode wrapper IDfaNode tree = rawTree.ActLike<IDfaNode>(); // We can now call methods and properties on the node... object rawParameters = tree.Parameters; // ...but they need to be wrapped using ImpromptuInterface too IDfaNode parameters = rawParameters.ActLike<IDfaNode>();
We have another problem with the properties that return
Dictionary types:
Literals and
PolicyEdges. The actual types returned are
Dictionary<string, DfaNode> and
Dictionary<object, DfaNode> respectively, but we need to use a type that doesn't contain the
DfaNode type. Unfortunately, that means we have to fall back to the .NET 1.1
IDictionary interface!
You can't cast a
Dictionary<string, DfaNode>to an
IDictionary<string, object>is because doing so would be an unsafe form of covariance.
IDictionary is a non-generic interface, so the
key and
value are only exposed as
objects. For the
string key you can cast directly, and for the
DfaNode we can use ImpromptuInterface to create the proxy wrapper for us:
// Enumerate the key-value pairs as DictinoaryEntrys foreach (DictionaryEntry dictEntry in node.Literals) { // Cast the key value to a string directly var key = (string)dictEntry.Key; // Use ImpromptuInterface to add a wrapper IDfaNode value = dictEntry.Value.ActLike<IDfaNode>(); }
We now have everything we need to create a custom
DfaWriter implementation by implementing
WriteNode, but this post is already a bit long, so we'll explore how to do that in the next post!
Summary
In this post I explored the
DfaWriter implementation in ASP.NET Core, and the two
internal classes it uses:
DfaMatcherBuilder and
DfaNode. The fact these class are internal makes it tricky to create our own implementation of the
DfaWriter. To implement it cleanly we would have to reimplement both of these types and all the classes they depend on.
Instead, I used the ImpromptuInterface library to create a wrapper proxy that implements similar methods to the object being wrapped. This uses reflection to invoke methods on the wrapped property, but allows us to work with a strongly typed interface. In the next post I'll show how to use these wrappers to create a custom
DfaWriter for customising your endpoint graphs.
|
https://andrewlock.net/creating-a-custom-dfagraphwriter-using-impromptuinterface-and-reflection/
|
CC-MAIN-2021-04
|
en
|
refinedweb
|
This page describes how to implement SQL routines -- functions and procedures -- in java. Feel free to edit. Especially please add working examples.
Table of Contents
- Functions vs. Procedures
- Creating Functions
- Creating Procedures
- The power of Java in SQL
- Are Derby Procedures *Stored* Procedures?
- Common Problems
Functions vs. Procedures
There is overlap between SQL Functions and. Starting in
Derby 10.2, a java procedure can also be invoked in a trigger.
Here's an example of invoking two built-in procedures using ij. The first, SQLJ.install_jar, loads my 'myStuff.jar' jar file into the database and the second, SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY, procedure using VALUES. That's just one of the differences between them. More comparisons are summarized in the table below:.
Examples from the Derby mail archives include:
A function without any parameters that returns an integer
A function that takes two values, adds them together and returns the result; also shows how to invoke a function in a trigger
A function that given a Date, returns the day of week
A function that converts a Timestamp to its corresponding Long value using Java
System.getProperty as a function
Here's a very simple example of how to define and use the JDK's System.getProperty() method from a Derby SQL
Note that for this to work, Derby's security policy must allow System.getProperty calls to be made to retrieve the properties in question.
Creating Procedures
The
Reference Guide provides the syntax for creating procedures.
The
Derby functional tests also include procedures.
Examples from the Derby mail archives include:
Returning java.sql.ResultSets from Java procedures(DP1 INTEGER, DP2 INTEGER) PARAMETER STYLE JAVA LANGUAGE JAVA READS SQL DATA DYNAMIC RESULT SETS 2 EXTERNAL NAME 'org.apache.derbyTesting.functionTests.util.ProcedureTest.selectRows'
Body of public static void Java method for procedure, using standard server-side JDBC. Must be in a public class.Statement ps2 = conn.prepareStatement("select * from t1 where i >= ?"); ps2.setInt(1, p2); data2[0] = ps2.executeQuery(); conn.close(); }
Client side application code to call procedure.
CallableStatement = conn.prepareCall("{ call DRS2(?, ?)}"); cs.setInt(1, p1); cs.setInt(2, p2); cs.execute(); WORK IN PROGESS
Items returned ResultSets. returned through CallableStatement is driven by the order of creation, not the order of the method's parameters.
The power of Java in SQL
The ability to write functions and procedures in Java brings the complete set of Java apis into your SQL environment as server side logic. A function or procedure may call any of the standard Java libraries, any of the standard Java extensions, or other third party libraries. Examples are:
SendEmailRoutine Sending e-mail from a database trigger with JavaMail API
please add others
or even just ideas of libraries that would be useful in Derby
Are Derby Procedures *Stored* Procedures?
Databases, pioneered by Sybase, initially provided stored procedures that were written in a enhanced SQL programming language. The enhanced SQL contained flow control, variables etc. in addition to the standard DML constructs. The procedures were declared in by a CREATE PROCEDURE statement containing the logic in the enhanced SQL. The database then compiled the procedure and stored its definition and compiled form. Thus the procedures were completely stored by the database, hence the term stored procedure.
Derby currently supports procedures written in the Java programming language, following the SQL Standard, Part 13. With these Java procedures, the implementation of the procedure, a public static Java method in a Java class, is compiled outside the database, typically archived into a jar file and presented to the database with the CREATE PROCEDURE statement. Thus the CREATE PROCEDURE statement is no an atomic "define and store" operation. The compiled Java for a procedure (or function) may be stored in the database using the standard SQL procedure SQLJ.INSTALL_JAR or may be stored outside the database in the class path of the application.
The advantage of Java procedures is that the same procedure will run on any database that supports the standard, such as Derby, IBM's DB2 and Oracle.
Common Problems
*Unrecognized* procedures
Up until at least 10.1.3, attempting to call a procedure with the wrong number of parameters causes an SQL exception: "ERROR 42Y03: 'SYSCS_UTIL.SYSCS_IMPORT_DATA' is not recognized as a function or procedure.".
SYSCS_IMPORT_DATA
The last line of data must be terminated with an end-of-line (possibly system dependant) or you will get an exception: "ERROR 38000: The exception 'SQL Exception: Read endOfFile at unexpected place on line 3.' was thrown while evaluating an expression."
The table and field names must be given in ALL UPPER CASE. Otherwise you will get "ERROR XIE0M: Table 'property' does not exist." or "ERROR XIE08: There is no column named: set_id."
If the number of columns in the data is greater than the number of columns in the insertColumns list then the extra columns are ignored. However, if the reverse is true then you get this ugly and nearly meaningless SQL exception: "ERROR 38000: The exception 'SQL Exception: Column 'COLUMN2' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'COLUMN2' is not a column in the target table.' was thrown while evaluating an expression."
|
http://wiki.apache.org/db-derby/DerbySQLroutines
|
crawl-002
|
en
|
refinedweb
|
I've wondered before what the fastest way is to pass a hash of options to a method in Ruby.. so today I benchmarked a few methods I've used in the past.
I've seen three main ways of passing an options hash to a method and extracting the options or use default values if they weren't passed in:
From what I can tell, using delete is the fastest:
require 'benchmark'
def ops_delete(ops={})
a = ops.delete(:a) || 11
b = ops.delete(:b) || 22
c = ops.delete(:c) || 33
d = ops.delete(:d) || 44
end
def ops_merge(ops={})
ops = {:a => 11, :b => 22, :c => 33, :d => 44}.merge(ops)
a = ops[:a]
b = ops[:b]
c = ops[:c]
d = ops[:d]
end
def ops_or(ops={})
a = ops[:a] || 11
b = ops[:b] || 22
c = ops[:c] || 33
d = ops[:d] || 44
end
n = 100000
puts "With no option values passed"
Benchmark.bmbm(7) do |x|
x.report("delete:") { n.times do ops_delete; end }
x.report("merge:") { n.times do ops_merge; end }
x.report("or_nil:") { n.times do ops_or; end }
end
puts
puts "With some option values passed"
Benchmark.bmbm(7) do |x|
x.report("delete:") { n.times do ops_delete(:a => 5, :c => 2); end }
x.report("merge:") { n.times do ops_merge(:a => 5, :c => 2); end }
x.report("or_nil:") { n.times do ops_or(:a => 5, :c => 2); end }
end
puts
puts "With all option values passed"
Benchmark.bmbm(7) do |x|
x.report("delete:") { n.times do ops_delete(:a => 5, :b => 1, :c => 2, :d => 4); end }
x.report("merge:") { n.times do ops_merge(:a => 5, :b => 1, :c => 2, :d => 4); end }
x.report("or_nil:") { n.times do ops_or(:a => 5, :b => 1, :c => 2, :d => 4); end }
end
Results (rehearsals omitted):
With no option values passed
user system total real
delete: 0.210000 0.000000 0.210000 ( 0.209877)
merge: 0.720000 0.000000 0.720000 ( 0.750394)
or_nil: 0.260000 0.000000 0.260000 ( 0.258416)
With some option values passed
user system total real
delete: 0.250000 0.000000 0.250000 ( 0.255536)
merge: 0.830000 0.000000 0.830000 ( 0.831358)
or_nil: 0.310000 0.000000 0.310000 ( 0.314737)
With all option values passed
user system total real
delete: 0.310000 0.000000 0.310000 ( 0.306889)
merge: 0.900000 0.000000 0.900000 ( 0.905261)
or_nil: 0.340000 0.000000 0.340000 ( 0.348061)
This was done in Ruby 1.8.4 on a 2GHz MacBook Intel Core Duo with 1GB 667 MHz DDR2 SDRAM.
Nothing new here, but thought I would share something that set me back a bit when first learning RSpec and testing controllers. If you're using a user authentication system like acts_as_authenticated, you have a method available in your controllers called "current_user" which of course returns the currently logged in user. To simulate this in a controller spec using RSpec, you can tell the controller to return a mock User object when current_user is called:
before do
controller.stub!(:current_user).and_return(mock_model(User, :to_param => "1"))
end
Of course you may have to change the :to_param value to something else, depending on what you're testing (e.g., maybe different users have different roles/permissions).
Thanks to Igal Koshevoy for the last tip I needed to get this working. Igal wrote the awesome AutomateIt open source tool for automating the setup and maintenance of servers, applications and their dependencies.
My friend Elizabeth needed to get a website up for her photography, so I said I'd see what I could do. After trying to customize Gallery (PHP), which is a really good way to go in general, I figured I should look into a quick, customized solution. I'm already familiar with the CakePHP framework (and since my host has crappy support for Ruby/Rails, I didn't want to use a Rails solution), I searched around a bit and found a good tutorial on how to set up a photo gallery with CakePHP using the Flickr API.
After about an hour I had a fully-functioning site up. The next few hours were spent tweaking the layout/design (and figuring out Internet Explorer bugs). I added some more JavaScript to the final solution that updates a caption in addition to the main photo. The results can be found at esoule.com. She's also got an online store at Etsy as well if you want to buy anything.
If you want to add a simple line graph to a Rails application but for one reason or another don't want to/can't use RMagick et al, a relatively simple way to do it is with the Open Flash Chart plugin. It includes a Ruby plugin in the zip archive called "ruby-ofc-library-pullmonkey". You just need to copy that to your Rails app's vendor/plugin directory and rename it to "open_flash_chart". Then you'll be able to make a graph like this in no time:
require 'open_flash_chart'
class AuditsController < ApplicationController
def drilldown
@audits = Audit.find_for_drilldown(params) # or find(:all), etc.
#merge the drilldown_graph action and this controller with other params (such as date range)
url = url_for(params.merge({'controller' => 'audits', 'action' => 'drilldown_graph'}))
@graph = OpenFlashChart.swf_object(250,150,url)
end
def drilldown_graph
@audits = Audit.find_for_drilldown(params)
ofc = OpenFlashChart.new
ofc.title("My Title", "{font-size: 16px;}")
ofc.set_data(@audits.map{|a| a.percent.to_f})
ofc.line_hollow(2,3,'#C06600', 'Audit Score', 12)
ofc.set_x_labels(@audits.map{|a| a.audit_date.strftime('%m/%d')})
ofc.set_x_label_style(9, '0x000000', 0, 3)
ofc.x_axis_color('0x999999','0xe3e3e3')
ofc.set_y_max(100)
ofc.set_y_min(50)
ofc.set_bg_color('#ffffff')
ofc.set_y_label_steps(5)
ofc.set_y_label_style(1, "#000000")
ofc.y_axis_color('0x999999','0xe3e3e3')
render :text => ofc.render
end
end
# View (drilldown.rhtml)
<%= @graph %>
One thing that annoys me a lot on the web is the extremely inefficient use of space on many (if not most) web pages. Why does the header always take up a third of the page? Or take a look at this:
That's a screen shot of my fantasy baseball league's live scoring page on a 21" monitor (1280x1040 resolution) where I've set the browser window size to 1024x768. The three things I really want to see on that page are: (1) The score of this week's match-up (5-4), (2) How each player is doing today (the section below the score) and (3) how this week's stats break down by category (which isn't even close to being on the page.. it's way below).
So the problem with this page is that we have about 9.5 inches of screen height to work with, and the score takes up almost 2 inches (it could easily take up 1/2 an inch), and the rest of the junk above the score takes up about 5 inches. The ad banner at the top is huge, but hey, it's supposed to generate money for the site, so I can accept that (and by accept I mean I block it with adblock of course, but it still takes up the space). The biggest problem is that the section between the top banner ad and the scoreboard takes up about 3.5 inches, which is more than a third of the page, yet conveys almost nothing. I'm quite aware that I'm on the Big Sky Baseball 2007 (listed twice for some reason) page, so maybe they could make that text a little smaller? There's also at least an inch of wasted white space in the "GameCenter" section. The links below "GameCenter" could be next to it instead of below for one thing.
Of course, this is only one of many web sites with similar problems, although this is about as bad as it gets.
I'm by no means web design expert, but I'm pretty sure I'm right about this. I even get annoyed by the space taken up by the header on my own website, UrbanDrinks.com, and it's only about an inch or so.
In my job at Sun as a quality engineer I have made several web-based applications to help analyze and report our manufacturing quality data. One common situation is where we have a number of units that tested during a time period and a number of them failed, and we want to know if the fail rate was worse than a threshold fail rate.
For example, we might have a threshold fail rate of 10% (in reality the thresholds we use are much, much lower, but this is easier for demonstration purposes) and tested 100 units, 12 of which failed. If we treat these 100 units as a sample out of a theoretical infinite population, are we at least 95% confident that population's fail rate is greater than or equal to 10%? To find out, we can use the binomial distribution class from the rubystats Ruby library (I ported this from the PHPMath project. It's available at RubyForge or you can install it with "gem install rubystats" on a system that already has RubyGems installed).
Once you have the rubystats gem installed, you can test our scenario rather easily. Below is a code sample that tests 10 scenarios against the 10% threshold (called bad_fail_rate in the code). This consists of finding the cumulative probability of observing f or more failures if the theoretical infinite population's true fail rate is 0.10. We use the cdf method (cumulative density function) to calculate the probability of observing (f-1) or fewer failures, then subtract that value from 1. If it's less than 0.05 (the alpha value for 95% confidence, i.e. 1 - 0.95 = 0.05), then the fail rate is significant.
Which outputs:
As you can see, the first scenario where 12 out of 100 failed is not statistically significant at 95% confidence.
We've recently added quite a few places to the UrbanDrinks.com (a Portland happy hour website and side project of mine) database, thanks in part to the excellent Portland Happy Hour Guidebook, and now have over 180 different places in Portland with happy hours! That's a lot considering it doesn't count any of the surrounding metropolitan area. Downtown Portland alone has 52 happy hours today. Wow. When I started this project I had no idea how many happy hours in Portland there really were.
So despite the gray, drizzly days, Portland has got to be the happiest place in the country!
I'm really glad to see that Sun is supporting the JRuby project now, and seems to be supporting scripting languages in general. I feel like now I don't have to give excuses at work. I've been developing web applications used Sun-wide internally for over a year and a half now. I work as a quality engineer in Operations, so I'm not really surrounded by Java developers, but I've still received the occasional question asking why I didn't develop in Java (or Perl, another favorite here). The truth is that I just don't know much Java, and some attempts to learn J2EE a couple of years ago frustrated me a bit. Also, I already knew some PHP, so I developed in PHP at Sun for a couple of years until I got good at it. Then I found Rails and tried it out. I immediately got it installed on my server and started developing in Rails from then on.
I like Rails because it provides that perfect mix of coding ease and structure. The Ruby language is extremely flexible, easy to understand, and truly object-oriented. PHP provides much of this, but the language is much more verbose. PHP seems to be a gateway language for many new developers (myself included, aside from some C/C++ in college), and not surprisingly, there are a lot of bad PHP applications out there (I am the guilty author of some). Ruby, on the other hand, is being learned for the most part by new Rails developers. The Rails framework definitely helps new developers create well-organized applications from the beginning. Basically, if PHP would have become popular because of a framework, we wouldn't have as much bad PHP code out there. I really like PHP still, but I like the Ruby/Rails stack better. When I do write PHP code, I try to structure it as well as possible, usually with a variety of PEAR libraries and using CakePHP as a framework (CakePHP follows a lot of Rails-like conventions, and is a very good framework). I wish the PHP books I read when I first started out used a good framework to teach with. However, if they had, we might not have needed this "Rails Revolution".
With JRuby, I hope to see Ruby get faster, and maybe I'll learn Java so I can write fast, compiled portions of my future Rails apps. Long live Java and Ruby!
This is one of those events in life that makes you say "wow, what are the odds of that happening?".
Shortly after I graduated high school, I moved to Phoenix, Arizona to start college at DeVry in July 1997. I was the first of four roommates to arrive, and since the apartment was in my name, I was the one going through the paperwork process. One of my new roommates, whom I hadn't met yet, was Clint Carlson from Alaska, who was also going to be attending DeVry and was scheduled to arrive that same day. I was in the apartment management office waiting for my turn to sign some papers when I overheard the guy in front of me say he was Clint Carlson. So I of course introduced myself and asked him if he was from Alaska (to make sure it wasn't some other random Clint Carlson), and he replied "yes".
"So I guess we're going to be roommates," I responded.
"Um, no, my roommate is so-and-so."
"Uh.. you're Clint Carlson from Alaska, right? Are you going to DeVry?"
"Yeah, start in a few days."
"Um.. I think you're my roommate then. I'm rooming with Clint Carlson from Alaska who's going to start DeVry next week."
"Well, my roommate is so-and-so, so maybe you got the wrong guy.."
Yeah right. So I asked the apartment manager if there was more than one Clint Carlson moving today.
"Yep, I guess there are."
"Two Clint Carlsons from Alaska, moving into the same apartment complex in Phoenix, Arizona on the same day and both attending DeVry? AND I happen to be in the apartment management office when the wrong one is here signing papers?"
"Yep, two Clints from Alaska moving in today."
"Wow, what are the odds of that?"
So there you have it. That's probably the strangest coincidence that's happened to me. I'd like to hear some other stories.
p.s. I don't believe in any voodoo or fate stuff, so my statistics-oriented mind chalks this up to random chance alone.
I'm excited to say that we've finally launched the beta version of UrbanDrinks.com, a happy-hour website focused on Portland, Oregon.
This has been a side-project I've been working on since early July using Ruby on Rails (in fact, it's what my RubyQuiz post was all about). I've learned a lot so far about the Google Maps API and designing a database to handle all of the time ranges and associated happy hours, as well as just polishing (er... maybe "sanding" is a better term) my Ruby skills. I've also had the pleasure of pulling my hair out dealing with Internet Explorer CSS bugs.
I have to thank Guilhem Vellut for his wonderful Google Maps Rails Plugin. This plugin made the Google Maps portion of the project a thousand times easier. Of course, I should also thank the people who responded to the DayRange RubyQuiz and the Rails and Ruby developers in general. They really do make web development fun.
The site is still under development, so there could be some bugs. Definitely let us know if you find any or if you have any comments or suggestions. We also have an UrbanDrinks blog where we'll keep you posted on site updates and our opinions on various things related to happy hours. Enjoy! "Ruby way" to generate this sentence-like string.
Here are some example lists of days and their expected returned strings:.
If you run a company with a separate computer for each employee, you should really stop doing that and switch over to running a company with a Sun Ray for every employee. Yeah, this is a "plug" for Sun, but I'm serious about this. Sun recently set me up with a Sun Ray at home (a Sun Ray 170 to be exact), and I'm very impressed. We've been using Sun Rays at work for a few years now, but seeing them work so well from home is whole other level of technological coolness. Here's a short list of benefits:
Heck, if I had a family, I'd set up a small Sun Ray network at home. Of course, I'd also make my kids use Solaris or Linux too...
Today's Page Hits: 65
|
http://blogs.sun.com/bdonovan/
|
crawl-002
|
en
|
refinedweb
|
Frank Kieviet
This blog is continued on
A few months ago I decided to look at a different place to host my blog. I compared Google's blogger and wordpress, and finally decided to go with the former.
The full URL is: .
Posted at
10:00AM Mar 17, 2009
by Frank Kieviet in Sun |
Permalink:
JavaOne!
Posted at
10:46AM May 21, 2008
by Frank Kieviet in Sun |
Permalink:
Server side Internationalization made easy
Last year I wrote a blog entry on my
gripes with Internationalization in Java for server side
components. Sometime in January I built a few utilities for JMSJCA that makes
internationalization for server side components a lot easier. To make
it available to a larger audience, I added the utilities to the tools
collection on.
What do these utilities do?
Generating resource bundles automatically
The whole point was that when writing Java code, I would like to
keep internationalizable texts close to my Java code. Rather than in
resource bundles, I prefer to keep texts in my Java code so that:
- While coding, you don't need to keep switching between a Java file and a resource bundle.
- No more missing messages because of typos in error identifiers; no more obsolete messages in resource bundles
- You can easily review code to make sure that error messages make sense in the context in which they appear, and you can easily check that the arguments for the error messages indeed match.
In stead of writing code like this:
sLog.log(Level.WARNING, "e_no_match_w_pattern", new Object[] { dir, pattern, ex}, ex);
Prefer code like this:
sLog.log(Level.WARNING, sLoc.t("E131: Could not find files with pattern {1} in directory {0}: {2}"
, dir, pattern, ex), ex);
Here's a complete example:
public class X {
Logger sLog = Logger.getLogger(X.class.getName());
Localizer sLoc = Localizer.get();
public void test() {
sLog.log(Level.WARNING, sLoc.t("E131: Could not find files with pattern {1} in directory {0}: {2}"
, dir, pattern, ex), ex);
}
}
Hulp has an Ant task that goes over the generated classes and extracts these phrases and writes them to a resource bundle. E.g. the above code results in this resource bundle:
# DO NOT EDIT
# THIS FILE IS GENERATED AUTOMATICALLY FROM JAVA SOURCES/CLASSES
# net.java.hulp.i18ntask.test.TaskTest.X
TEST-E131 = Could not find files with pattern {1} in directory {0}\: {2}
To use the Ant task, add something like this to your Ant script,
typically between <javac>
and <jar>:
<taskdef name="i18n" classname="net.java.hulp.i18n.buildtools.I18NTask" classpath="lib/net.java.hulp.i18ntask.jar"/>
<i18n dir="${build.dir}/classes" file="src/net/java/hulp/i18ntest/msgs.properties" prefix="TEST" />
How does the Ant task know what strings should be copied into the
resource bundle? It uses a regular expression for that. By default it
looks for strings that start with a single alpha character, followed by
three digits followed by a colon, which is this regular expression: [A-Z]\d\d\d: .*.
Getting messages out of resource bundles
With the full English message in the Java code, how is the proper
localized message obtained? In the code above, this is done in this
statement:
sLoc.t("E131: Could not find files with pattern {1} in directory {0}: {2}", dir, pattern,.:
public static class Localizer extends net.java.hulp.i18n.LocalizationSupport {
public Localizer() {
super("TEST");
}
private static final Localizer s = new Localizer();
public static Localizer get() {
return s;
}
}
The class name should be Localizer so that the Ant task
can be extended later to automatically detect which packages use which
resource bundles.
The class name should be Localizer so that the Ant task
can be extended later to automatically detect which packages use which
resource bundles.
Using the compiler to enforce internationalized code
It would be nice if the compiler could force internationalized
messages to be used. To do that, Hulp includes a wrapper around java.util.logging.Logger that
only takes objects of class LocalizedString
instead of just String.
The class LocalizedString
is a simple wrapper around String.
The Localizer class
produces these strings. By avoiding using java.util.logging.Logger
directly, and instead using net.java.hulp.i18n.Logger
the compiler will force you to use internationalized texts. Here's a
full example:
public class X {
net.java.hulp.i18n.Logger sLog = Logger.getLogger(X.class);
Localizer sLoc = Localizer.get();
public void test() {
sLog.warn(sLoc.x("E131: Could not find files with pattern {1} in directory {0}: {2}"
, dir, pattern, ex), ex);
}
}
Logging is one area that requires internationalization, another is
exceptions. Unfortunately there's no general approach to force
internationalized messages in exceptions. You can only do that if you
define your own exception class that takes the LocalizedString in the
constructor, or define a separate exception factory that takes this
string class in the factory method.
Download
Go to
to download these utilities. The jars (the Ant
task and utilities)
are also hosted on the Maven
repository on java.net.
Posted at
04:32PM Oct 07, 2007
by Frank Kieviet in Sun |
Permalink:
Using Nested Diagnostics Contexts in Glassfish_13<<
Posted at
11:49AM Sep 30, 2007
by Frank Kieviet in Sun |
Permalink:
JavaOne)
Posted at
10:01AM May 15, 2007
by Frank Kieviet in Sun |
Permalink:
JavaOne / memory leaks revisited...
Memory."
Posted at
09:56PM May 02, 2007
by Frank Kieviet in Sun |
Permalink:
Using Resource Adapters outside of EE containers at
08:03PM Feb 04, 2007
by Frank Kieviet in Sun |
Permalink:
JMSJCA, a feature rich JMS Resource Adapter, is now a java.net project.
Posted at
10:22AM Jan 21, 2007
by Frank Kieviet in Sun |
Permalink:
Logless transactions.
Posted at
11:58AM Jan 15, 2007
by Frank Kieviet in Sun |
Permalink:
Short note: Running Java CAPS on Java SE 6
Today Java SE 6 was
released. It comes with many new features and cool tools. One of them
being jmap as described in a previous log on permgen
exceptions. The Integration Server is not officially supported on
SE 6 yet. However, if you want to run the Java CAPS integration server
on SE 6, this is what you can do:
- Install JDK 6 somewhere, e.g. c:\java
- Install the IS somewhere, e.g. c:\logicalhost
- Rename c:\logicalhost\jre to c:\logicalhost\jre.old
- Copy c:\java\jre1.6.0 to c:\logicalhost\jre
- Copy c:\java\jdk1.6.0\lib\tools.jar to c:\logicalhost\jre\lib
- Copy c:\logicalhost\jre\bin\javaw.exe to c:\logicalhost\jre\bin\is_domain1.exe
- Copy c:\logicalhost\jre\bin\javaw.exe to c:\logicalhost\jre\bin\ isprocmgr_domain1.exe
- Edit c:\logicalhost\is\domains\domain1\config\domain.xml and comment out these lines:
<!--
<jvm-options>-Dcom.sun.org.apache.xalan.internal.xsltc.dom.XSLTCDTMManager=com.sun.org.apache.xalan.internal.xsltc.dom.XSLTCDTMManager</jvm-options>
<jvm-options>-Dorg.xml.sax.driver=com.sun.org.apache.xerces.internal.parsers.SAXParser</jvm-options>
<jvm-options>-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl</jvm-options>
<jvm-options>-Dcom.sun.org.apache.xerces.internal.xni.parser.XMLParserConfiguration=com.sun.org.apache.xerces.internal.parsers.XIncludeParserConfiguration</jvm-options>
<jvm-options>-Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl</jvm-options>
<jvm-options>-Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl</jvm-options>
<jvm-options>-Djavax.xml.soap.MessageFactory=com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl</jvm-options>
<jvm-options>-Djavax.xml.soap.SOAPFactory=com.sun.xml.messaging.saaj.soap.ver1_1.SOAPFactory1_1Impl</jvm-options>
<jvm-options>-Djavax.xml.soap.SOAPConnectionFactory=com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnectionFactory</jvm-options>
-->
i.e. add <!-- before and add --> after these lines.
Also comment out this line:
<!-- <jvm-options>-server</jvm-options>-->
After these changes you can run the Integration Server with Jave SE 6. These are not “official” recommendations (as mentioned, there’s no support for SE 6 just yet); also the lines commented out are optimizations, that need to be re-established for SE 6 tet, so don’t do any performance comparisons just yet.
Posted at
10:41PM Dec 11, 2006
by Frank Kieviet in Sun |
Permalink:
Moving out of people management at
03:59PM Dec 03, 2006
by Frank Kieviet in Musings |
Permalink:
Using java.util.logging in BEA Weblogic
Some.
Posted at
02:16PM Nov 16, 2006
by Frank Kieviet in Sun |
Permalink:
More on... How to fix the dreaded "java.lang.OutOfMemoryError: PermGen space" exception (classloader leaks).
Posted at
10:29PM Nov 15, 2006
by Frank Kieviet in Sun |
Permalink:
How to fix the dreaded "java.lang.OutOfMemoryError: PermGen space" exception (classloader leaks)_54<<_55<<_56<<
Clicking on the classloader link brings up the following screen:
Scrolling down, I see Reference Chains from Rootset / Exclude weak refs . Clicking on this link invokes the code that I modified; the following screen comes up:
.
Posted at
04:10PM Oct 19, 2006
by Frank Kieviet in Sun |
Permalink:
Classloader leaks: the dreaded "java.lang.OutOfMemoryError: PermGen space" exception
Did"); } }Try to redeploy this little sample a number of times. I bet this will eventually fail with the dreaded java.lang.OutOfMemoryError: PermGen space error. If you like to understand what's happening, read on._63<<
-_64<<_65<<_66<<.
Posted at
11:40AM Oct 16, 2006
by Frank Kieviet in Sun |
Permalink:
Transactions, disks, and performance at
10:30PM Oct 11, 2006
by Frank Kieviet in Sun |
Permalink:
A free course in Java EE (link)
I found this note in my mail::
If you have anybody who wants to learn Java EE programing through hands-on style using NetBeans, please let them about this course.
Posted at
12:24PM Sep 18, 2006
by Frank Kieviet in Sun |
Permalink:
Funny videos from SunWho knew... Sun makes pretty funny commercials. See here: Sun videos. While you're there, also take a look at Project LookingGlas... impressive stuff!
Posted at
02:05PM Sep 14, 2006
by Frank Kieviet in Sun |
Permalink:
Testing connection failures in resource adapters
In a previous blog (see J2EE JCA Resource Adapters: Poisonous pools) I talked about the difficulty to detect faulty connections to the external system (EIS) that the Resource Adapter is interfacing with. A common cause of connection failures is simply connection loss. In my previous blog I detailed the problems of detecting connection loss in the RA and presented a number of ways to address this problem.
What I didn't discuss is how you can build unit tests so that you
can easily test connection failures and connection failure recovery.
That is the topic of this blog.
What is it that I will be looking at? Say that you have a resource
adapter that connects to an external system (EIS) using one or more
TCP/IP connections. The failure I want to test is that of a simple
connection drop. This can happen if the EIS is rebooted, crashes, or
simply because the network temporarily fails (e.g. someone stumbles
over a network cable).
An automated way to induce failures
How would you manually test this type of failure? You could simply
kill the EIS, or unplug the network connection. Simple and effective,
but very manual. What I prefer is an automated way so that I
can include test failures in an automated unit test suite. Here's
a way to do that:
use a port-forwarder proxy. A port forwarder proxy is a process that
listens on a particular port. Any time a connection comes in on that
port, it will create a new connection to a specified server and port.
Bytes coming in from the client are sent to the server unmodified.
Likewise, bytes coming in from the server are sent to the client
unmodified. The
client is the RA in this case; the server is the EIS. Hence, the port
-forwarder proxy sits between the Resource Adapter and the EIS.
A failure can be induced by instructing the port-forwarder proxy to
drop all the connections. To simulate a transient failure, the
port-forwarder proxy should then again accept connections and forward
them to the EIS.
Here is an example of how this port-forwarder proxy can be used in a
JUnit test. Let's say that I'm testing a JMS resource adapter. Let's
say that I'm testing the RA in an application server: I have an MDB
deployed in the application server that reads JMS messages from one
queue (e.g. Queue1) and forwards them to a different queue (e.g.
Queue2). The test would look something like this:
- start the port-forwarder proxy; specify the server name and port number that the EIS is listening on
- get the port number that proxy is listening on
- generate a connection URL that the RA will use to connect to the EIS; the new connection URL will have the proxy's server name and port number rather than the server name and port number of the EIS
- update the EAR file with the new connection URL
- deploy the EAR file
- send 1000 messages to Queue1
- read these 1000 message from Queue2
- verify that the port-forwarder has received connections; then tell the port-forwarder to kill all active connections
- send another batch of 1000 messages to Queue1
- read this batch of 1000 messages from Queue2
- undeploy the EAR file
As you can see I'm assuming in this example that you are using an
embedded resource adapter, i.e. one that is embedded in the EAR file.
Ofcourse you can also make this work using global resource adapters;
you just need a way to automatically configure the URL in the global
resource adapter.
A port forwarder in Java
My first Java program I ever wrote was a port-forwarder proxy
(Interactive Spy). I'm not sure when it was, but I do remember that
people just started to use JDK 1.3. In that version of the JDK there
was only blocking IO available. Based on that restriction a way to
write a port-forwarder proxy is to listen on a port and for each
incoming connection create two threads: one thread exclusively reads
from the client and sends the bytes to the server; the other thread
reads from the server and sends the bytes to the client. This was not a
very scalable or elegant solution. However, I did use this solution
successfully for a number of tests in the JMS test suite at SeeBeyond
for the JMS Intelligent Queue Manager in Java CAPS (better known to
engineers as STCMS). However, when I was developing the connection
failure tests for the JMSJCA Resource Adapter for JMS, I ran into these
scalability issues, and I saw test failures due to problems in the test
setup rather than to bugs in the application server, JMSJCA or STCMS.
A better approach is to make use of the non-blocking NIO
capabilities in JDK 1.4. For me this was the opportunity to explore the
capabilities of NIO. The result is a relatively small class that fully
stands on its own; I pasted the source code of the resulting class
below. The usual restrictions apply: this code is provided "as-is"
without warranty of any kind; use at your own risk, etc. I've omitted
the unit test for this class.
This is how you use it: instantiate a TCPProxyNIO passing it the
server name and port number of the EIS. The proxy will find a port to
listen on in the range of 50000. Use getPort() to find out what the
port number is. The proxy now listens on that port and is ready to
accept connections. Use killAllConnections()
to kill all connections. Make sure to destroy the proxy after use:]
*/
package com.stc.jmsjca.test.core;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A proxy server that can be used in JUnit tests to induce connection
* failures, to assure that connections are made, etc. The proxy server is
* setup with a target server and port; it will listen on a port that it
* chooses itself and delegates all data coming in to the server, and vice
* versa.
*
* Implementation: each incoming connection (client connection) maps into
* a Conduit; this holds both ends of the line, i.e. the client end
* and the server end.
*
* Everything is based on non-blocking IO (NIO). The proxy creates one
* extra thread to handle the NIO events.
*
* @author fkieviet
*/
public class TcpProxyNIO implements Runnable {
private static Logger sLog = Logger.getLogger(TcpProxyNIO.class.getName());
private String mRelayServer;
private int mRelayPort;
private int mNPassThroughsCreated;
private Receptor mReceptor;
private Map mChannelToPipes = new IdentityHashMap();
private Selector selector;
private int mCmd;
private Semaphore mAck = new Semaphore(0);
private Object mCmdSync = new Object();
private Exception mStartupFailure;
private Exception mUnexpectedThreadFailure;
private boolean mStopped;
private static final int NONE = 0;
private static final int STOP = 1;
private static final int KILLALL = 2;
private static final int KILLLAST = 3;
private static int BUFFER_SIZE = 16384;
/**
* Constructor
*
* @param relayServer
* @param port
* @throws Exception
*/
public TcpProxyNIO(String relayServer, int port) throws Exception {
mRelayServer = relayServer;
mRelayPort = port;
Receptor r = selectPort();
mReceptor = r;
new Thread(this, "TCPProxy on " + mReceptor.port).start();
mAck.acquire();
if (mStartupFailure != null) {
throw mStartupFailure;
}
}
/**
* Utility class to hold data that describes the proxy server
* listening socket
*/
private class Receptor {
public int port;
public ServerSocket serverSocket;
public ServerSocketChannel serverSocketChannel;
public Receptor(int port) {
this.port = port;
}
public void bind() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocket = serverSocketChannel.socket();
InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
serverSocket.bind(inetSocketAddress);
}
public void close() {
if (serverSocketChannel != null) {
try {
serverSocketChannel.close();
} catch (Exception ignore) {
}
serverSocket = null;
}
}
}
/**
* The client or server connection
*/
private class PipeEnd {
public SocketChannel channel;
public ByteBuffer buf;
public Conduit conduit;
public PipeEnd other;
public SelectionKey key;
public String name;
public PipeEnd(String name) {
buf = ByteBuffer.allocateDirect(BUFFER_SIZE);
buf.clear();
buf.flip();
this.name = "{" + name + "}";
}
public String toString() {
StringBuffer ret = new StringBuffer();
ret.append(name);
if (key != null) {
ret.append("; key: ");
if ((key.interestOps() & SelectionKey.OP_READ) != 0) {
ret.append("-READ-");
}
if ((key.interestOps() & SelectionKey.OP_WRITE) != 0) {
ret.append("-WRITE-");
}
if ((key.interestOps() & SelectionKey.OP_CONNECT) != 0) {
ret.append("-CONNECT-");
}
}
return ret.toString();
}
public void setChannel(SocketChannel channel2) throws IOException {
this.channel = channel2;
mChannelToPipes.put(channel, this);
channel.configureBlocking(false);
}
public void close() throws IOException {
mChannelToPipes.remove(channel);
try {
channel.close();
} catch (IOException e) {
// ignore
}
channel = null;
if (key != null) {
key.cancel();
key = null;
}
}
public void listenForRead(boolean on) {
if (on) {
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
} else {
key.interestOps(key.interestOps() &~ SelectionKey.OP_READ);
}
}
public void listenForWrite(boolean on) {
if (on) {
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
} else {
key.interestOps(key.interestOps() &~ SelectionKey.OP_WRITE);
}
}
}
/**
* Represents one link from the client to the server. It is an association
* of the two ends of the link.
*/
private class Conduit {
public PipeEnd client;
public PipeEnd server;
public int id;
public Conduit() {
client = new PipeEnd("CLIENT");
client.conduit = this;
server = new PipeEnd("SERVER");
server.conduit = this;
client.other = server;
server.other = client;
id = mNPassThroughsCreated++;
}
}
/**
* Finds a port to listen on
*
* @return a newly initialized receptor
* @throws Exception on any failure
*/
private Receptor selectPort() throws Exception {
Receptor ret;
// Find a port to listen on; try up to 100 port numbers
Random random = new Random();
for (int i = 0; i < 100; i++) {
int port = 50000 + random.nextInt(1000);
try {
ret = new Receptor(port);
ret.bind();
return ret;
} catch (IOException ignore) {
// Ignore
}
}
throw new Exception("Could not bind port");
}
/**
* The main event loop
*/
public void run() {
// ===== STARTUP ==========
// The main thread will wait until the server is actually listening and ready
// to process incoming connections. Failures during startup should be
// propagated back to the calling thread.
try {
selector = Selector.open();
// Acceptor
mReceptor.serverSocketChannel.configureBlocking(false);
mReceptor.serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (Exception e) {
synchronized (mCmdSync) {
mStartupFailure = e;
}
}
// ===== STARTUP COMPLETE ==========
// Tha main thread is waiting on the ack lock; notify the main thread.
// Startup errors are communicated through the mStartupFailure variable.
mAck.release();
if (mStartupFailure != null) {
return;
}
// ===== RUN: event loop ==========
// The proxy thread spends its life in this event handling loop in which
// it deals with requests from the main thread and from notifications from
// NIO.
try {
loop: for (;;) {
int nEvents = selector.select();
// ===== COMMANDS ==========
// Process requests from the main thread. The communication mechanism
// is simple: the command is communicated through a variable; the main
// thread waits until the mAck lock is set.
switch (getCmd()) {
case STOP: {
ack();
break loop;
}
case KILLALL: {
PipeEnd[] pipes = toPipeArray();
for (int i = 0; i < pipes.length; i++) {
pipes[i].close();
}
ack();
continue;
}
case KILLLAST: {
PipeEnd[] pipes = toPipeArray();
Conduit last = pipes.length > 0 ? pipes[0].conduit : null;
if (last != null) {
for (int i = 0; i < pipes.length; i++) {
if (pipes[i].conduit.id > last.id) {
last = pipes[i].conduit;
}
}
last.client.close();
last.server.close();
}
ack();
continue;
}
}
//===== NIO Event handling ==========
if (nEvents == 0) {
continue;
}
Set keySet = selector.selectedKeys();
for (Iterator iter = keySet.iterator(); iter.hasNext();) {
SelectionKey key = (SelectionKey) iter.next();
iter.remove();
//===== ACCEPT ==========
// A client connection has come in. Perform an async connect to
// the server. The remainder of the connect is going to be done in
// the CONNECT event handling.
if (key.isValid() && key.isAcceptable()) {
sLog.fine(">Incoming connection");
try {
Conduit pt = new Conduit();
ServerSocketChannel ss = (ServerSocketChannel) key.channel();
// Accept
pt.client.setChannel(ss.accept());
// Do asynchronous connect to relay server
pt.server.setChannel(SocketChannel.open());
pt.server.key = pt.server.channel.register(
selector, SelectionKey.OP_CONNECT);
pt.server.channel.connect(new InetSocketAddress(
mRelayServer, mRelayPort));
} catch (IOException e) {
System.err.println(">Unable to accept channel");
e.printStackTrace();
// selectionKey.cancel();
}
}
//===== CONNECT ==========
// Event that is generated when the connection to the server has
// completed. Here we need to initialize both pipe-ends. Both ends
// need to start reading. If the connection had not succeeded, the
// client needs to be closed immediately.
if (key != null && key.isValid() && key.isConnectable()) {
SocketChannel c = (SocketChannel) key.channel();
PipeEnd p = (PipeEnd) mChannelToPipes.get(c); // SERVER-SIDE
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">CONNECT event on " + p + " -- other: " + p.other);
}
boolean success;
try {
success = c.finishConnect();
} catch (RuntimeException e) {
success = false;
if (sLog.isLoggable(Level.FINE)) {
sLog.log(Level.FINE, "Connect failed: " + e, e);
}
}
if (!success) {
// Connection failure
p.close();
p.other.close();
// Unregister the channel with this selector
key.cancel();
key = null;
} else {
// Connection was established successfully
// Both need to be in readmode; note that the key for
// "other" has not been created yet
p.other.key = p.other.channel.register(selector, SelectionKey.OP_READ);
p.key.interestOps(SelectionKey.OP_READ);
}
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">END CONNECT event on " + p + " -- other: " + p.other);
}
}
//===== READ ==========
// Data was received. The data needs to be written to the other
// end. Note that data from client to server is processed one chunk
// at a time, i.e. a chunk of data is read from the client; then
// no new data is read from the client until the complete chunk
// is written to to the server. This is why the interest-fields
// in the key are toggled back and forth. Ofcourse the same holds
// true for data from the server to the client.
if (key != null && key.isValid() && key.isReadable()) {
PipeEnd p = (PipeEnd) mChannelToPipes.get(key.channel());
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">READ event on " + p + " -- other: " + p.other);
}
// Read data
p.buf.clear();
int n;
try {
n = p.channel.read(p.buf);
} catch (IOException e) {
n = -1;
}
if (n >= 0) {
// Write to other end
p.buf.flip();
int nw = p.other.channel.write(p.buf);
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">Read " + n + " from " + p.name + "; wrote " + nw);
}
p.other.listenForWrite(true);
p.listenForRead(false);
} else {
// Disconnected
if (sLog.isLoggable(Level.FINE)) {
sLog.fine("Disconnected");
}
p.close();
key = null;
if (sLog.isLoggable(Level.FINE)) {
sLog.fine("Now present: " + mChannelToPipes.size());
}
p.other.close();
// Stop reading from other side
if (p.other.channel != null) {
p.other.listenForRead(false);
p.other.listenForWrite(true);
}
}
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">END READ event on " + p + " -- other: " + p.other);
}
}
//===== WRITE ==========
// Data was sent. As for READ, data is processed in chunks which
// is why the interest READ and WRITE bits are flipped.
// In the case a connection failure is detected, there still may be
// data in the READ buffer that was not read yet. Example, the
// client sends a LOGOFF message to the server, the server then sends
// back a BYE message back to the client; depending on when the
// write failure event comes in, the BYE message may still be in
// the buffer and must be read and sent to the client before the
// client connection is closed.
if (key != null && key.isValid() && key.isWritable()) {
PipeEnd p = (PipeEnd) mChannelToPipes.get(key.channel());
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">WRITE event on " + p + " -- other: " + p.other);
}
// More to write?
if (p.other.buf.hasRemaining()) {
int n = p.channel.write(p.other.buf);
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">Write some more to " + p.name + ": " + n);
}
} else {
if (p.other.channel != null) {
// Read from input again
p.other.buf.clear();
p.other.buf.flip();
p.other.listenForRead(true);
p.listenForWrite(false);
} else {
p.close();
key = null;
if (sLog.isLoggable(Level.FINE)) {
sLog.fine("Now present: " + mChannelToPipes.size());
}
}
}
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">END WRITE event on " + p + " -- other: " + p.other);
}
}
}
}
} catch (Exception e) {
sLog.log(Level.SEVERE, "Proxy main loop error: " + e, e);
e.printStackTrace();
synchronized (mCmdSync) {
mUnexpectedThreadFailure = e;
}
}
// ===== CLEANUP =====
// The main event loop has exited; close all connections
try {
selector.close();
PipeEnd[] pipes = toPipeArray();
for (int i = 0; i < pipes.length; i++) {
pipes[i].close();
}
mReceptor.close();
} catch (IOException e) {
sLog.log(Level.SEVERE, "Cleanup error: " + e, e);
e.printStackTrace();
}
}
private PipeEnd[] toPipeArray() {
return (PipeEnd[]) mChannelToPipes.values().toArray(
new PipeEnd[mChannelToPipes.size()]);
}
private int getCmd() {
synchronized (mCmdSync) {
return mCmd;
}
}
private void ack() {
setCmd(NONE);
mAck.release();
}
private void setCmd(int cmd) {
synchronized (mCmdSync) {
mCmd = cmd;
}
}
private void request(int cmd) {
setCmd(cmd);
selector.wakeup();
try {
mAck.acquire();
} catch (InterruptedException e) {
// ignore
}
}
/**
* Closes the proxy
*/
public void close() {
if (mStopped) {
return;
}
mStopped = true;
synchronized (mCmdSync) {
if (mUnexpectedThreadFailure != null) {
throw new RuntimeException("Unexpected thread exit: " + mUnexpectedThreadFailure, mUnexpectedThreadFailure);
}
}
request(STOP);
}
/**
* Restarts after close
*
* @throws Exception
*/
public void restart() throws Exception {
mChannelToPipes = new IdentityHashMap();
mAck = new Semaphore(0);
mStartupFailure = null;
mUnexpectedThreadFailure = null;
mReceptor.bind();
new Thread(this, "TCPProxy on " + mReceptor.port).start();
mStopped = false;
mAck.acquire();
if (mStartupFailure != null) {
throw mStartupFailure;
}
}
/**
* Returns the port number this proxy listens on
*
* @return port number
*/
public int getPort() {
return mReceptor.port;
}
/**
* Kills all connections; data may be lost
*/
public void killAllConnections() {
request(KILLALL);
}
/**
* Kills the last created connection; data may be lost
*/
public void killLastConnection() {
request(KILLLAST);
}
/**
* Closes the proxy
*
* @param proxy
*/
public void safeClose(TcpProxyNIO proxy) {
if (proxy != null) {
proxy.close();
}
}
}
Other uses of the port-forwarding proxy
What else can you do with this port-forwarding proxy? First of all,
its use is not limited to outbound connections: ofcourse you can also
use it to test connection failures on inbound connections. Next,
you can also use it to make sure that connections are infact being made
the way that you expected. For example, the CAPS JMS server can use
both SSL and non SSL connections. I added a few tests to our internal
test suite to test this capability from JMSJCA. Here, just to make sure
that the test itself works as expected, I'm using the proxy to find out
if the URL was indeed modified and that the connections are indeed
going to the JMS server's SSL port. Similary, you can also use the
proxy to count the number connections being made. E.g. if you want to
test that connection pooling indeed works, you can use this proxy and
assert that the number of connections created does not exceed the
number of connections in the pool.
Missing components
In the example I mentioned updating the EAR file and automatically
deploying the EAR file to the application server. I've created tools
for those too so that you can do those things programmatically as well.
Drop me a line if you're interested and I'll blog about those too.
Posted at
03:59PM Sep 10, 2006
by Frank Kieviet in Sun |
Permalink:
SeeBeyond was acquired by Sun a year ago. What changed.
Posted at
12:49PM Aug 27, 2006
by Frank Kieviet in Musings |
Permalink:
.
Posted at
10:56PM Aug 26, 2006
by Frank Kieviet in Sun |
Permalink:
JMS request/reply from an EJB
Sometimes.
Posted at
04:35PM Aug 13, 2006
by Frank Kieviet in Sun |
Permalink:
J2EE JCA Resource Adapters: Poisonous pools
Introduction
Posted at
10:33PM Jul 31, 2006
by Frank Kieviet in Sun |
Permalink:
J2EE JCA Resource Adapters: The problem with XAResource wrappers.
Posted at
04:35PM Jul 23, 2006
by Frank Kieviet in Sun |
Permalink:
Resource adapters at JavaOneAt JavaOne 2006 I gave the presentation "Developing J2EE Connector Architecture Resource Adapters". I did that together with Sivakumar Thyagarajan. He works in Sun's Bangalore office.
That he works there, while I work in Monrovia California... that's one of the interesting things about working at Sun: it's very international. Sun has people in all corners of the world. Last week I was on a phone call with perhaps 20 other people, and 12 of them were from other countries.
I talked to Sivakumart a few times on the phone before JavaOne, but met him only face to face for the first time at JavaOne. That's also one of the nice things about JavaOne: you get to meet people face to face you otherwise only talk with on the phone.
The presentation went pretty well, and the audience agreed: at the end of the presentation all audience members can fill in an evaluation form. Here are the feedback results
If you're interested, here's some more information:
JavaOne session information of "Developing J2EE Connector Architecture Resource Adapters"
Slide presentation "Developing J2EE Connector Architecture Resource Adapters"
I've recorded the presentation on my MP3 player:
Audio presentation of "Developing J2EE Connector Architecture Resource Adapters" (.wav)
Audio presentation of "Developing J2EE Connector Architecture Resource Adapters" (.mp3)
Posted at
10:43PM Jul 22, 2006
by Frank Kieviet in Sun |
Permalink:
Next: JCA Resource adaptersAt Sun I'm responsible for the application server and the JMS server that are shipping as part Java CAPS. As such I've been involved quite a bit in resource adapters (Java Connector Architecture, or JCA).
All this serves as an introduction to some more technical blogs on resource adapters.
Posted at
09:59PM Jul 22, 2006
by Frank Kieviet in Sun |
Permalink:
Automatic log translationWhy would I want to translate logs from one locale to another?
Say that I were to build a product, and I do a nice job to make it internationalizable. The product is a success, and it is localized into various languages. Next, a customer in a far-away place sends an email complaining about the server failing to start up. For my convenience, he attached the log file to it. Since I did a good job writing decent error and logging messages, I expect it to be no problem to diagnose what's going wrong. But oops, since I did such a nice job internationalizing the product, the log is in some far-away language, say Japanese! Now what?
Let me give exemplify the example. Let's say that the log contains this entry:
(F1231) Bestand bestelling-554 in lijst bestellingen kon niet geopend worden: (F2110) Een verbinding metLooks foreign to you? (It doesn't to me, but I would have great problems if this example were in Japanese).
server 35 kon niet tot stand gebracht worden.
Fortunately, through the error codes, we could make an attempt to figure out what it says by looking up the error codes. However, if there are many log entries, this becomes a laborious affair. Would it be possible to obtain an English log file without tedious lookups and guess work?
I think there are a few different approaches to this problem:
- always create two log files: an English one and a localized one.
- store the log in a language-neutral form, and use log viewers that render the log in a localized form
- try to automatically "translate" the localized log file into English
try {The exception message is already localized when it is thrown. E.g. in the catch-block, there is already no language neutral message anymore. It would have been nice if there were a close cousin to the Object.toString() method: one that takes the locale: toString(Locale) and if the Exception class would take an Object instead of limiting itself to a String.
...
throw new Exception(msgcat.get("F2110: Could not establish connection with server {0}", serverid));
} catch (Exception e) {
String msg = msgcat.get("F1231: Could not open file {1} in directory {0}: {2}", dir, file, ex);
throw new IOException(msg, ex);
}
In a previous product where I had more control over the complete codebase, I approaches this problem by introducing a specialized text class that supported the toString(Locale) method, and Exception classes that could return this text class. This solution was also ideal for storing text in locale-neutral form in a database, so that different customers could view the data in different locales.
There is a kludgy work-around: we could change the msg.get() method so that it returns a String that is locale neutral rather than localized. A separate method would convert the locale neutral String into a localized String, e.g. msg.convert(String, Locale). This method would have to be called any time a String would be prepared for viewing, e.g. in the logging for a localized log.
In the products that I am currently working on, these approaches to support locale-neutral strings are not feasible because they would require widespread. So let's take a look at option 3.
Given the resource bundle
F1231 = Bestand {1} in lijst {0} kon niet geopend worden: {2}and
F2110 = Een verbinding met de server {0} kon niet tot stand gebracht worden.
F1231 = Could not open file {1} in directory {0}: {2}let's see if there is a way to automatically translate the message
F2110 = Could not establish connection with server {0}
(F1231) Bestand bestelling-554 in lijst bestellingen kon niet geopend worden: (F2110) Een verbinding metinto
server 35 kon niet tot stand gebracht worden.
(F1231) Could not open file bestelling-554 in directory bestellingen: (F2110) Could not establish aI think it is possible to build a tool that can do that. The tool would read in all known resource bundles (possibly by pointing it to the installation image, after which the tool would scan all jars to exttact all resource bundles), and translate them into regular expressions. It would have to be able to recognize error codes (e.g. \([A..Z]dddd\) ) and use these to successively expand the error message into its full locale neutral form. In the example, the neutral form is:
connection with server 35.
[F1231, {0}=bestellingen, {1}=bestelling-554, {2}=[F2110, {0}=35]]The neutral form then can be easily converted into the localized English form.
Posted at
05:50PM Jul 16, 2006
by Frank Kieviet in Sun |
Permalink:
Internationalization of logging and error messages for the server side (cont'd)In Thursday's entry I proposed that a tool is needed to make it easier to internationalize sources where the English error messages are kept in the source file, and the foreign language messages are in resource bundles.
Let's talk about this tool. There are a few different approaches to go about this tool. As Tim Foster remarked in his comments, it's possible to parse the source code. This approach is doable, especially when existing tools are used (Tim mentioned.
Another approach is to parse the compiled byte code. Using tools like BCEL, it's fairly simple to read a .class file, and extract all the strings in there. It could easily be run on the finished product: just add some logic to go over the installation image, find all jars, and then iterate over all .class files in the jars.
Fortunately the compiler makes a string that is split up over multiple lines in the source into one:
String msg = msgcat.get("F1231: Could not open file {1}"is found in the .class file as:
+ " in directory {0}: {2}", dir, file, ex);
F1231: Could not open file {1} in directory {0}: {2}So it's simple to extract strings from a .class file. But how can we discern strings that represent actual error messages from other strings? Error messages can be discerned from other strings because they start with an error message number. The error message number should follow a particular pattern. In the example
String msg = msgcat.get("F1231: Could not open file {1} in directory {0}: {2}", dir, file, ex);the pattern (regular expression) is
[A-Z]dddd\:Note that a similar trick would have been used when parsing source code, unless some logic is applied to find only those strings thar are used in particular constructs, like calling methods on loggers, or constructors of exceptions. This can quickly become very complicated because often log wrapper classes are used instead of java.util.Loggers.
This is also the answer to a question that I didn't pose yet: in the following code,
String msg = msgcat.get("F1231: Could not open file {1} in directory {0}: {2}", dir, file, ex);how does the msgcat object localize messages? It does that by extracting the error code from the message (F1231) applying the same regular expression, or by splitting the string on the colon. In either case, it's important to have a convention on how the error message looks like or is embedded into the message.
throw new IOException(msg, ex);
Next problem: how to re-localize an existing log so that an American support engineer can read a log from his product that was created on a Japanese system?
Posted at
03:45PM Jul 15, 2006
by Frank Kieviet in Sun |
Permalink:
Internationalization of logging and error messages for the server side (cont'd)
I ended my previous blog with "Isn't there a better way"? Well...
how would I like to use error messages in Java
source code? I would simply want to write something like this:
String msg = msgcat.get("F1231: Could not open file {1} in directory {0}: {2}", dir, file, ex);The advantages are clear:
throw new IOException(msg, ex);
- No switching to a different file to add the error message
- The error message is visible right there in the source code -- easy to review!
- It's easy to see that the arguments in {0}, {1} are correct
How is this source file internationalized? We need a tool! The tool will
- locate all error messages in the code base
- generate properties files for all desired languages if they don't exist
- print out a list of all properties files that need to be localized
msgs_en_US.propertiesand
# AUTOMATICALLY GENERATED# DO NOT EDIT
# com.stc.jms.server.SegmentMgr
F1231 = Could not open file {1} in directory {0}: {2}
msgs_nl_NL.properties
# com.stc.jms.server.SegmentMgr
# F1231 = Could not open file {1} in directory {0}: {2}
# ;;TODO:NEW MESSAGE;;F1231 =
so that a human translator can easily add the translations to the foreign properties files. As you can see, it includes the location (Java class) where the message was encountered.
msgs_nl_NL.propertiesOfcourse the tool would have a way of handling if you would change the error message in the source code. The translated properties file would look like this:
# com.stc.jms.server.SegmentMgr
# F1231 = Could not open file {1} in directory {0}: {2}
F1231 = Bestand {1} in lijst {0} kon niet geopend worden: {2}
msgs_nl_NL.propertiesAny ideas on how to build this tool?
# com.stc.jms.server.SegmentMgr
# F1231 = File {1} in directory {0} could not be opened: {2}
# F1231 = Could not open file {1} in directory {0}: {2}
# ;;TODO: MESSAGE CHANGED;;
F1231 = Bestand {1} in lijst {0} kon niet geopend worden: {2}
Posted at
11:30PM Jul 13, 2006
by Frank Kieviet in Sun |
Permalink:
Internationalization of logging and error messages for the server sideThis is how one would throw an internationalizable message:
String msg = msgcat.get("EOpenFile", dir, file, ex);The localized message is typically in a .properties file, e.g.
throw new IOException(msg, ex);
EOpenFile=F1231: Could not open file {1} in directory {0}: {2}Each language has its own .properties file. The msgcat class is a utility class that loads the .properties file. Logging messages to a log file typically uses the same constructs.
Looks cool, right? So what's my gripe?
- when coding this, you would have to update .properties file in addition to the .java file you're working on
- It's easy to make a typo in the message identifier, EOpenFile in the example above; there is no compile time checking for these "constants".
- It's difficult to check that the right parameters are used in the right order ({0}, {1}) etc.
- When reviewing the .java file, it's difficult to check that the error message is used in the right context and that the error message is meaningful in the context.
- When reviewing the .properties files, it's difficult to determine where these error messages are used (if at all!) -- you can only find out through a full text search
Posted at
10:26PM Jul 10, 2006
by Frank Kieviet in Sun |
Permalink:
|
http://blogs.sun.com/fkieviet/
|
crawl-002
|
en
|
refinedweb
|
Goal: run the same PyThon-based Wiki Engine on my IBook and my Sharp Zaurus, then set up some Data Synch routines...
Outcome summary
launch by doing: go into Terminal; do cd documents/wiki; do '/usr/bin/python pcgi.py';
July'2005
Decided to go with this PyThon distribution, and grab the core, net-client, and net-server chunks.
here's some discussion of alternatives...
installed
core with no problem, and ran it. Excellent.
installed
net-client - it gave me a warning about now having
io and
mime, which also leads me to
math, etc.
Tried to run [Simple Http Server], but got error which makes it clear I'm missing
linecache.py. Blech that's not in this distribution for [Sharp Rom] Zaurus, it's in another distribution from the same guy... How easy is it going to be to just sneak that module over?
copied
linecache.py over. Now no
string.py! After that, no
shutil.py.
Now when run get "serving on 0.0.0.0 port 8000"
bring up Opera, go to that URI
I get a directory listing! I pick a python file, and I get to see it.
I make 2 HTML pages that link to each other (using full-qualified URI-s so I know it's not just using the file: protocol), copy them over. Can load one, then follow link to the other, follow link back again! See title, bold, color links, etc.!
make real subclass of [Simple Http Server] to handle a real directory?
or jump right to some existing Wiki Engine?
some notes on [Simple Http Server]
Bruce Eckel mentions it but says it only support HttpGet which doesn't seem correct given some other mentions I've seen...
Moin Moin seems to be able to run just on PyThon, but documentation may not be current/consistent. Also concerned it may be too much for this little machine....
Karigell apparently is build on [Simple Http Server] and includes a Wiki Engine. (Though, given that it's a Python Web Framework, there may be more junk in there than I want...)
or maybe use [Cgi Http Server] with one of the Wikiengine-s that use CGI.
there's a super-lite approach using [WyPy] and [Cgi Http Server] and [Basic Http Server] - that might be most promising
had to copy some more stuff over, plus hack a little code to get the
sre Regular Expression module working
now getting empty page but no error message, ugh how fun to debug that
switched to slightly longer version mentioned in the original reference.
Then needed to change the permissions on the file, tweak the uri in the same way, etc.
starting to work!
doesn't seem to be rendering links for Wiki Name-s!
doesn't seem to actually remember the page contents - if you reload you still see the contents, but if you hit Edit you get an empty textarea.
Opera died from lack of memory.
restarted Opera, tried again, had a tiny bit more success but still pretty bad...
I hacked a few pages via a text editor; backlinks even give me a list, except I'm just seeing the raw markup version rather than the pretty html. Not getting any good HTML at all - even simple paragraphs aren't getting separated. (Lack of [View Source] in this Opera is really annoying.)
got the same code running on MacOsX. Works just right, rendering links, etc. At some point realized I had put some linebreaks in place where there were semi-colons, then realized that some of those weren't end-lines, but were hard constants within other stuff, so undid all that. But when I looked more closely at the version on the Zaurus, that one looked fine. Actually I went back and tweaked the linebreaks again anyway for a little bit of readability - have both platforms the same, and the Mac is running fine. Still half-working on Zaurus.
(at some point need to integrate some bits to make this server stoppable. In the meantime I'll try
kill -s kill pid)
now thinking there's no point in hacking on this approach, given that the Smart Ascii is so non-smart. Will start to play with some different Wiki Engine-s. I'd just jump to Moin Moin, but (a) I'm pretty sure I hate its Smart Ascii, and (b) it smells loverly big-complicated.....
Got Piki Piki Wiki Engine running easily, but hate the Smart Ascii it shares with Moin Moin. But maybe I should live with it for the sake of Wiki Standards...
get it running on MacOsX first. A few oddities with page loads, esp when using '/
instead of ?' as delimiter.
I suspect my little CGI stub is the culprit
which could have been one of the problems with [WyPy] also...
Install Piki Piki on Sharp Zaurus.
get "can't work out query" page back - huh that means the Regular Expression check against the page-name isn't working.
so I hack out that code and just pass the page contents without checking whether it's a valid Wiki Name. I get the page contents, but without any of the HTML rendering! Just like in [WyPy]!
So now I'm thinking that the Regular Expression library on the Sharp Zaurus is seriously not working or something (though it's not throwing off an exception, just never matching anything). I wonder if there's a Unit Test in there or something?
Aug'2005 - try to fix things
remove
re* and
sre* from Zaurus
go back to source of feeds, grab the
re library. Suspect I did something weird last time, maybe took from the non-[Sharp Rom] distribution, because now get demand for
strold library, so I add that.
put back in the original Piki Piki. Find I have to rename the script from plain
piki to
piki.py.
It's working!
But getting some strange results after editing. Sometimes clicking on an existing-page link, I'll get an edit form. I suspect it's some weird caching-effect... actually tweaking the code to pass the page-name as an argument (via '?
instead of just /') seemed to help a lot
But I am having cache problems which cause pages not to show their changes unless I Reload (even an edit form!), which is very frustrating.
try using Meta tags ([Pragma No Cache] and [Expires Neg One]) but that doesn't help.
is it the OperA browser or the [Simple Http Server]? suspect the former
Despite the cache issue, have moved all my To Do List-s over into WiKi. Success!
Aug11'2005
tweak Regular Expression-s to handle my variants on Wiki Word rules (can have consecutive caps and acronyms, include numbers anywhere in name except 1st char), plus decide to use double-brackets for a different patterns matching the [BlogBit] naming convention I use here.
all working, except the Recent Changes shows blank. Need to look at edit log
ah, I think the issue is that double-brackets was already used for macros calls - so need a different [Free Links] delimiter (I'm not doing full [Free Links], I mainly want a variant that's like a date-stamp like I do on ZWiki for [Blog Bits]).
single-brackets - no, I like to use that in body text sometimes.
bracket plus quotes? MoinMoin:HelpOnPageCreation (just used to allow spaces in names, not necessarily special chars)
double-parens? bracket-plus-paren?
actually, the double-parens might not be bad, as on the Sharp Zaurus Key Board it doesn't smell easy to make those brackets anyway....
settled on bracket-plus-quote - thought it was breaking the
WordIndex macro, but the real problem was I was mixing tabs and spaces (haven't gotten that worked out yet in JEdit), so that's cool
also inclined to move [BlogBit] pattern to starting straight with year-number, rather than with leading
z like I do in ZWiki. Though not quite comfortable with that decision, just because of potential for cross-compatibility...
Aug29'2005
everything looking pretty good (on code running on MacOsX - will need to roll out to Sharp Zaurus next)
though realized that Recent Changes in this code is case-insensitive and not careful about checking just for whole-words, so get some false-positive matches. Example: I was playing with ATT as acronym page, and [Back Link] led me to one page containing "attached" and another containing "formatted". Argh.
But probably not a priority for now (for more typical Wiki Word-s it's probably more of a feature than a bug).
but this would be a problem if it was the basis for a Touch Graph view.
Aug30
trying to fix OperA caching problem - success!
found config file in
/home/root/.opera/
edited per this doc - setting
Docs Modification=1 was key
Aug31
try playing around with various MacOsX ways to GUI mount an FTP. I figured that would be interactive enough that I wouldn't end up needing to write any synch code...
unfortunately none of them seem to work - they take forever to prompt me for an id/password, then they fail, etc.
back to Command Line
open Terminal window
cd to IBook directory where I want to work
FTP, open connection to Sharp Zaurus
cd to Zaurus directory where I want to work
then do FTP commands - put, get, etc.
Sept'2005 - Converting [Palm Pilot] notes to Wiki pages
I have old notes going back to 1998 or so. Various conversion processes led me to have a text file for each old folder/category, with all the notes for the category dumped together (with a clear separator, etc.).
Heh, actually wrote my first PyThon
class from scratch.
Some issues that came up
did some clean-up of text in JEdit before conversion (dashes into
*, correct line breaks and spacing for bullet lists, etc.)
a single-word Subject/firstLine for a note doesn't make a nice Wiki Word, so have to review list of pages generated, find those cases, and go tweak the source document
I didn't even have unique names for notes within a category sometimes, so have to review and tweak, etc.
if I already named a note with a Wiki Word, then using PyThon's
title function wipes out the mid-caps. So I have to write my own function to change cases in the ways I want to...
I tend to often name notes with a topic followed by a 6-dig yymmdd - I should probably convert these to use my "zyyyy-mm-dd-title" format...
I definitely have an issue with names duplicated across different contexts (Name Space) - e.g. if I'm thinking about multiple possible StartUp-s then each one might have its own Elevator Pitch page. What am I going to do about that?
prefix each with context name: [Business One Elevator Pitch], [Business Two Elevator Pitch] - blech long names; but maybe easiest solution if not many names will get used in multiple contexts. Short-term hack taken.
use Sub Pages features that some Wiki Engines have (does Piki Piki do that? Nope.). You can more easily link back-up to pages in the main namespace, and you get a single integrated Recent Changes view.
do I see if I can run Moin Moin on the Zaurus, or do I try and steal just that little bit and put it into Piki Piki?
make multiple spaces:
probably best idea, given potential for writing lots of spec pages, etc. - though will probably have some transition process where new ideas will start in the root/core, then become their own spaces.
how accomplish this?
multiple copies of scripts
some change to the Web Server stub
ugh I'm too lazy for these steps I think.
Feel like I need to think in the bigger picture - what happens in a WikiWeb with everyone having lots of wikis of varying types...
Oct20'2005 update
realized I need to wrap blog-bit listing pages in bracket-dblquote to make them link - just did it by hand for now
argh Sharp Zaurus FTP doesn't support
mget so it's going to be a huge pain to get files back from the zaurus to the IBook! (At least mput works, since it's driven from the MacOsX side) so I could dump a few hundred notes onto the Z.)
Jan'2008 update: well, for a 1-time thing, using an SD card might be easiest...
Apr'2007
just realized I can use the Wiki On Zaurus from my IBook (screen/keyboard).
this might be the basis of some Data Synch opportunity...
|
http://webseitz.fluxent.com/wiki/WikiOnZaurus
|
crawl-002
|
en
|
refinedweb
|
Ads Via DevMavens
ASP.NET doesn’t have this particular feature at least in stock ASP.NET projects. Part of the reason for this is that Resource management in ASP.NET is a bit more complicated as there are two kinds of resources that exist and also due to the fact that ASP.NET uses resource providers to expose the localization engine rather than a stock ResourceManager. So by default ASP.NET doesn’t have this strongly typed Resources feature.
Note though that Web Application Projects – being a more traditional project - incidentally does support strongly typed resources, although you’ll want to be careful with that as these resources are not using the ASP.NET Resource Provider but rather use a ResourceManager so they won’t work with custom providers and cause some possible duplication of resources cached in memory (more on that below).
Sooo – I got to thinking that it’s not terribly hard to properly generate strongly typed resources at least for global resources. After all ASP.NET makes it pretty easy to access ASP application resources directly in code via HttpContext.GetGlobalResourceObject() and GetLocalResourceObject() (also exposed on the Control and Page objects).
So why only Global Resources? Local Resources are page/control specific and so typically these are use with page specific logic and implicit keys (meta:resourcekey). In theory you could generate resource Ids for some of that content as well (like all non . containing resource keys), but it’s probably not nececessary. Typically local resource files will only contain implicit keys that are automatically assigned by ASP.NET’s implicit resource key (meta:resourcekey) functionality. Note though that you can store plain resources in a local resource file however if you choose. But generating
After looking at this initially it turns out that .NET actually includes a class that provides strongly typed resource creation automatically and it’s fairly easy to use and this was my first stop as I figured that would be the way to go. After all why reinvent the wheel, right? In fact, I thought I could rig this myself by using some tools the StronglyTypedResourceBuilder class to generate the class for me. It’s fairly straight forward to do this and it works with any type of resource manager (I’m using a custom database driven resource set here):
/// <summary>
/// Generates a strongly typed assembly from the resources
/// </summary>
/// <param name="ResourceSetName"></param>
/// <param name="Namespace"></param>
/// <param name="Classname"></param>
/// <param name="FileName"></param>
/// <returns></returns>
public bool CreateStronglyTypedResource(string ResourceSetName,string Namespace,
string Classname, string FileName)
{
try
{
//wwDbResourceDataManager Data = new wwDbResourceDataManager();
//IDictionary ResourceSet = Data.GetResourceSet("", ResourceSetName);
// *** Use the custom ResourceManage to retrieve a ResourceSet
wwDbResourceManager Man = new wwDbResourceManager(ResourceSetName);
ResourceSet rs = Man.GetResourceSet(CultureInfo.InvariantCulture, false, false);
IDictionaryEnumerator Enumerator = rs.GetEnumerator();
// *** We have to turn into a concret Dictionary
Dictionary<string, object> Resources = new Dictionary<string, object>();
while (Enumerator.MoveNext())
{
DictionaryEntry Item = (DictionaryEntry) Enumerator.Current;
Resources.Add(Item.Key as string, Item.Value);
}
string[] UnmatchedElements;
CodeDomProvider CodeProvider = null;
string FileExtension = Path.GetExtension(FileName).TrimStart('.').ToLower();
if (FileExtension == "cs")
CodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
else if(FileExtension == "vb")
CodeProvider = new Microsoft.VisualBasic.VBCodeProvider();
CodeCompileUnit Code = StronglyTypedResourceBuilder.Create(Resources,
ResourceSetName, Namespace, CodeProvider, false, out UnmatchedElements);
StreamWriter writer = new StreamWriter(FileName);
CodeProvider.GenerateCodeFromCompileUnit(Code, writer, new CodeGeneratorOptions());
writer.Close();
}
catch (Exception ex)
this.ErrorMessage = ex.Message;
return false;
return true;
}
This can be called with:
Exporter.CreateStronglyTypedResource("resources",
"AppResources","Resources",
Server.MapPath("App_Code/Resources/Resources.cs"));
This worked like a charm, but alas it creates a class that calls the ResourceManager and not the ASP.NET ResourceProvider. It looks something like this:
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AppResources.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
public static global::System.Globalization.CultureInfo Culture {
return resourceCulture;
set {
resourceCulture = value;
/// Looks up a localized string similar to Could not create new customer.
public static string CouldNotCreateNewCustomer {
return ResourceManager.GetString("CouldNotCreateNewCustomer", resourceCulture);
/// Looks up a localized string similar to Could not load customer.
public static string CouldNotLoadCustomer {
return ResourceManager.GetString("CouldNotLoadCustomer", resourceCulture);
/// Looks up a localized string similar to Customer was saved.
public static string CustomerSaved {
return ResourceManager.GetString("CustomerSaved", resourceCulture);
public static System.Drawing.Bitmap Sailbig {
object obj = ResourceManager.GetObject("Sailbig", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
/// Looks up a localized string similar to Today.
public static string Today {
return ResourceManager.GetString("Today", resourceCulture);
/// Looks up a localized string similar to Yesterday.
public static string Yesterday {
return ResourceManager.GetString("Yesterday", resourceCulture);
It worked great generating this class, but unfortunately this class won’t work with ASP.NET because it hardcodes the REsourceManager assignment and the code makes an assumption that the assembly that hosts the generated class also hosts the resources – an assumption that unfortunately is not true in ASP.NET. In ASP.NET Global Resources are stored in APP_GLOBALRESOURCESXXXX.dll. So this approach simply doesn’t work.
As I mentioned earlier WAP automatically creates strongly typed resources for global resources, creating one class for each resource file. In WAP this process actually works because ASP.NET creates this assembly by combining the resources and the generated resource class wrapper into the APP_GLOBALRESOURCESXXXX.DLL assembly. By placing the file there the stock generator actually works and the following initialization code works:
ResourceManager rm = ResourceManager("AppResources.Resources", typeof(Resources).Assembly);
However - note that this ResourceManager will be a duplicate of the ResourceManager that the ASP.NET ResourceProvider may already be using to access ResX resources. So if you access any resources through HttpContext.GetGlobalResource() you are now holding two ResourceSets in memory – one for the ResourceProvider and one for the ResourceManager. In addition these resources also will not work if you use a separate ResourceProvider since it bypasses ASP.NET’s resource provider altogether and goes straight to the ResourceManager.
So be wary of using these strongly typed resources or at the very least make sure that you use only the strongly typed resources or only GetGlobalResourceObject to minimize Resource cache duplication.
So the above is interesting, but it’s obviously not the right way to return provide strongly typed Resource data. The way that this should work is that each of these properties returns the result from HttpContext.GetGlobalResourceObject() so that it always goes through the ASP.NET provider which would ensure that Resource access always works whether you’re going through the default ResX provider or a custom provider and that there is no resource cache duplication. This mechanism should work both with stock projects and WAP.
So as part of my resource provider and general ASP.NET localization utilitities I added some functionality to create strongly typed resources from Global Resources that look something like this:
using System;
using System.Web;
namespace AppResources
public class Myresource
{
public static System.String Home
{
get { return (System.String) HttpContext.GetGlobalResourceObject("Myresource","Home"); }
public static System.String HelloWorld
get { return (System.String) HttpContext.GetGlobalResourceObject("Myresource","HelloWorld"); }
}
public class Resources
public static System.String Yesterday
get { return (System.String) HttpContext.GetGlobalResourceObject("Resources","Yesterday"); }
public static System.Drawing.Bitmap Sailbig
get { return (System.Drawing.Bitmap) HttpContext.GetGlobalResourceObject("Resources","Sailbig"); }
public static System.String Today
get { return (System.String) HttpContext.GetGlobalResourceObject("Resources","Today"); }
public static System.String CustomerSaved
get { return (System.String) HttpContext.GetGlobalResourceObject("Resources","CustomerSaved"); }
public static System.String CouldNotCreateNewCustomer
get { return (System.String) HttpContext.GetGlobalResourceObject("Resources","CouldNotCreateNewCustomer"); }
public static System.String CouldNotLoadCustomer
get { return (System.String) HttpContext.GetGlobalResourceObject("Resources","CouldNotLoadCustomer"); }
The tool will look at all Global resources in APP_GlobalResources .resx files (or my Database provider or a raw ResourceSets) and then convert them into classes, one class for each resource set. Each class has properties for each resourcekey and it simply returns a strongly typed value for the GetGlobalResourceObject() call.
There are routines that can create one class per ResourceSet or create all ResourceSets as shown above (2 resourcesets) and you can use either ResX files as input or the Database Provider that is related to this library.
There are one little kink in generating all ResourceSets at once –the class name is generated based on the resource name, but it’s made ‘proper’ case to ensure that the resource name stays the same regardless what case was used for the actual file or resourcesetname in the database. This is primarily a workaround for a decision I made in the database provider to use all lowercase storage in the database and for resx exports. Proper case is slightly more readable but for longer resource set names this will still not be optimal.
To generate the resource class you can run a couple of lines of code:
StronglyTypedWebResources Exp = new StronglyTypedWebResources(Request.PhysicalApplicationPath);
string Class =Exp.CreateClassFromAllResXResources("AppResources", Server.MapPath("~/App_Code/Resources.cs")));
or you can create an individual class from a single resource:
Clas = Exp.CreateClassFromResXResource(
Server.MapPath("~/App_GlobalResources/resources.resx"),
"AppResources",
"Resources",
Server.MapPath("~/App_Code/Resources.cs") );
Specifying a .cs or .vb file will create the appropriate class. Other methods allow doing the same export from the DataBase resources or by running against a live ResourceSet object which means you can pretty much convert any resource file as long as there’s a ResourceManager or Provider that can provide the ResourceSet.
Parsing ResX files is pretty trivial to do so for the ResX version the code looks something like this:
/// Creates a class containing strongly typed resources of all resource keys
/// in all global resource ResX files. A single class file with multiple classes
/// is created.
///
/// The extension of the output file determines whether VB or CS is generated
/// </summary>
/// <param name="FileName">Output file name for the generated class. .cs and .vb generate appropriate languages</param>
/// <returns>Generated class as a string</returns>
public string CreateClassFromFromAllGlobalResXResources(string Namespace, string FileName)
if (!this.WebPhysicalPath.EndsWith("\\"))
this.WebPhysicalPath += "\\";
bool IsVb = this.IsFileVb(FileName);
string ResPath = WebPhysicalPath + "app_globalresources\\";
string[] Files = Directory.GetFiles(ResPath, "*.resx");
StringBuilder sbClasses = new StringBuilder();
foreach (string CurFile in Files)
string file = CurFile.ToLower();
string[] tokens = Path.GetFileName(file).Split('.');
// *** If there's more than two parts is a culture specific file
// *** We're only interested in the invariant culture
if (tokens.Length > 2)
continue;
// *** ResName: admin/default.aspx or default.aspx or resources (global or assembly resources)
string LocaleId = "";
string ResName = Path.GetFileNameWithoutExtension(tokens[0]);
ResName = ResName.Replace(".", "_");
ResName = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(ResName);
string Class = this.CreateClassFromResXResource(file, Namespace, ResName, null);
sbClasses.Append(Class);
string Output = this.CreateNameSpaceWrapper(Namespace, IsVb, sbClasses.ToString());
File.WriteAllText(FileName,Output);
return Output;
/// Creates an ASP.NET compatible strongly typed resource from a ResX file in ASP.NET.
/// The class generated works only for Global Resources by calling GetGlobalResourceObject.
/// This routine parses the raw ResX files since you can't easily get access to the active
/// ResourceManager in an ASP.NET application since the assembly is dynamically named and not
/// easily accessible.
/// <param name="ResourceSetFileName"></param>
/// <param name="FileName">Output filename for the CSharp class. If null no file is generated and only the class is returned</param>
public string CreateClassFromResXResource(string ResXFile, string Namespace, string Classname, string FileName)
XmlDocument Dom = new XmlDocument();
Dom.Load(ResXFile);
return null;
string Indent = "\t\t";
StringBuilder sbClass = new StringBuilder();
CreateClassHeader(Classname, IsVb, sbClass);
XmlNodeList nodes = Dom.DocumentElement.SelectNodes("data");
foreach (XmlNode Node in nodes)
string Value = Node.ChildNodes[0].InnerText;
string ResourceId = Node.Attributes["name"].Value;
string TypeName = null;
if (Node.Attributes["type"] != null)
TypeName = Node.Attributes["type"].Value;
if (!string.IsNullOrEmpty(TypeName))
// *** File based resources are formatted: filename;full type name
string[] tokens = Value.Split(';');
if (tokens.Length > 0)
// *** Grab the type and get the full name
TypeName = Type.GetType(tokens[1]).FullName;
else
TypeName = "System.String";
// *** It's a string
if (!IsVb)
sbClass.Append(Indent + "public static " + TypeName + " " + ResourceId + "\r\n" + Indent + "{\r\n");
sbClass.AppendFormat(Indent + "\tget {{ return ({2}) HttpContext.GetGlobalResourceObject(\"{0}\",\"{1}\"); }}\r\n",
Classname, ResourceId,TypeName);
sbClass.Append(Indent + "}\r\n");
sbClass.Append("\t}\r\n\r\n");
sbClass.Append(Indent + "Public Shared Property " + ResourceId + "() as " + TypeName + "\r\n");
sbClass.AppendFormat(Indent + "\tGet\r\n" + Indent + "\t\treturn CType( HttpContext.GetGlobalResourceObject(\"{0}\",\"{1}\"), {2})\r\n",
sbClass.Append(Indent + "\tEnd Get\r\n");
sbClass.Append(Indent + "End Property\r\n\r\n");
if (!IsVb)
sbClass.Append("\t}\r\n\r\n");
else
sbClass.Append("End Class\r\n\r\n");
if (!string.IsNullOrEmpty(FileName))
string FileContent = this.CreateNameSpaceWrapper(Namespace, IsVb, sbClass.ToString());
File.WriteAllText(FileName, FileContent);
return FileContent;
return sbClass.ToString();
There are a couple of helper dependencies (provided in the library download) but you can get the jist of what’s happening here. The code basically runs through each of the data nodes of the XML document, picks up each key and type and based on that creates the property Get methods that return HttpContext.GetGlobalResourceObject().
For the ResX provider it took me a while of searching to figure out that ASP.NET has no way from a running application to get an instance of the ResourceProvider or ResourceManager. I searched high and low and although those properties are available the ResourceExpressionBuilder, they are marked internal and inaccessible (well, I guess Reflection could have gotten me access <s>) to an application. I suppose this makes some sort of sense since ASP.NET’s provider model doesn’t require a ResourceManager – you can implement a new provider and only implement the provider interface without ever creating the more complex and messy ResourceManager ‘implementation’ (yeah – no interface there!). But it sure would be helpful to be able to at least get a reference to the ResourceProvider and ResourceSet it contains to allow retrieving all the resource keys at runtime. I couldn’t find a way to do this except by hooking the provider. So instead I opted for the more brute force mechanism of parsing the ResX file directly. It’s easy enough to do if not as elegant.
Anyway, I’ve added this code to my ResourceProvider application sample and there’s a sample page in the LocalziationAdmin folder (StronglyTypedGlobalResources.aspx) that can generate these resources as shown above as well as the provider and utility source code.
You can download the latest version of the provider including this code from:
There are a few other enhancements in this update:
Support for Importing ResX resources into the Resource Database
ResourceId renaming and Implicit Key renaming (renaming a group of keys)
Updated layout
A few bug fixes
Documentation can be found here:
Enjoy
|
http://west-wind.com/WebLog/posts/9120.aspx
|
crawl-002
|
en
|
refinedweb
|
By: Barry Mossman
Abstract: This is the second article in a series upon the GOF Design patterns from a C# and .Net Framework perspective. It examines the STRUCTURAL Patterns. It focuses upon the benefits that would be obtained from their use. Reworked 5th August 2004.
by BarryMossman<is_at>primos.com.au
(5th August 2004: article and demostration program
reworked to remove heavy use of Interface declarations as I have
since learnt that these are not recommded in most situations)
This is my second article about the GOF Design patterns. The first
article studied the Creational Patterns, while this one looks at the
Structural Patterns. The first article also gave an overview of where
the patterns came from, and the general discussion of the general
techniques that they promoted. There is a link to my first article at
the bottom of this one, but I will firstly briefly recap a few of the
points from that article.
The source for this article's demonstration program is available
at CodeCentral. See link at the bottom of this document. The program
contains annotated example displays, and also displays some notes
about the patterns, so if you are interested in starting to work with
the patterns it may be a useful utility to have on your desktop
during the learning period.
The GOF design patterns help address the following challenges :".
The GOF described various categories of patterns: favoured way offer a great deal of runtime
flexibility, and are better set up for future modification. A
general theme of the design patterns is that they allow the
composition of larger and more flexible structures from smaller
helper classes.
The approach necessitates more physical classes, but is made more
workable where the
Adapter
Allows us to provide a new interface for a class that already
exists, allowing reuse of a heritage class where our client
requires a different interface.
Also allows us to build a new class which will have
"pluggable" adapters tailored for individual client
needs.
Bridge
Allows us to decouple a class from it's interface.
This allows the class and it's interface to be changed
independently over time which can lead to more reuse and less
future shock.
It also allows us to dynamically switch between
implementations at runtime allowing increased levels of runtime
flexibility.
Composite
A flexible pattern that allows the client to deal with complex
and flexible tree structures.
The trees can be built from various types of containers or
leaf nodes, and it's depth or composition can be adjusted or
determined at runtime.
The client is simplified as it can deal with the tree as a
single object, as the Composite pattern can take care of dealing
appropriately with all the differing component parts.
Decorator
Allows us to dynamically modify an object at runtime by
attaching new behaviours, or by modifying existing ones.
Is applied just to specific object instances rather than to
the class as a whole.
Can allow design of "pay as you go" systems where
overhead is incurred only when runtime, or configuration options,
require it.
Is best limited to changing an object's "skin"
rather than it's "guts".
Facade
This pattern allows us to simplify the client by creating a
simplified interface into a subsystem, or by creating a unified
interface into a group of subsystems.
Potential benefits are to simplify the client,
compartmentalise the client, help future proof our application,
or enable more reuse.
Flyweight
This pattern optimises memory use when we need a design a
class with which our client will want to create a very large
number runtime of objects.
The pattern is most applicable if there will be clusters of
runtime objects that have similar state (data), as it arranges
sharing of these instances.
The pattern works well with the Composite pattern.
Proxy
This pattern provides a surrogate object that controls access
to some other object.
The aim is to simplify the client when it needs to use an
object that has complications.
Examples include objects upon a remote system, objects who
have client authentication requirements, or objects that are
expensive to fully create so some client purposes may be served
with just a cut down instantiation.
This pattern allows us to define a different interface for a class
that already exists. The pattern is also known as a "wrapper".
The class that the client interacts with is called the "adapter"
class, and the class, behind the scenes, that they are actually using
is called the "adaptee" class.
Reasons that we may wish to use the Adapter pattern could be:
Or we are building a new class that we expect will be much
reused. It may be easier for these future clients if we minimise any
assumptions about the interface that they will wish to deploy when
using our class. We have the option of building interface adaption
into our class; this is called a "pluggable adapter". We
could design the adaptee class interface to be very detailed. We
could then design one or more adapter classes where the interface of
each is more simple and is tailored to the specific business need of
it's particular set of clients.
There are two implementation approaches for the Adapter pattern:
another advantage is that the adapter can expose just the
interface that is required by the client.
My illustration program demonstrates both Object and Class
Adapters.
Firstly let us look at the client code that is using the Adapter
pattern. The following code shows the client first using the older
Adapatee class, and then using the Adapter with it's new interface.
The heritage object's interface exposes method calls, while the new
look uses properties.
// use the "heritage" object
ShowUserCommentary(1);
ConcreteAdaptee adaptee = new ConcreteAdaptee();
listBox1.AppendText(adaptee.SayWho());
listBox1.AppendText(String.Format("nMade on {0}n", adaptee.SayWhen()));
// use the heritage object with a new interface via an Object Adapter
ShowUserCommentary(2);
ObjectAdapter adapter = new ObjectAdapter();
listBox1.AppendText(adapter.Name);
listBox1.AppendText(String.Format("nMade on a {0} in {1}n",
adapter.DayOfWeek, adapter.Month));
The output is as follows (The "UserCommentary" is in black,
and the "AppendText" output is in blue):
The heritage (Adpatee) class was defined as follows:
// ------------ "heritage" class
public class ConcreteAdaptee {
public string SayWho() {
return this.ToString();
}
public string SayWhen() {
return System.DateTime.Now.ToShortDateString();
}
}
As mentioned above there are two implementation approaches for the
Adapter pattern. The first is the OBJECT adapter where we create a
private instance of the Adaptee inside the adapter, and then
translate from the new interface into the old interface to achieve
the client's wishes. This approach is useful when we are providing an
Adapter to be used with a family of Adaptees as we can choose at
runtime which Adaptee class to instantiate privately. This means that
we have to provide just the one Adapter for use with all Adaptees.
/*----------- Approach #1: OBJECT Adapter
--------------*/
public class ObjectAdapter {
// fields
private ConcreteAdaptee _concreteAdaptee = new ConcreteAdaptee();
// properties
public string Name {
get {
return _concreteAdaptee.SayWho();
}
}
public string DayOfWeek {
get {
DateTime dt = System.DateTime.Parse(_concreteAdaptee.SayWhen());
return (dt.DayOfWeek.ToString());
}
}
public string Month {
get {
DateTime dt = System.DateTime.Parse(_concreteAdaptee.SayWhen());
return CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[dt.Month-1];
}
}
}
The other Adapter pattern implementation is a Class Adapter where we
inherit the Adapter from the Adaptee's class. This is more efficient
as the client will work directly with an object, rather than the
Adapter needing to create it's hidden private object and doing double
handling translation behind the scenes.
/*----------- Approach #2: CLASS Adapter
--------------*/
public class ClassAdapter: ConcreteAdaptee{
// properties
public string Name {
get {
return base.SayWho();
}
}
public string DayOfWeek {
get {
DateTime dt = System.DateTime.Parse(base.SayWhen());
return (dt.DayOfWeek.ToString());
}
}
public string Month {
get {
DateTime dt = System.DateTime.Parse(base.SayWhen());
return CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[dt.Month-1];
}
}
}
This pattern allows us to decouple a class from it's interface.
The pattern is also known as a "handle". The class that
provides the interface is called the Abstraction, and the class that
provides the service is called the Implementor. The client creates
both, and then advises the Abstraction that it is to use this
specific Implementor for this run.
A simple abstract class with subclassed implementations already
give us similar functionality, but the implementations are
permanently bound to the abstraction. The Bridge pattern allows to
make changes to either the interface or the implementation
independently of each other. This flexibility may become useful in
the future as it helps to future proof our systems against unexpected
change requirements. It will aid reuse and extension if we can vary
each independently in this way. The pattern also allows us to
dynamically switch implementations at runtime giving the possibility
increased runtime flexibility.
Deja vu ?
Doesn't this sound a bit like the Adapter pattern ?
Although the Bridge pattern is similar to the Adapter
pattern, they are different in intent and timing. The Adapter
pattern intent is to allow us to use an implementation via a
different interface. This is normally done after the
implementation has been published and is in use. The Bridge pattern
intent is to allows us to use multiple implementations with
possibly multiple interfaces. This is normally part of the original
design of the implementation itself.
My illustration program uses the Abstraction to call an Implementor
that states it's name and tells the time. It then switches to another
Implementor and makes the same call again. The new Implementor states
it's own name, and tells the time in a different format. Here are the
client calls:
ShowUserCommentary(1);
ImplementorBase implementor = new ConcreteImplementorA();
ConcreteAbstraction abstraction = new ConcreteAbstraction();
abstraction.Implementor = implementor;
listBox1.AppendText(abstraction.SayWho());
listBox1.AppendText(String.Format("n{0}", abstraction.SayWhen()));
// now access use the same calls & interface to access a different
// Implementor
ShowUserCommentary(2);
implementor = new ConcreteImplementorB();
abstraction.Implementor = implementor;
listBox1.AppendText(abstraction.SayWho());
listBox1.AppendText(String.Format("n{0}",
abstraction.SayWhen()));
Here is the output that we get:
Firstly let us look at the implementation of the Abstraction.
// --- Concrete Abstraction
// The interface allowing access to the Implementor.
public class ConcreteAbstraction {
// fields
ImplementorBase _Implementor;
// properties
public ImplementorBase Implementor {
set {
_Implementor = value;
}
}
// methods
public string SayWho() {
if (_Implementor == null)
throw new Exception("You must assign an Implementor
before using the Abstraction.");
return _Implementor.GetName();
}
public string SayWhen() {
if (_Implementor == null)
throw new Exception("You must assign an Implementor
before using the Abstraction.");
return _Implementor.GetTime();
}
}
And finally the Implementors.
// --- Concrete Implementations
// No public memebers. The client should only access methods via an
// Abstraction instance.
abstract public class ImplementorBase {
// methods
internal string GetName() {
return this.ToString();
}
internal abstract string GetTime() ;
}
public class ConcreteImplementorA: ImplementorBase {
// methods
override internal string GetTime() {
return System.DateTime.Now.ToString();
}
}
// A different implementation of the same services
public class ConcreteImplementorB: ImplementorBase {
// fields
private readonly DateTime _CSharpBLaunch = new System.DateTime(2003,5,6);
// methods
override internal string GetTime() {
return String.Format("{0} days since C#B launch",
System.DateTime.Now.Subtract(_CSharpBLaunch).Days.ToString());
}
}
This pattern allows us our client to work with complex and dynamic
tree structure objects.
The tree is built from two families of object. One family are
containers (Composites), and the other family are terminal nodes
(Leaves). Any Composite, at any level in the tree, can contain Leaves
or further Composites, so the tree structure can be of any depth. The
tree's structure can be determined, or altered, at run time making
this a very powerful and flexible pattern.
A focus of the pattern is to simplify the client by allowing it
operate, with generic code, upon the whole tree, a branch from the
tree, or just a single leaf. The use of this pattern will simplify
the client as it is working with tree objects generically regardless
of whether the object is a composite which in turn contains objects,
an empty composite, or just a terminal leaf node. We avoid a dense
set of switch blocks from having to be littered throughout our
client.
The pattern will also future proof the client somewhat as it will
not be impacted if we add further types of composite or leaves to
build the tree from. It is working with these objects generically and
did not know which concrete classes it was dealing with anyway.
The pattern's above objective relies upon the fact that we can
design a common interface for both Composites & Leaves. There are
two conflicting design considerations:
we want to be able handle Composites and Leaves generically
for the above reasons
the danger is that if the common interface, for example,
contains members that are only appropriate for Composites, then we
.run the danger of client code making an inappropriate call against
a Leaf object.
We can handle this inside the Leaf by having a null
implementation, but this may just hide a client bug. We want to
employ strong typing to avoid such bugs in the first place. If, for
example, there is a separate Composite interface, and the
Composite-only members are defined down the inheritance chain away
from the Leaves we will have better safety. The cost of course is
that our client has become more complex as it needs to test which
form of object it is dealing with.
The answer is to put as much functionality as possible into their
common ancestor, providing separate implementations via member
overrides. It helps if we consider a Leaf to be just a permanently
empty Composite. For the remaining members where safety is
required we move to Plan B. My demonstration program illustrates
these issues.
There is a further illustration of the composite pattern within
the Flyweight pattern's demonstration as
these patterns can work well together.
This first illustration of the composite pattern has a tree
structure which is built from two types of composite, and two types
of Leaf. Either composite type can contain either leaf type.
Firstly our client builds a multi-level tree, and then asks the
tree to document itself via the SayWho method. This method is
supported at both the composite or leaf levels. The tree as a whole
is just another Composite and therefor accepts the SayWho method
also.
The SayWho behaviour at each level is to print it's class name,
and to indicate semi-graphically it's depth within the tree. When the
SayWho method is called against a Composite, it in turn calls SayWho
against each object which it contains. This behaviour recurses
through the whole tree which demonstrates the powerful utility of the
pattern. Here is the client code:
// Create a "tree" structure
ComponentBase tree = new ConcreteContainer1();
tree.Add(new ConcreteLeaf1());
ComponentBase container = new ConcreteContainer2();
ComponentBase container2 = new ConcreteContainer2();
container2.Add(new ConcreteLeaf2());
container2.Add( new ConcreteLeaf1());
container.Add(container2);
container.Add( new ConcreteLeaf1());
tree.Add(container);
ComponentBase leaf = new ConcreteLeaf1();
tree.Add(leaf);
// The SayWho method processes the tree as a whole. It returns a
// string that portrays the structure semi-graphically.
ShowUserCommentary(1);
listBox1.AppendText(tree.SayWho());
This produces the following output:
The client then steps through the lower level of the tree to
reinforce the idea that the method can work with either Composites or
Leaves. Again the call against a Composite causes the whole structure
to be documented:
// Now step through the 1st level of the tree. The same
method is
// working with both Composites or Leaves.
ShowUserCommentary(2);
foreach (ComponentBase obj in tree) {
listBox1.SelectionColor = System.Drawing.Color.MediumBlue;
listBox1.AppendText(obj.SayWho());
listBox1.AppendText("------------n");
}
This produces output as follows:
The client then demonstrates further capabilities of the Composite
pattern. It firstly jumps to a specific tree position rather than
navigating forward a node at a time. It then performs a method which
requires the tree to process itself in a reverse direction.
/* Position to a specific position within the structure;
the 1st
child of the root's 2nd child. ie. we will be 3 deep in the
structure. This demonstrates the use of an indexer into the tree */
ComponentBase node = tree[1][0];
listBox1.AppendText(node.SayWho());
listBox1.SelectionColor = System.Drawing.Color.MediumBlue;
/* the following call demonstrates a call that works backwards
through the tree */
listBox1.AppendText(String.Format("The above object is {0} deep in the tree"
,(node.GetDepth()).ToString()));
Finally the client demonstrates how to handle any essential
differences between the composite & leaf node's interfaces.
/* Demonstrate how to handle any essential differences in
composite
& leaf interfaces. It makes no sense to try and delete an object
from with a Leaf node. If the node object is a Composite delete
it's child object. Remember that we are positioned within the tree */
ShowUserCommentary(4);
if (node is ContainerBase) {
ComponentBase objToDelete = node[0];
if (objToDelete != null) {
listBox1.AppendText(System.String.Format("Deleting
{0}n",objToDelete.ToString()));
((ContainerBase)node).Remove(objToDelete);
listBox1.SelectionColor = System.Drawing.Color.MediumBlue;
listBox1.AppendText(node.SayWho());
}
}
Enough talk ? Firstly we build an Abstract ancestor class for both
Composite and Leaf classes. This will contain logic and fields common
to both. This "graphical" illustration of the depth of the
object within the tree is maintained in the _indicateNesting field.
The IncreaseIndent method is called to increment the object's depth
whenever it is added into a container. This behaviour recurses
whenever a container is added inside an outer container. The GetDepth
method illustrates backwards navigation through the tree using an
object's reference to it's parent.
// --- Abstract Class
abstract public class ComponentBase {
// fields
private string _indicateNesting = "==";
private ComponentBase _parent = null;
// properties
abstract public ComponentBase this[int index] {get;}
internal ComponentBase Parent {
get {return _parent;}
set {_parent = value;}
}
internal string Indentation {
get {return _indicateNesting;}
set {_indicateNesting = value;}
}
// methods
// Add an object into this container (if this is a container)
abstract public void Add(ComponentBase aComponent);
// Increment the graphical indication this object's depth within the
tree
virtual internal void IncreaseIndent(bool Recurse) {
this.Indentation += "==";
}
// Calculate this object's depth within the tree.
public int GetDepth() {
ComponentBase work = this;
int i = 1;
while ((work.Parent != null) & (i < 99)) {
i++;
work = work.Parent;
}
return i;
}
// Provide an enumerator to drive "foreach"
virtual public IEnumerator GetEnumerator() { return null; }
// Build a string that semi-graphical shows this objects structure
// This method is overriden for the container classes
virtual public string SayWho() {
return (System.String.Format("{0}>
{1}n",this.Indentation,this.ToString()));
}
}
Next we have the implementation of the Composite classes.
// --- Container Classes
abstract public class ContainerBase: ComponentBase {
// Fields
private ArrayList ChildContents = new ArrayList();
// Properties
override public ComponentBase this[int index] {
get {
if (index >= ChildContents.Count)
throw new ArgumentException("No such
child");
return (ComponentBase)ChildContents[index];
}
}
// Methods
override public void Add(ComponentBase aComponent) {
ComponentBase newChild = (ComponentBase)aComponent;
newChild.Parent = this;
newChild.IncreaseIndent(false);
ChildContents.Add(aComponent);
}
override public IEnumerator GetEnumerator() {
return ChildContents.GetEnumerator();
}
override internal void IncreaseIndent(bool Recurse) {
foreach (ComponentBase xx in ChildContents) {
// if this is another container handle all it's children
too
if (xx is ContainerBase) {
((ContainerBase)xx).IncreaseIndent(true);
}
xx.Indentation += "==";
}
// only handle our own indentation once
if (!Recurse)
this.Indentation += "==";
}
// Removes an object into this Container.
public void Remove(ComponentBase aComponent) {
ChildContents.Remove(aComponent);
}
override public string SayWho() {
string st = "";
foreach (ComponentBase xx in ChildContents) {
st += xx.SayWho();
}
return (base.SayWho() + st);
}
}
public class ConcreteContainer1: ContainerBase {
}
public class ConcreteContainer2: ContainerBase {
}
Finally we have the implementation of the Leaf classes. There is very
little to implement at this level as the Component class has the more
complex behaviour, and what little there is required for the Leaves
has mostly been done in the Abstract ancestor class.
// --- Leaf Classes
abstract public class AbstractLeaf: ComponentBase {
// properties
override public ComponentBase this[int index] {
get { return null; }
}
// methods
override public void Add(ComponentBase aComponent) {
throw new ApplicationException("Cannot ADD to LEAF
nodes.");
}
}
public class ConcreteLeaf1: AbstractLeaf {
}
public class ConcreteLeaf2: AbstractLeaf {
}
I guess this looks like a lot of work, but we need to balance this by
the fact that this is a very powerful and flexible pattern that will
significantly simplify the client where it needs to process flexible
and dynamic structures such as these trees
This useful pattern allows us to dynamically modify an object at
run time by attaching new behaviours, or by modify existing ones. The
class to which we are going to add the new behaviour is called the
Component, and the new behaviours are added by using various
Decorators to operate upon the Component. The Decorator is a new
class that is added into the system. The Component class does not
need to, and will not, be aware of it's existence.
The Decorator's interfaces are compatible with the Component so we
can use either to address the Component.
The pattern is applicable when designing new systems, and is also
a useful option during a system modification project.
We could, of course, achieve the objective of attaching new
behaviours to our Component class by inheriting sub-classes from the
Component at compile time. The Decorator pattern has a number of
benefits to static inheritance:
In a situation where there are many different Component
classes, all with the same interface, we would be forced to create
an equal number of sub-classes if we were to use static inheritance
to implement the new behaviours. The Decorator pattern may enable us
to use just one Decorator to work with all of the component classes.
Before proceeding we should make clear what the Decorator pattern
is not. The GOF make a distinction between "changing
the skin" of an object versus "changing it's guts".
The Decorator pattern is only making changes to the Component from
the outside. If more invasive changes are required it would be better
to look to the Strategy pattern where the Component would outsource
some of it's functionality to one of several Strategy classes.
The pattern bears a relationship to the Adapter pattern:
the Adapter pattern allows us to modify an objects interface.
My illustration program has a Component class which has the
familiar SayWho method. The demonstration then adds various
Decorators to modify the SayWho behaviour. It then changes the
sequence which the Decorators are applied to achieve a different
effect. Finally it shows how a Decorator can add new behaviour to the
Component class.
The Component and Decorator clases are unlikely to share a common
base class, however we need to be sure that the Decorators implement
the same interface as the Component. We would also like to write
generic code that can deal with both Components and Decorators. For
this reason I have defined an interface called IGOFComponent that
both the Component and Decorator classes implement. Since there is no
common base class we need to use the Interface name, rather than a
class name, in our client's variable declarations.
There is a second interface named IDecorator that is inherits from
IGOFComponent and enables us to extend the Component's capabilities
if required as is demonstrated in my program.
The client is coded as follows:
// show the native SayWho behaviour before decoration
ShowUserCommentary(1);
IGOFComponent component = new ConcreteComponent();
listBox1.AppendText(component.SayWho());
// now apply 1st form of decoration; convert to uppercase
ShowUserCommentary(2);
IGOFComponent decorator = new ConcreteDecorator1(component);
listBox1.AppendText(decorator.SayWho());
// now apply 2nd form of decoration on top; make a sentance
ShowUserCommentary(3);
IGOFComponent decorator2 = new ConcreteDecorator2(decorator);
listBox1.AppendText(decorator2.SayWho());
// now apply the decorator in the reverse sequence to show a
// different result; everything will be in upper case.
ShowUserCommentary(4);
decorator = new ConcreteDecorator2(component);
decorator2 = new ConcreteDecorator1(decorator);
listBox1.AppendText(decorator2.SayWho());
// now use a capability that has been added by decoration
ShowUserCommentary(5);
decorator = new ConcreteDecorator2(component);
listBox1.AppendText(((IDecorator)decorator2).SayWhen());
The output is:
The interfaces are defined as follows. Note that I have called the
first interface IGOFComponent rather than the GOF's name of
IComponent to avoid confusion with the .Net component of the same
name. The Idecorator interface illustrates functionality that is
introduced by the use of the Decorator.
// --- Interfaces
public interface IGOFComponent {
// methods
string SayWho();
}
public interface IDecorator: IGOFComponent {
// methods
string SayWhen();
}
We then implement the Component interface:
// --- Concrete Component
public class ConcreteComponent: IGOFComponent {
// methods
public string SayWho() {
return this.ToString();
}
}
We then create a abstract ancestor upon which to base the various
Decorators. It is here that we implement the new SayWhen behaviour
which is added to the Component object by the Decorators.
>// --- Abstract Decorator
abstract public class AbstractDecorator: IDecorator {
// fields
protected IGOFComponent _concreteComponent;
// constructor
public AbstractDecorator(IGOFComponent aComponent) {
_concreteComponent = aComponent;
}
// methods
public string SayWhen() {
return String.Format("When = {0:f}",DateTime.Now);
}
abstract public string SayWho();
}
Finally we implement the Decorators.
// --- Concrete Decorators
public class ConcreteDecorator1: AbstractDecorator {
// constructor
public ConcreteDecorator1(IGOFComponent aComponent): base(aComponent) {
}
//methods
override public string SayWho() {
return _concreteComponent.SayWho().ToUpper();
}
}
public class ConcreteDecorator2: AbstractDecorator {
// constructor
public ConcreteDecorator2(IGOFComponent aComponent): base(aComponent) {
}
// methods
override public string SayWho() {
char [] delimiter = new char[] {'.'};
string beforeDecoration = _concreteComponent.SayWho();
string [] split = null;
split = beforeDecoration.Split(delimiter);
return System.String.Format(
"I am from namespace {0} and my class name is {1}.",split);
}
}
This pattern allows us to assist the client by creating a
simplified interface into a subsystem, or by creating a unified
interface into a group of subsystems. This can be desirable in both
an initial system design, and in a system maintenance scenario.
In this pattern we design a Facade class that presents a simple
interface that is suitable for our client's needs, and then we
outsource into this Facade class any plumbing tasks required to
obtain the services offered via the interface. This could include the
selection of the actual classes that form the subsystem, their
instantiation and configuration, building of parameters, calling
methods, etc. The client has a simple view of the world that is
consistent with it's needs, and any complexity that is associated
with dealing with the servicing subsystem is isolated into one point,
and away from application logic.
The subsystems that are being used are not aware of the fact that
they are being called via a facade.
In an initial system design situation our motivation may be to
create a system that is logically broken down into several
subsystems. This will have a number of advantages:
another situation would be if we needed a result from the
cooperation of several pre-existing subsystems with inconsistent
interfaces.
The GOF promote a application design that favours "object
composition" over "class inheritance". I described the
differences between these two approach in my earlier article that
described the GOF's Creational
Patterns. In summary this type of design dynamically assembles
object behaviour via the interaction a number of smaller helper
classes, rather than solely using static object inheritance to
assemble our object's behaviours at compile time. The downside to
this design option is that our application will contain more physical
classes than a system that is built just using class inheritance. The
use of the Facade pattern can reduce this as a issue as our client
can still deal with what looks like relatively simple objects.
In a system maintenance scenario the use of the Facade pattern may
allow us to extend the useful life of a subsystem whose interface has
become dated or out of step with the current requirements. Maybe
there are lots of options that are no longer applicable, or are still
applicable but just not to our client.
The application will often need just a single instance of the
Facade, so it is often used in conjunction with the Singleton pattern
that was described in the above article.
My illustration program uses needs to obtain a greeting message
from a group of inconsistent subsystems. It uses a facade to simplify
itself so that it can obtain the greeting with a simple call.
// The facade pattern builds us what seems a simple
greeting message
ShowUserCommentary(1);
ConcreteFacade facade = new ConcreteFacade();
listBox1.AppendText(facade.Greeting);
Here is the output:
The first code snippet is just part of my demonstration example,
and is not part of the Facade pattern, but my illustration doesn't
make much sense unless I show it here. This is the simulation of the
subsystems that the facade is going to simplify from the client's
perspective.
/* Some silly classes to simulate a complex subsystem whose
interface that
we want to simplify with a facade.
1/ A class that provides us with a variable greeting message format.
2/ A class that can provide the datetime in caller specified format
3/ A class that can tell us our name in either upper or lower case.
We are wanting our client to be able to get a simple timed, named greeting
without getting into lots of details that are not relevant to this client's
use of the sub-system. */
// --- Enumerations
public enum GreetingStyles {Terse, Chatty};
// --- Sub-Systems Classes
public class SubSys_GreetingText {
// methods
public string GetText(GreetingStyles style) {
switch(style){
case GreetingStyles.Chatty:
return "Hello and welcome, my name is {0} and the time is {1}";
case GreetingStyles.Terse:
return "{0}: {1}";
default:
throw new ApplicationException("Invalid style requested.");
}
}
}
public class SubSys_Time {
// methods
public string GetTime(string format) {
string work = String.Format("{{0:{0}}}",format);
return String.Format(work,DateTime.Now);
}
}
public class SubSys_Who {
// methods
public string GetName(Object obj, bool aUpper) {
return aUpper?obj.ToString().ToUpper():obj.ToString();
}
}
Now back to the Facade itself. It needs to work with the above
subsystems to obtain the greeting message for the client. All of the
formatting options are an overkill for this client, so the facade has
made this into a simple property access.
// --- Concrete Facade
public class ConcreteFacade {
// fields
private SubSys_GreetingText _greetingText;
private SubSys_Time _greetingTime;
private SubSys_Who _greetingName;
// properties
public string Greeting {
get {
/* The facade object is where we have the detailed knowledge of
how
to use the subsystems that we are proving a facade for.
Here we
assemble an outwardly simple greeting from a few classes
with
interfaces that are too complex for our simple
requirement. */
string _greeting = _greetingText.GetText(GreetingStyles.Chatty);
string _time = _greetingTime.GetTime("f");
string _name = _greetingName.GetName(this,true);
return (String.Format(_greeting,_name,_time));
}
}
// constructors
public ConcreteFacade() {
// initialise the various subsystems that we will be
using
_greetingText = new SubSys_GreetingText();
_greetingTime = new SubSys_Time();
_greetingName = new SubSys_Who();
}
}
The Flyweight pattern is designed for situations where we would
like to use objects in our system design, but are concerned about
doing so because a very large quantity of these objects will be
required at runtime. The Flyweight pattern allows us to economically
use objects in this case by automatically sharing an existing
instance, rather than creating a new one, whenever the client asks to
create an object where a mostly similar one is already in existence.
This allows us to design a system where we achieve the benefits of an
object orientated design even where it would seem that the memory
cost of all the individual objects would too expensive.
Where object instances are being shared we are also obviously
sharing the instance's data fields (termed "state" by the
GOF). Flyweight objects have two classes of data; intrinsic data and
extrinsic data. The shared data that is held within the flyweight
instance's fields is the "intrinsic" data. Any data that is
unique to each separate use of the instance is called "extrinsic"
data, and has to be held outside of the instance somehow.
The flyweight pattern is only really applicable if most of the
object's data can be made intrinsic (shared). The pattern allows the
most memory saving where there is either a large quantity of
intrinsic data associated with each instance, or where the actual
data at runtime allows a lot of sharing to occur. The memory savings
come at a cost of extra computational resources required to locate
the correct instance and to pass extrinsic data back and forth.
Flyweights are not applicable if our application needs to use code
such as "if (flyweightA == flyweightB)". The problem is
that flyweightA and flyweightB may share the same instance behind the
scenes, although the client regards them as separate objects.
The client uses a Flyweight Factory to create flyweight instances,
and is not aware that reuse is occurring. It thinks that is always
been given a fresh new instance, although of course it is having to
somehow store the extrinsic data and then pass it into the flyweight
whenever it is needed. This means that objects are a little more
clumsy than normal objects, but at least the client is able to focus
upon business issues without being bogged down with the plumbing
involved in arranging the sharing.
There are "shared" and "unshared" flyweights.
The "shared" versions are as described above. The
"unshared" ones are just normal single use, single instance
classes, which implement the same interface as their "shared"
relations. The same Flyweight factory can build both as this will
simplify life for the client. It will also help to future-proof the
client as we will be able to easily change the class of the
flyweights in a future version of the application by just changing
the Flyweight Factory. The client will be able to operate unchanged
with the new Flyweight objects as long as the new flyweights
implement the old interface (see my article about the GOF Creational
patterns in the links below).
The Flyweight pattern can be used within the Composite pattern
allowing us to cheaply create a large number of Leaf nodes. The leaf
nodes would be shared flyweights, and the containers would be
unshared. There is a restriction however as the fact that the
intrinsic data must be shared means that we will not be able to keep
a reference pointing to it's container in each leaf node. This will
restrict the navigation through the tree in an upwards direction
unless we can hold the parent reference within extrinsic data.
My illustration program for the Flyweight pattern is within a
Composite pattern context. I build a tree where the root is a
document. It can contain sentences which are themselves containers.
The sentences contain words and punctuation, which are the leaf nodes
and are implemented as shared flyweights. The illustration seeks to
show the use of both shared & unshared flyweights, also intrinsic
& extrinsic data.
The tree is built from some sentences extracted from a Borland
press release. Each word or piece of punctuation, is created as a
shared flyweight object and is added into it's particular sentance
container. The leaf object is then asked whether it seems to close
the sentence. If so the sentence container is added into the
document, and a new sentence container is created as an unshared
flyweight object. The "intelligence" as to whether the leaf
seems to close the sentence is outsourced to the leaf object, and is
intended to demonstrate the kind of benefit that we are achieving
from the leaf being an object. The client is fairly simple and clear
due in part to the benefits coming from the Flyweight pattern and OO.
// Create Flyweight factory, and then unshared flyweight
containers
// for the whole document and the 1st sentence.
FlyweightFactory factory = new FlyweightFactory();
IGOFComponent document = factory.CreateDocument();
IGOFComponent sentence = factory.CreateSentence();
IGOFComponent word;
ShowUserCommentary(1);
// Load the document's text from disk, and then break it up into
// a collection of individual words & punctuation.
MatchCollection itemList = LoadAndBreakUpUnformatedDocument();
// Process each item in the collection. Create a Flyweight object
// for the item, and add it into it's sentence container. Create new
// sentances as required. The flyweight objects have a property which
// indicates whether this object closes the current sentance. This OO
// working for us as this simplifies the client.
foreach (Match m in itemList) {
if (m.Length > 0) {
word = factory.CreateWord(m.ToString());
sentence.Add(word);
if (word.IsASentenceCloser) {
document.Add(sentence);
sentence = factory.CreateSentence();
}
}
}
Let us ignore the LoadAndBreakUpUnformatedDocument() call1 for the
moment as it is not related to the Flyweight pattern.
We are creating and using shared flyweight objects here, but the
client is not aware of this optimisation. It remains simple thanks to
the flyweight pattern.
The tree has been built from unformatted data. Once it has been
built this demonstration then instructs the flyweight instance that
contains the word "Borland" that it is to be coloured red
if it is to be written. This is achieved via intrinsic data stored in
the specific single instance that contains the word "Borland".
It affects all uses of the word "Borland" within the tree
as they all refer to the same shared instance.
The tree is then instructed to Write itself. The Composite pattern
works with the Flyweight containers & leaf nodes to print the
tree's data. The Write behaviour of the flyweight leaf node is to
underline the word if it appears within a glossary list known to the
flyweight class. This again demonstrates intrinsic data and the type
of client benefit to be obtained by the words being objects. The leaf
node's Write behaviour also causes the 1st word of each sentence to
be bolded. This demonstrates the use of extrinsic data. Each
individual use of a word shares the same single flyweight instance.
The word's text is the same and is shared, but each use may have it's
own individual position within it's own sentence. The sentence
position is stored externally to the flyweight, and is passed
extrinsic data at Write time with the above formatting behaviours.
Here is the client code that formats the word Borland, and then
causes the document to print itself. Again the client has been made
simple by OO.
// cause the word "Borland" to be written with a red font;
to
// demonstrate the the incidents are shared flyweights, and to show
// use of intrinsic data.
word = factory.CreateWord("Borland");
word.colour = System.Drawing.Color.Red;
// Cause the document to write. The leaf node object's Write
// behaviour demonstrates the benefits being obtained by the fact
// that the words are objects, and illustrates the use of intrinsic
// & extrinsic state.
document.Write(listBox1,1);
Now lets us look at the output achieved. Remember that the input to
this was plain unformatted text.
Now remember that my illustration of the Flyweight is within the
context of a Composite pattern, so we need a interface for the nodes
within the Composite pattern:
// --- Interfaces
public interface IGOFComponent {
// properties
Color colour {set;} // font colour: only meaningful for leaves
bool IsOnlyPunctuation {get;} // is this a "word" or is it only
// punctuation; only meaningful for
// leaves
bool IsASentenceCloser {get;} // does this leaf indicate the end of
the
// the end of the sentence; only
// meaningful for leaves
//methods
void Add(IGOFComponent aComponent); // only meaningful for
// containers
void Write(System.Windows.Forms.RichTextBox richtextbox,
int aPosition); // meaningful for either leaves or containers,
// but 2nd paramater only meaningful leaves
// (it is extrinsic state
showing the position
// of the word within the sentence).
}
Next we have the FlyWeight factory. This is where the sharing occurs.
The factory should only create a new instance where the object, that
the client has called, for has unique intrinsic data.:
// --- Flyweight factory
/* The client uses this factory to create both the "shared" & "unshared"
flyweight objects. The unshared ones could be created outside the factory,
but that would make life more complex for the client.
The method called CreateWord creates "shared" flyweights (words), and the
other Createxxx methods create "unshared" flyweights (sentences and the
whole document). */
public class FlyweightFactory {
// fields
private Hashtable Flyweights = new Hashtable();
// methods
public IGOFComponent CreateWord(string aWord) {
IGOFComponent testWord = (IGOFComponent)Flyweights[aWord];
if (testWord == null) {
testWord = new FlyLeaf(aWord);
Flyweights.Add(aWord, testWord);
}
return testWord;
}
public IGOFComponent CreateSentence() {
return new FlySentence();
}
public IGOFComponent CreateDocument() {
return new FlyDocument();
}
}
I did not create an abstract shared ancestor for the Composite and
leaf nodes, as the demonstration required no generic behaviour, and
it just distracted from what I am trying to illustrate here. I have
connected the two classes by having them both implement the
IGOFComponent interface. So now lets us look at the implementation of
the Container nodes. These are unshared Flyweights, which are really
just normal classes which happen to implement the same interface as a
shared Flyweight.
We can see an example of extrinsic data here. Any reuse of a an
individual word will share a Flyweight instance. They share the
word's text value, as well as the font colour that will be used to
print the word. What they don't share is the position within the
sentence for each individual use of that word. If a Flyweight
operation needs such extrinsic data it needs to be passed in as a
parameter. In the demonstration program the shared Flyweight's Write
method needs the word's position within the sentance as it wants to
bold the first word in each sentence. The extrinsic data for each
context needs to be stored external to the Flyweight somehow. In this
example it is inferred from the position of the reference to the
shared Flyweight in it's context, ie. within the Composite's
container node.
// --- Flyweight UNSHARED class: container nodes in our Composite
pattern
abstract public class AbstractUnsharedFlyContainer: IGOFComponent {
// fields
private ArrayList _children = new ArrayList();
// properties
public Color colour {
set {
throw new ApplicationException(
"Colour not relevant for sentences.");
}
}
public bool IsOnlyPunctuation {
get{ return false;} // default value; overriden for
leaves
}
public bool IsASentenceCloser {
get{return true;} // default value; overriden for
leaves
}
// methods
public void Add(IGOFComponent aComponent) {
_children.Add(aComponent);
}
public void Write(System.Windows.Forms.RichTextBox richtextbox,
int aPosition) {
int i = 1;
/* the position of the word in the sentance is an example of
a flyweight's extrinsic data. It is passed into the flyweight
whenever it is needed. In this case it is needed so that the 1st
word in each sentance can be bolded. */
foreach (IGOFComponent leaf in _children) {
leaf.Write(richtextbox, i);
if (!leaf.IsOnlyPunctuation)
i ++;
}
}
}
public class FlySentence: AbstractUnsharedFlyContainer {
}
public class FlyDocument: AbstractUnsharedFlyContainer {
}
Now let us look at the shared Flyweights; the words and punctuation
items within a sentence. The main things to notice is the intrinsic
data which is stored in the class's fields, and the use of both
intrinsic and extrinsic data within the Write method.
// --- Flyweight SHARED class: leaf nodes in our Composite
pattern
public class FlyLeaf: IGOFComponent {
// fields; --- can only be "intrinsic" data (see BDN article)
private string _word;
private Color _colour = Color.Blue; // default
// properties
public Color colour {
set { _colour = value;}
}
public bool IsOnlyPunctuation {
get{
//return Regex.IsMatch(@"W*",_word); // C#B bug ? Does not
work
return Regex.IsMatch(
@"[!#$*()-:;,.""?]",_word);
}
}
public bool IsASentenceCloser {
get{
/* The sentance has been broken down into words & "punctuation".
Each punctuation item is in it's own flyweight item, except for
quoted "sentance closers" being either a quoted period or
exclamation mark. These come as a pair, eg either ." or !" */
switch (_word) {
case ".": return true;
case @".""": return true;
case "!": return true;
case @"!""": return true;
default: return false;
}
}
}
// constructors
public FlyLeaf(string aWord) {
_word = aWord;
}
// methods
public void Add(IGOFComponent aComponent) {
throw new ApplicationException("Cannot ADD to LEAF nodes.");
}
/* Some fairly silly formatting so that we can see some "benefit"
coming from our object. */
public void Write(System.Windows.Forms.RichTextBox richtextbox,
int aPosition) {
// save existing font colour & style
System.Drawing.Color saveColour = richtextbox.SelectionColor;
System.Drawing.Font saveFont = richtextbox.SelectionFont;
System.Drawing.FontStyle saveFontStyle
= richtextbox.SelectionFont.Style;
// override colour to that specified for this word (intrinsic
// state)
if (saveColour != _colour) richtextbox.SelectionColor = _colour;
// use extrinsic state; set word bold if it is the 1st word in
// it's sentence
System.Drawing.FontStyle newFontStyle =
(aPosition ==1)
? System.Drawing.FontStyle.Bold:
System.Drawing.FontStyle.Regular;
// underline any word found in the "glossary" (instrinsic
// state again)
if (IsWordInGlossary(_word)) newFontStyle
|= System.Drawing.FontStyle.Underline;
// override the listbox's font's style with the above changes
richtextbox.SelectionFont = new Font(saveFont,newFontStyle);
// write the word to the list box
richtextbox.AppendText(String.Format("{0} ", _word));
// restore the listbox's font & colour attributes
richtextbox.SelectionFont = saveFont;
richtextbox.SelectionColor = saveColour;
}
/* Simulate a glossary function */
private bool IsWordInGlossary(string aWord) {
switch (aWord) {
case "Kahn":
return true;
case "Fuller":
return true;
default:
return false;
}
}
}
Finally you might like to see the LoadAndBreakUpUnformatedDocument
method from the client where I loaded the Press Release text and then
roughly broke it appart into it's constituent words and punctuation
items. This is nothing to do with the Flyweight design pattern, but I
had a bit of fun with the .Net Regex class to do this, and you may be
interested. The regex facility is very powerful. You can experiment
with it using the excellent free ware tool called Expresso from
Ultrapico (see link at the end of this document). Regex has a Matches
function which matches a supplied string against a regular expression
pattern. It puts all matches into a collection object. My pattern
causes the text to be roughly broken up into words, numbers,
"sentence closers", and individual punctuation items.
I have one confession to make; I had to edit the press release a
little to make this work. I had to deprive Mr Fuller of his middle
initial as it's following fullstop caused my function to prematurely
flag the termination of the sentence.
/* Obtain some data for the demonstration to work with. A section
of a
Borland press release is loaded from a file, and then is broken up into
a collection of words, numbers and punctuation. */
private MatchCollection LoadAndBreakUpUnformatedDocument() {
/* collection will contain:
* sentance closers; fullstop, exclamation mark (quoted or unquoted)
.+""+|!+""
* misc punctuation
[!#$*()-:;,.""?]
* numbers
d+
* words
w* */
Regex regex = new Regex(@".+""+|!+""+|[!#$*()-:;,.""?]|d+|w*",
RegexOptions.IgnoreCase
| RegexOptions.Multiline
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
RichTextBox rich = new RichTextBox();
const string fileName = "Flyweight words.rtf";
try {
rich.LoadFile(fileName);
}
catch (System.IO.FileNotFoundException e) {
throw new ApplicationException(String.Format
("File "{0}" is needed by this
demonstration; {1}",
fileName, e.Message));
}
return regex.Matches(rich.Text);
}
The Proxy pattern's role is to provide the client with a
surrogate, or gatekeeper, object that controls access to some other
object. The GOF named the object that the client deals as the Proxy
object, and the object that it gives us access to is called the
RealSubject.
The client thinks that the Proxy is the real object, and is
unaware that it is using this other, behind the scenes, object. This
is achieved by the fact that the Proxy implements the RealSubject's
interface.
There are various situations where we obtain advantage from using
a Proxy:
A Smart Proxy: This type of proxy does some generic
housekeeping before, or after, use of the RealSubject. This allows
us to centralise housekeeping such as pooling or locks requred for
updates.
There is some similarity to the Decorator pattern as both patterns
implement the interface of some other object, and stand between it
and the client. The difference is in intent. The Proxy does not allow
us to add or subtract capabilities from the behind the scenes object
as the Decorator does. It's intent is to provide a gatekeeper when it
is inconvienet or undesirable to access the RealSubject.
My illustration program shows a Remote Proxy. The client needs to
use a remote server, and has been simplified by use of the Proxy.
Here is the client call using what looks just to be a normal class.
// Use a method on a remote server. The Proxy pattern simpifies
the
// client so that it can focus upon the business issues of what the
// object does for us, rather than confusing the issue by all the
// surrounding remoting plumbing.
RemProxy proxy = new RemProxy();
listBox1.AppendText(proxy.SayWho());
We need to start the "Remote Server" before pressing the
"Use Proxy" button otherwise you will get the following
error message followed by an exception.
The "remote server" is part of the demonstration program
that is available at CodeCentral. The RemoteInterface.dll is the
interface that is shared between the client's ProxyTest class and the
Remote Server which is the exe called remoteServer.
Once we run the Remote Server we will see the following
Now when we press the client's "Use Proxy" button we can
see the desired result. We can see that the Remote Server has been
accessed by the audit trail within the DOS box window, and we can see
that the result of the SayWho call has been returned to the client
for display.
The interface has been declared in it's own project so that it can
be shared by the Remote server, the client, and the dll that the
client uses for the demonstration.
namespace RemoteInterface
{
public interface IRemoteInterface {
string SayWho();
}
}
Here is the Proxy Class. The main things to note are that the
reference to the RealSubject is in the field called _server. The
proxy class aranges for the remote connection, handles exceptions,
and makes the request for the client.
public class RemProxy : IRemoteInterface {
// Fields
private IRemoteInterface _server;
// Methods
public string SayWho() {
TcpChannel channel = new TcpChannel();
string classAndServerName = "";
try {
ChannelServices.RegisterChannel(channel);
if( _server == null )
_server = (IremoteInterface)Activator.GetObject
(typeof(IRemoteInterface),
"tcp://localhost:8085/MyRemoteClassKnown");
try {
classAndServerName = _server.SayWho();
}
catch (System.Net.Sockets.SocketException) {
MessageBox.Show("You must start the supplied "remote"
server before pressing the Proxy button. The server also runs on this computer.",
"Problem",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
throw;
}
}
finally {
ChannelServices.UnregisterChannel(channel);
}
return String.Format("My name is {0}.",classAndServerName);
}
}
For the sake of completeness here is the implementation of the
RealSubject with the Remote server.
class Server {
[STAThread]
static void Main(string[] args) {
TcpChannel channel = new TcpChannel(8085);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(MyRemoteClassKnown), "MyRemoteClassKnown",
WellKnownObjectMode.Singleton);
System.Console.WriteLine("Press <enter> to exit.");
System.Console.ReadLine();
}
public class MyRemoteClassKnown: MarshalByRefObject, IRemoteInterface {
public string SayWho() {
System.Console.WriteLine("SayWho method has been called.");
return this.ToString();
}
}
}
This article has examined the Structural Patterns from those
described by the GOF in their book titled "Design patterns".
I think that the study of their design patterns is a worthwhile thing
to do. I found the following links helpful while studying the
patterns myself and while preparing this article. The book itself is
a good investment as it provides supplementary detail upon the
problems that the patterns are trying to solve, the elements of the
solution, and the consequences and trade-offs involved in using the
patterns.
Look out for my next article which will look at the Behavioural
patterns.
GOF
Creational Patterns ... If you found this article helpful you
may also enjoy my earlier article upon the Creational Patterns
(Factory, Abstract Factory, Builder, Prototype and Singleton)....
Expresso – an excellent free ware tool for building and
testing Regular Expressions (as used within the .Net Regex class).
See the Flyweight illustration.
ure
... contains a series of articles on the GOF patterns with C#
implementation examples
Server Response from: SC3
|
http://edn.embarcadero.com/article/32383
|
crawl-002
|
en
|
refinedweb
|
By: John Kaster
Abstract: Danny talked about Delphi language and run-time library improvements, .NET and Win32 support
This is a log of the chat rooms during the live audio chat from November 19, 2004 on Delphi 2005 with Danny Thorpe , a Borland Chief Scientist, and
architect of the Delphi compilers. Danny discusses changes and enhancements to the Delphi Win32 and Microsoft.NET compilers, the run time framework, and .NET support in general.
Note: This log is only the chat room transcript. There is much additional information covered in the audio replay that is not available in this chat log. For all previous and upcoming live chats, see.
dthorpe: who was supposed to bring the propeller?
aohlsson: Hehe!
dthorpe: mm refactoring good
aohlsson: Yes, is it good?
aohlsson: Careful. Youll break this chat client...
aohlsson: :)
dthorpe: mrbtrieve gets first post!
aohlsson: We know! :)
aohlsson: Hi! Cobolman!
aohlsson: Sprite!
dthorpe: and davidf!
jkaster: reminder: use /ask to submit questions
jkaster: thanks for the heads up on the picture behavior. will fix that for next chat (checked, and it's a browser settings issue, not a chat room issue)
jkaster: futurix : "Danny, for... in works for all types? Arrays? Collections? (in Win32 I mean)" - Win32 follows same rules for GetEnumerator. VCL has been updated to support this, for example. Arrays, multi-dimensional arrays,
strings, sets, classes that implement the pattern.
jkaster: cobolman : "can you change an object surfaced in a for ... in loop?" -.
jkaster: serge_d : "Can you expand TCollection to an IInterface (ICollection) to make it similar to .Net" - yes, it could be done, but my concern is about overhead to TList and collections, which are currently very lightweight.
Will continue investigating this.
jkaster: drbob42: "what about token collisions (the same type in multiple units - but same namespace)?" - that is a new risk in Delphi 2005 because you have multiple units with separate name scopes. Generally, that a bad idea to do,
but itsok. When you compile those two units into a .NET assembly, the units w/ the same type and same name are forbidden by .NET. The compiler doesnt currently catch duplicate names across different units in .NET. Best way to find those is using
PEVerify currently.
jkaster: JonR : "Are there compiler hints when the compiler "chooses" not to inline?" - Te compiler will hint when you ask for something to be inlined but it wont by the compiler
jkaster: leopasta : "Can we set an option so that the compiler will evaluate every function of a project, trying to inline it?" - yes, theres a complier directive called $inline with 3 states: on, off, auto
jkaster: Tjipke : "How to get rid of these inline hints?" - turn inline off or turn hints off
jkaster: drbob42: "is there a way to see if it was inlined or not?" - theres no simple indicator. hoping for color difference for dot indicator for debugger in the future
jkaster: JonR : "But what about Win32 API wrappers in Windows.pas? Wouldnt this be a huge benefit?" - yes, it is and we have!
jkaster: JonR : "My bad, there are many API wrappers that arent inlined in Windows.pas. I guess someone has already figured out reasons for these not to be inlined." - thanks for the followup
aohlsson: We turned off all cell phones. Forget about the landline... LOL!
jkaster: edan, use /ask to submit questions for danny to answer
jkaster: MrBtrieve: "For all of us non-.NET heads, what is Borlands long-term plan and/or commitment to keeping (and hopfully enhancing) the Win32 version of Delphi post Delphi2005?" - the plan is to continue to develop Win32 for
the compiler and IDE, primarily a lot of productivity work for the IDE
jkaster: drbob42: "will the Kylix compiler be upgraded to the same Win32/.NET language features?" Were working on the Kylix compiler plan. There is strong interest in updating Kylix, but nothing I can say for sure about Kylix
compiler plans. Main focus is bringing platform support up to latest Linux OS levels.
jkaster: futurix : "Inevitable question ;-) any chance of native Delphi for Win64?" - Which 64bit platform? Were certainly still considering this and analyzing costs involved.
jkaster: cobolman : "Is there significant overhead to using interfaces in Win32?" - the overhead is exactly the same as what its been all along, including support for addref and thread safety
jkaster: cobolman : "any chance of getting an expanded case statement to allow things like string items?" - In .NET thats a possibility using its string tokenizer. We would make the strings case sensitive
jkaster: mnk : "What priority have Generics?" - #1 for .NET 2.0
jkaster: MrBtrieve: "What is the status of Delphi for .NET apps and compatibility with products such as Mono?"> - We dont actively test on mono, but we actively recruit field testers who are familiar with mono. last I heard, the
Delphi for .NET compilers produce .NET applications that will execute on mono
jkaster: Leonel : "Is there a chance that Mono could be a supported platform in the future?" - the multi-personality IDE certainly opens up the door for plug-ins for things like this. CrossKylix is something you might want to
look at as well.
jkaster: JoeH : "any signs of MS making it easier for Delphi to have CF ?" - were working on this. targetting 2006
jkaster: webcab : "Any plans to extend
Delphi s support for COM (i.e. #import, 2 dim arrays wrappers) ?" - not planning on significant new investment on win32 com
jkaster: serge_d : "Do you plan to sync component list between .Net/Win32 and VS.Net (HelpProvider, ToolTip, NotifyIcon, ErrorProvider)" - ask allen bauer during his chat
jkaster: serge_d : "How ready D2005 for .Net 2.0?" - answered
aohlsson: emisosa : "re unicode, what happens with the .pas file format?" - handled
jkaster: serge, I dont understand your questions
aohlsson: leopasta : "Do you have any plan to remove p/Invoke dependency from VCL.Net in order to be compatible with Mono?" - no.
aohlsson: edan : "What is involved in moving a VCL (that extensively uses Win32 API calls) to a .NET assembly?" - handled
aohlsson: bfierens : "any progress,news,sight on pocketpc development" - handled earlier
jkaster: abauer : "hey I hear my name being bantered around!" - thats just a voice in your head, Allen
aohlsson: serge_d : "Will .Net 2.0 leverage CF support for D2005?" - handled earlier
jkaster: MaxOdenda : "I like the idea of having multiple personalities, what are your plans about including Kylix/Crosskylix/CLX into Delphi 2005 ?" - answered
aohlsson: Leonel : "How do you weight codegen improvements against new features when planning future development? I mean, how important is an optimizing compiler for you, in the big picture?" - handled
aohlsson: Max, use /ask...
jkaster: MrBtrieve : "Granted its a small sample, but ive heard from one user of Delphi 2005 that the IDE is "slow", specifically when switching between a form and unit, on the scale of 2-3 seconds. is this true? Additionally he
stated that when using the classic floating window IDE mode, CPU usage skyrockets. Comments?" - this is a great question for Allens chat. Watch EventCentral for announcements of his chat
jkaster: futurix : "Are there any changes for non-database VCL in Delphi 2005? New components?" - yes, there are. good question for Seppy Blooms chat. Watch EventCentral for it
jkaster: livechat : "Working with records in .NET is much faster than with objects. Record types have been also greatly expanded in the recent versions of Delphi. Do you generally recommend using records over objects whenever
possible?" - records in .NET are value types. You have to be careful in that assertion of performance gain because data gets copied all over the place.
jkaster: Tjipke: "Even adding system.io doesnt remove the inline hint" - ok, well have to look at that!
aohlsson: Leonel : "Any plans to include Design by Contract in the Delphi language?" - answered
jkaster: Tjipke : "what is the use of the hint: "[Hint] CB4Tables.pas(949): H2443 Inline function ExtractFileName has not been expanded because unit System.IO is not specified in USES list" ExtractFileName doesnt even come
from system.io!" -.
aohlsson: UnitOOPS : "horrified at the idea of even thinking about inlining. Comment?" - handled
jkaster: Tjipke: "(inline continued..) it does remove the warning when it is added to the implementation uses clause (not interface), but what if you change the implementation of extractfilename using not system.io but something else: all
units that have added the system.io now need the other namespace... looks very bad to me (but no need really to handle here)" - please follow-up on the newsgroups for this. were actually past time to quit
aohlsson: domus : "Have any internal benchmarks been executed to compare Delphi.NET applications to their Win32 equivalents?" - handled
aohlsson: serge_d : "D2005 and .Net 2.0/ASP2.0 support plans" - Great question for the upcoming chat with Jim & Steve regarding ASP.NET. Stay tuned.
jkaster: MaxOdenda : "I loved the demo from John Kaster about Together technology. Any chance we get this in a
Delphi release?" - Together for Delphi is one of the wishlist items we have for the near future. ECO actually uses the Together design surfaces. More should come in the future.
aohlsson: webcab: "In Delphi for .NET, COM; we're not sure what the best way to send and to receive two-dimensional safe arrays to COM methods is?" - Lets schedule a chat with Chris Bensen!
aohlsson: MrBtrieve : "Why, oh why, did you go and change our good old friend the tabbed-component palette?" - Perfect question for Allen or Corbin. Check EventCentral soon.
jkaster: emisosa : "maybe i should ask this to MS, but what happened with OpenGL or DirectX in .NET? is there anything on the VCL in D2005?" - DirectX is already available in .NET directly. OpenGL is a pet project of Dannys,
and there were some issues that prevented getting it into managed code in time for this release.
jkaster: question about Web Services and SOAP
jkaster: tsool : "I heard you were using the Virtual Tree View in D2005. Any chance you might it make available as a component for the D2005 users for use in .NET?" - ask corbin or seppy in their chat
aohlsson: Worried about what, Julian?
jkaster: JonR : "It seems someone from the dev team mentioned that Microsoft has prohibited Borland from officially supporting mono. Is that the accurate?" - not correct. That would be a violation of US Federal law for MS to
attempt to prohibit Borland from doing this.
dthorpe: tjipke: vacation, family, then work. :P.
funkyfred: hi all
Anders: Hi Fred!
funkyfred: hi
funkyfred: VIP Lounge? Public Chat?
funkyfred: :-)
MrBtrieve: hello
MrBtrieve: 10-4
MrBtrieve: coffee?
MrBtrieve: Gates
DavidF: Got my cup
MrBtrieve: returns
UnitOOPS: Refactoring, eh?
UnitOOPS: Btw...is this the volume level we can expect?
UnitOOPS: Btw...I use "UnitOOPS" since my real name breaks lots of stuff
UnitOOPS: Jim OBrine
UnitOOPS: (OBrien)
UnitOOPS: Right.
MrBtrieve: YAY
MrBtrieve: im #1
serge_d: hi, I hear you guys
serge_d: ;o)
serge_d: when do you plan to release first update for D2005?
iman: lol serge
cobolman: hi all
cobolman: Pepseye?
MrBtrieve: French mineral water
DavidF: Wow! All these high-tech dudes (MrBetrieve, Cobolman)!!
serge_d: nothing illigal at work (drinks)?
cobolman: Hey Anders - nice to see you - havent seen you in the ngs for a while
cobolman: yup - thats me
MrBtrieve: i am hi-tech
DavidF: Hi Danny
cobolman: Hi All - how long until you officially start?
iman: no
cobolman: Nope - connecting was easy
AndiS: no problem
bmcgee: No problems connecting here
serge_d: nop, nice sound too
DavidF: wadda mean Cobolman. This is it. chat away!
MrBtrieve: when you pasted a link in the chat, clicking on taht should open a new browser.
leopasta: ok from here
bmcgee: Missed the Cobol thing, though
iman: roomkey needs to be bold and underline
cobolman: OK great - time to get some caffeine
drbob42: no problem here - good sound
cobolman: Hey Dr Bob - got your hat on?
iman: yes
drbob42: no hat anymore ;-)
iman: :)
cobolman: WHAT! That Mark Miller .... <g>
DavidF: How we supposed to recognize yoou without the hat Dr Bob?
drbob42: I just turned 40 a few days ago...
cobolman: Bloody yougster ;-)
drbob42: old feller...
drbob42: thanks
leopasta: hey, this was a good example of a kylix app ;) It is good to see you are using it :)
MrBtrieve: kylix? whats that?
cobolman: Gday
futurix: Hello there!
serge_d: a little louder please! ;o)
cobolman: That must be a safe harbour statement <vbg>
drbob42: Danny, you rock!
serge_d: PS. Click on a picture replaced current page, which then lead to clear chat
JonR: Picture opened a new page for me... IE6
maxrf: not for me IE6
serge_d: PS.2. We see a lot of people rejoining, so ...
futurix: Firefox rules! ;-) I opened it in a tab
cobolman: Firefox here too - works great
mnk: test
sGingter: Hello
sGingter: makes sense :)
drbob42: and stringlists
futurix: Thank you! :-)
mnk: dr.bob is here!
drbob42: where else would I be? <g>
mnk: what means 42?
drbob42: the object pointer cannot be changed, but the properties can!
drbob42: but you can change the properties. I have an example...
Brion: did someone remember to start the transcript recorder?
livechat: Can we see the questions that have been asked already?
drbob42: hmm, ok - thanks for the warning then ; )
cobolman: OK - thanks for that answer. Quite a bit to it :-) Seems similar to C#
MrBtrieve: keep them lightweight please!
serge_d: (ICollection) Why? Can we get just accessor interface
JonR: Someone could create a TInterfacedCollection?
Wizardiii: I have heard some of you have missed the audio portion. If you dont hear danny goto:
Wizardiii inserts the following link:
serge_d: I have one. Exactly from a standpoint of accessor (available in DS Plug-in framework)
serge_d: I can post TInterfacedCollection to binaries for D2005 (could be included somewhere?)
JonR: How about posting to CodeCentral?
serge_d: OK, will do
serge_d: still would prefer to see it in base class...
JonR: Id prefer a separate class, so TCollection doesnt have the overhead (the same reason there is a TInterfaceList, TObjectList, etc)
serge_d: then you will need to reintroduce TCollection editors and classes for existing components
JonR: If TInterfacedCollection could drive from TCollection, shouldnt existing editors work?
MrBtrieve: does multi-unit namespaces have any effect on win32 projects?
drbob42: no
Wizardiii: Ask questions using the Ask Button.
MrBtrieve: <== .NET clueless
MrBtrieve: sorry
Wizardiii: then they show up above ;-)
MrBtrieve: my mistake
JonR: Dannys comments dont represent Borlands opinion, so D9 works for me. :)
serge_d: to JinR, yes...
MrBtrieve: "vb code" hehehe
emisosa: function inlinining.. finally! :)
JonR: Very very useful for API wrappers too...
drbob42: yes, I would like to see that hint ; )
JonR: As long as we can turn it off :-P
drbob42: you can always uncheck all hints ;-)
emisosa: heheh
domus: Salut, Bruno.
bfierens: hi all
domus: <- Dominique
emisosa: good one jkaster :)
emisosa: sorry, i meant , good one Tjipke.. :P
Tjipke: thx
leopasta: It would be extremelly useful to know when a function could be inlined by the compiler
drbob42: So finally I can use my Klingon (Unicode) identifiers!
Wizardiii: lol
drbob42: no Klingon properties! DokaH!
emisosa: :D
domus: "Honey, Im in the middle of a meeting"
edan: What is involved in moving a VCL (that extensively uses Win32 API calls) to a .NET assembly?
leopasta: LOL
cobolman: Someone asked about 64bit! Who did that? Own up! Come on :-)
serge_d: Delphi 200x and WindowsXP/2003 extensions (GUI) - getting Windows XP logo compliance for generated aps cobolman: Dennis? Are you in here? Will? : )
_zzorro: No it wasnt Dennis....
cobolman: Yeah - I see it was futurix
leopasta: .Net is the overhead on using .Net interfaces :)
cobolman: Thanks for these answers guys - I appreciate it.
DonS: generic generics?
drbob42: but you need the CLX units from D7 to allow it to work on D2005...
JonR: CrossKylix is very cool...
drbob42: yes, it is very very cool indeed!!
JulianK: Only 48 users? I expected 4800.. :(
drbob42: perhaps you are late? missed the best part? <g>
JoeH: thats great news !
drbob42: Thats Delphi 2006, right, not the year 2006... ??
jthurman: I finally escaped from prior obligations, with 5 minutes left in the chat...
Wizardiii: With my buffer delay your answers are here before I hear you talk about them ;-)
JonR: Past chats have been archived...
serge_d: thank you, will do
serge_d: To JohnK: Sorry ;( WindowsXP complaince? Docking, Help system, look and feel, theams, ... we have things done but not completed...
Wizardiii: MaxOdenda... it is on the partner CD.
MaxOdenda: Together for Delphi ? Wizardiii: CrossKylix
MaxOdenda: I know, I was thinking about a real integration including form designer
JulianK: From all that I hear, Im really worried as Delphi developer. :(
MrBtrieve: why?
emisosa: you should be happy!
Wizardiii: Why?
drbob42: are you listening to the same channel?? ;-)
JulianK: Cause since "D6" the Delphi seems like one endless experiment..
emisosa: to you? ;)
jthurman: I think Borland is (rightfully) leary of Mono after the lackluster Kylix results.
jthurman: Or is that leery?
drbob42: its called innovation - progress...
drbob42: BTW, the full Feature Matrix is online now!
jthurman: bob: Cool.
Tjipke: thanks guys (danny especially)
delyria: reset
jthurman: Thanks Danny! (and hi, incidentally)
Tjipke: Danny no get back to work soon!
drbob42: with a few typos in the key...
webcab: Thanks, now do I schedule a chat with Chris Benson
drbob42: thanks Danny
bmcgee: Thanks guys.
DonS: thx guys...
MaxOdenda: Thanks Borland for these Chat events
_zzorro: Thanks guys.
serge_d: there is updated version of component list as well
drbob42: BUT THE CHART/KEY IS A BIT WRONG - SEE NON.TECHNICAL
livechat: Thank you. Thank you very much!
emisosa: no, thank you... we should do this chats more often
AndiS: bye
drbob42: Bye everyone
serge_d: bye everyone
Server Response from: SC3
|
http://edn.embarcadero.com/article/32789
|
crawl-002
|
en
|
refinedweb
|
The Storage Team Blog about file services and storage features in Windows Server, Windows XP, and Windows Vista.. In this posting I will show some exploratory uses of the Dfsutil tool.
If you are working on a Windows Server 2008 system you have Dfsutil already available. On a Windows vista SP1 system you need to install the RSAT pack. To install the RSAT pack you can refer to for simple installation guidelines. Once Dfsutil is installed we can start doing some simple experiments. First let's have a look at the help:
Dfsutil /?
This is the best way to start exploring the tool. The help shows you the nine main commands Dfsutil offers:
The commands are organized in a tree like structure. So if you issue Dfsutil cache the result is:
Then you can select one of the three cache commands. If you pick Referral, for instance, the full command line will be Dfsutil cache referral. This is the new Dfsutil interface. Dfsutil also supports the old interface. You can obtain the help for the old interface by doing Dfsutil /oldcli.
With Dfsutil you can create/modify/remove DFS namespaces roots and links, add/remove targets, modify/view site costing properties, modify/view DFS registry keys, etc. It's a powerful tool! But let's start with something simple. How about listing all the namespaces in a domain? For that use the Domain command:
Dfsutil domain DomainName
That will give you the list of namespaces roots for the domain DomainName. You can use the FQDN if you prefer. Also, you can list the namespaces roots hosted on a specific machine by doing:
Dfsutil server MachineName
MachineName is the root server. This command lists domain and standalone namespaces hosted in the root server. The root server can be a remote machine. Now to look at the individual namespaces, you can do:
Dfsutil root \\DomainName or MachineName\RootName
Here's an example:
Alright, so we have the standalone root myroot on the root server 432233e0630-79. By using Dfsutil root, we can see that this root has a link called link0 and the target for this link is the share dlink0. Doing net share dlink0 you find the directory the link \\432233e0630-79\myroot\link0 points to.
Using Dfsutil and these few commands you can map all namespaces in your domain.
Hope this helped you get started with Dfsutil.
More info: Technet documentation: Dfsutil Overview
------- Marcello Hasegawa
PingBack from
Trademarks |
Privacy Statement
|
http://blogs.technet.com/filecab/archive/2008/06/26/dfs-management-command-line-tools-dfsutil-overview.aspx
|
crawl-002
|
en
|
refinedweb
|
Code Generator SPI Officially Available
Sometime ago this blog provided a preliminary example of a code generator. However, at the time, all that info wasn't official yet and you had to set an implementation dependency on one of the APIs. In the meantime, if you look at the NetBeans API Changes since Last Release document (which you should keep tabs on religiously, if you're a NetBeans Platform developer), you'll see this notification: "Code Generation SPI added":
The Code Generation SPI consists of two interfaces. The CodeGenerator implementations registered for various mime types serve for creating code snippets and inserting them into documents on the Insert Code editor action invocation. The CodeGeneratorContextProvider implementations registered for the mime types could provide the respective CodeGenerators with an additional context information.
Fine. What does all that mean? Firstly, interestingly, it means that the CodeGenerator class (and its supporting classes) are now officially supported and are exposed to the NetBeans API Javadoc. So, read the description to get an overview of it all.
Secondly, guess what? You can create code generators for any MIME type you want. So, you could add one/more to your HTML files... such as here:
So, the above appears when I press Alt-Insert in an HTML source file. What happens when I select the code generator item is up to me (i.e., the implementor of the API). In the case of Java source files, you can make use of the rather cool (though very cryptic) Retouche APIs. Let this document be your friend. I have found it pretty tough going, but gradually things become clear. Below, step by step, is my first implementation of a code generator. In the process, you'll see the Retouche APIs in action.
- Get a very recent post 6.1 development build and create a new NetBeans module.
- Set dependencies on Editor Library 2, Javac API Wrapper, Java Source, and Utilities API.
- Let's start very gently:
import java.util.Collections; import java.util.List; import org.netbeans.spi.editor.codegen.CodeGenerator; import org.openide.util.Lookup; public class HelloGenerator implements CodeGenerator { public static class Factory implements CodeGenerator.Factory { @Override public List extends CodeGenerator> create(Lookup context) { return Collections.singletonList(new HelloGenerator()); } } @Override public String getDisplayName() { return "Hello world!"; } @Override public void invoke() { } }
- Register it in the layer.xml file like this, in other words, register the Factory that you see in the Java code above:
<folder name="Editors"> <folder name="text"> <folder name="x-java"> <folder name="CodeGenerators"> <file name="org-netbeans-modules-my-demo-HelloGenerator$Factory.instance"/> </folder> </folder> </folder> </folder>
- Now you're good to go. Just install the module and invoke the code generators as always, Alt-Insert, and then you'll see the new one added:
- OK, now we'll do something useful. We'll start by getting the JTextComponent from the Lookup. That JTextComponent is the Java editor and if we use getText, we can get the text of the Java editor. We can also get the Document object, which is all that we need in order to get the JavaSource object, via JavaSource javaSource = JavaSource.forDocument(doc);, which, in turn, is our entry point into the Retouche APIs. So, here we go:
public class HelloGenerator implements CodeGenerator { private JTextComponent textComp; private HelloGenerator(JTextComponent textComp) { this.textComp = textComp; } public static class Factory implements CodeGenerator.Factory { public List<? extends CodeGenerator> create(Lookup context) { Item<JTextComponent> textCompItem = context.lookupItem(new Template
(JTextComponent.class, null, null)); JTextComponent textComp = textCompItem.getInstance(); return Collections.singletonList(new HelloGenerator(textComp));} } @Override public String getDisplayName() { return "Hello world!"; } @Override public void invoke() { } }
I don't know whether the above is the optimal way of doing this, but at the end of the day we now have a JTextComponent. In the next part, I've simply taken code from the Java Developer Guide, referred to earlier, and implemented the invoke exactly as described there, so see that document in order to understand the code below:
- Define the invoke method like this, which as stated above is completely taken from the Java Developer Guide:
@Override public void invoke() { try { Document doc = textComp.getDocument(); JavaSource javaSource = JavaSource.forDocument(doc); CancellableTask task = new CancellableTask<WorkingCopy>() { @Override public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); for (Tree typeDecl : cut.getTypeDecls()) { if (Tree.Kind.CLASS == typeDecl.getKind()) { ClassTree clazz = (ClassTree) typeDecl; ModifiersTree methodModifiers = make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC), Collections.<AnnotationTree>emptyList()); VariableTree parameter = make.Variable(make.Modifiers(Collections.<Modifier>singleton(Modifier.FINAL), Collections.<AnnotationTree>emptyList()), "arg0", make.Identifier("Object"), null); TypeElement element = workingCopy.getElements().getTypeElement("java.io.IOException"); ExpressionTree throwsClause = make.QualIdent(element); MethodTree newMethod = make.Method(methodModifiers, "writeExternal", make.PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), Collections.
singletonList(parameter), Collections.<ExpressionTree>singletonList(throwsClause), "{ throw new UnsupportedOperationException(\"Not supported yet.\") }", null); ClassTree modifiedClazz = make.addClassMember(clazz, newMethod); workingCopy.rewrite(clazz, modifiedClazz); } } } @Override public void cancel() {} }; ModificationResult result = javaSource.runModificationTask(task); result.commit(); } catch (Exception ex) { Exceptions.printStackTrace(ex); } }
- Excellent. At this point, check that you have this impressive list of import statements:
import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ModifiersTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeParameterTree; import com.sun.source.tree.VariableTree; import java.io.IOException; import java.util.Collections; import java.util.List; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeKind; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import org.netbeans.api.java.source.CancellableTask; import org.netbeans.api.java.source.JavaSource; import org.netbeans.api.java.source.JavaSource.Phase; import org.netbeans.api.java.source.ModificationResult; import org.netbeans.api.java.source.TreeMaker; import org.netbeans.api.java.source.WorkingCopy; import org.netbeans.spi.editor.codegen.CodeGenerator; import org.openide.util.Exceptions; import org.openide.util.Lookup; import org.openide.util.Lookup.Item; import org.openide.util.Lookup.Template;
- Now install the module again. Then open a Java source file. Let's say it looks like this:
package org.netbeans.modules.my.demo; public class NewClass { }
Press Alt-Insert anywhere in the source file, choose "Hello world!", and now you will see this instead of the code above:
package org.netbeans.modules.my.demo; import java.io.IOException; public class NewClass { public void writeExternal(final Object arg0) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } }
Hurray. You have your first code generator. In an HTML source file, the above invoke method could be as simple as this, which would print <h2>hello</h2> at the caret:
@Override public void invoke() { try { Caret caret = textComp.getCaret(); int dot = caret.getDot(); textComp.getDocument().insertString(dot, "<h2>hello</h2>", null); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } }
The very cool thing about these code generators is that you can keep typing, i.e., your fingers don't leave the keyboard in order to go to a menu item via the mouse, etc. You're typing as normal, then you press Alt-Insert, you select something, and then you go on typing. Being able to make your own contributions to the list of Java code generators (plus, being able to make them for other MIME types) is a really powerful enhancement to NetBeans IDE.
May 17 2008, 08:28:13 AM PDT Permalink
Does that also work if I have a MIMEResolver subclass that dynamically resolves MIME types? I'm asking this because I'm doing a platform application and have a feeling that once a Node has it's MIME type resolved it cannot be reevaluated.
Posted by kovica on May 17, 2008 at 03:26 PM PDT #
Don't know kovica, I've never tried any of that.
Posted by Geertjan on May 17, 2008 at 09:56 PM PDT #
Hi.
I was trying with your previous version of this functionallty and was very useful(), when I found this new post.. wow.. I think .. I need to test this new functionallity :) but unfortunatelly it doesn't work, my NetBeans version is NetBeans IDE 6.1 (Build 200804211638) and I can't find other new version with this APIs, now exposed...
I can't include org.netbeans.spi.editor.codegen.CodeGenerator :S
Posted by Yamil on May 19, 2008 at 12:11 PM PDT #
Go to the download page and download the development version instead of the 6.1 version, Yamil.
Posted by Geertjan on May 19, 2008 at 04:17 PM PDT #
Yamil, great to hear! Looking forward to hearing what you're doing with it (do you have a blog where you're writing about this stuff?)
Posted by Geertjan on May 20, 2008 at 07:22 AM PDT #
I want wizard for code generators! Please, Geertjan convince someone to provide it.
Posted by Jaroslav Tulach on May 21, 2008 at 06:17 AM PDT #
It's already in trunk:
Posted by Geertjan on May 21, 2008 at 07:01 AM PDT #
|
http://blogs.sun.com/geertjan/entry/code_generator_spi_officially_available
|
crawl-002
|
en
|
refinedweb
|
Escalation Engineer for SharePoint (WSS, SPS, MOSS) and MCMS All posts are provided "AS IS" with no warranties, and confers no rights.
Some of our field controls shipped with MOSS show a quite ugly behaviour as they add an extra entry after the field. Means an extra space.
This is especially ugly for the RichImageField control as it prevents two images to show up right beside each other. This article shows that this is actually a long known issue. But this article only shows a workaround which can be compared with the approach we used in CMS 2001 before we had custom placeholder controls: to hide the control in published mode, to read the content and then to modify it in the way we want to have it.
An approach in CMS 2002 would have been to create a custom placeholder for this. So only one single change and you can benefit from this anywhere on your site.
A similar approach can easily be implemented using a custom field control in MOSS.
A field control that would fix the problem discussed in this article would look like this:
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Web; using System.Web.UI; using Microsoft.SharePoint.Publishing.WebControls; namespace StefanG.SharePoint.WebControls { public class CorrectedRichImageField : RichImageField { protected override void RenderFieldForDisplay(HtmlTextWriter output) { // create a new tempWriter to consume the output from the base class TextWriter tempWriter = new StringWriter(); base.RenderFieldForDisplay(new HtmlTextWriter(tempWriter)); // capture the output of the base class and do the required adjustments string newHtml = tempWriter.ToString().Replace("</span> ", "</span>"); // write out the corrected html output.Write(newHtml); } } }
If you need information about how to implement such a field control please have a look at the relevant topic in the SDK:
If you would like to receive an email when updates are made to this post, please register here
RSS
Thanks for the tip. My team have started evaluating MOSS as a WCM platform and we've run into issues re accessibility and poor markup (tables being used instead of CSS, spacers, etc) when using the standard controls so this technique will come in very handy. Do you know if there are plans to provide web standards-friendly controls in future (e.g. via service pack or separate download)?
Hi Mark,
the same question often came up with CMS 2002 and the anwer was usually that this should be addressed with custom placeholder controls.
So I would not expect it. But if enough requirements from customers arrive through service requests it might be that this question will be evaluated again for a service pack in the future.
Cheers,
Stefan
Not the answer I wanted to hear but thanks for replying all the same :-)
Oen question on RichImageFields: Is it possible to have a custom page layout with multiple PageImages on it?? I've tried many times, today, but couldn't get it to work.
FieldName was set to PublishingPageImage, ID was set to something sifferent for each instance.
Page 'renders' correctly in Sharepoint Designer, and when edititing the page in Sharepoint I get to see the placeholders and I can set an image to it, but When I save, all Image-fields show the exect same image, regardless of how I set them...
Any thoughts on this?
Hi Iskander,
first you need to create a content type to be used by your page layout. The page layout is just the rendering window for the content type. For each field control you add you need to have an individual column in the content type.
Then bind the different field controls to the different columns.
Hi Stefan,
My biggest issue with controls are the web parts that come out of the box or even custom built ones. The web part is wrapped with table tags. Has anyone tried css adapters for web parts?
thanks,
anabhra
i have a question.
i want to repalce my own modified Datetime control instead of sharepoint original datetime control. is it possible?
Regards,
Sed Taha
Hi Sed,
if this is on a page layout you can do this.
Best would be to derive your control from the original one.
Can you show an example of this being used in an aspx page?
Hi Ed,
you can only use this in a page layout - like the original field controls comming with MOSS.
You have to open the page layout using SharePoint Designer and then you have to replace the original RichImageField control with the CorrectedRichImageField in Html View.
Also ensure to register the namespace of your DLL and class at the top.
Have a look in the SDK for details.
Does it mather what namespace you use? Do it have to end with .SharePoint.WebControls?
The namespace can be different.
Just ensure that you add the correct namespace as a reference in your page layout.
We came across a random issue lately where a publishing image (RichImageField) does not render correctly
Thanks.
And i use RenderFieldForDisplay for my custom render.
DisplayPattern is hard to use for me.
|
http://blogs.technet.com/stefan_gossner/archive/2007/03/29/how-to-overcome-glitches-with-the-standard-field-controls-shipped-with-moss-2007.aspx
|
crawl-002
|
en
|
refinedweb
|
There are exceptions to the types of SOAP web services Flash can consume. Flash only supports SOAP-based web services when they are transported over the HTTP protocol. Flash does not support SOAP web services over SMTP or FTP as of this release.
Flash also does not support web services with non-SOAP ports, such as MIME. The name attribute within the port element must point to a SOAP port. In the excerpt from the service definition of a WSDL document below, the port that bears the name SamplePort must be a SOAP port.
<service name="SampleService"> <port name="SamplePort"> <soap:address </port> </service>
Flash also does not support the
import tag. You can use
the
import tag to keep parts of a WSDL description in separate
files. You can reuse those parts, such as schemas and other definitions.
Flash MX Professional 2004 does not support web services that use the
import tag.
You may also run into problems with web services that require complex data, such as objects containing arrays, as an input parameter. If you try to pass complex data to a web service using the WebService API, you will receive an error saying that the endpoint URL could not be opened. To send complex data, use Flash Remoting. Complex data in output parameters, on the other hand, does not cause any problems.
This is probably pretty obvious, but I'll point it out anyway: Flash does not support web services that return data it can't handle, such as highly formatted HTML. If a web service returns an interactive HTML map, for example, Flash will not be able to render it correctly due to the limitations of its HTML capabilities. On the other hand, if the web service returns simply the building blocks for an interactive map, such as an XML structure describing label strings, the URLs of image files, and so on, Flash, with some effort, can recreate the map.
Finally, there are some types of web services that the WebService API supports that will fail if you use the WebServiceConnector component. The WebServiceConnector does not support web services with more than one SOAP port defined in the WSDL. The WSDL excerpt below defines a service with two SOAP ports.
<service name="SampleService"> <port binding="tns:Service1" name="Service1"> <soap:address </port> <port binding="tns:Service1" name="Service2"> <soap:address </port> </service>
If you try to invoke this type of web service with the WebServiceConnector, the compiler will throw an error: "There are multiple possible ports in the WSDL file; please specify a service name and port name!" The call fails because the WebServiceConnector API doesn't allow the developer to specify the port. When there is only one port, this does not become an issue.
Even though this is undocumented, the WebService API provides a workaround for handling multiple ports.
// instantiate the WebService object var ws:WebService = new WebService(''); // specify the port name ws._portName = 'Service1'; // call an operation on the service ws.getInfo('94103');
The example consumes a fictitious web service named Sample Service,
which defines an operation named
getInfo.
If you use the code above, the web service call will no longer fail because
it specifies the port. Note that this code requires the WebServiceClasses to
be in your movie's library. Select Other Panels > Common Libraries > Classes
and drag the WebServiceClasses compiled clip into the library of your Flash
file.
The WebServiceConnector component also does not support web services with more than one service defined in the WSDL. Web services with more than one service often have more than one SOAP port as well, since each service element in the WSDL contains a port element. Here is an excerpt from a WSDL description that describes a web service with more than one service:
<service name="SampleService"> <port binding="tns:SampleService" name="SampleService"> <soap:address </port> </service> <service name="AnotherService"> <port binding="tns:AnotherService" name="AnotherService"> <soap:address </port> </service>
Each service usually encompasses several operations. When you add the URL of the WSDL description of a web service with more than one service to the Web Services panel, Flash only parses the first service and its operations and displays them in the panel. This is because the Web Services panel only supports web services with exactly one service. The Web Services panel doesn't display more than one service per WSDL.
If you call one of the web services of a multiservice definition using the WebServiceConnector component, the compiler reports the same multiple ports error mentioned above. Again, there is an undocumented workaround through the WebService API. If you use this API to specify the service name and port name (as shown in the following code), the web service call will succeed.
import mx.services.* ; // instantiate the WebService object var ws:WebService = new WebService(''); // specify the service name ws._name = 'SampleService'; // specify the port name ws._portName = 'Service'; // call an operation on the service ws.invokeMethod('94103');
Note: This code requires the WebServiceClasses to be in the library of your Flash file. Select Other Panels > Common Libraries > Classes and drag the WebServiceClasses compiled clip into the Library panel.
|
http://www.adobe.com/devnet/flash/articles/flmxpro_webservices_03.html
|
crawl-002
|
en
|
refinedweb
|
This publication was prepared in the framework of a technical assistance project aimed at strengthening the capacity of least developed countries to mobilize resources through venture capital funds. It is intended for use in the training of senior and middle management in business planning and as a reference manual for individual enterprises to prepare their business plans, for submission to investors for funding, including venture capital funds.
Working out the business plan…………………………….2 B.. Monitoring the process……………………………………. Setting goals……………………………………………….3 D. How to prepare a business plan?……………………………………. Purpose of the business plan……………………………………….9 b. 10 d.2 A.. 23 PART TWO: BASIC ELEMENTS OF A BUSINESS PLAN CHAPTER II: EXECUTIVE SUMMARY…………………………. Why a business plan?………………………………………………. 13 G.. 11 f... Format and organization of a business plan………………………. 19 I.Contents Page Preface………………………………………………………………… iv PART ONE: INTRODUCTION CHAPTER I: THE ABC OF A BUSINESS PLAN…………………..6 2.. 29 A. Assessing the situation……………………………………….. What is a business plan?……………………………………………. Setting employee objectives………………………………. Different types of business plans…………………………………. 12 E..9 c.. Content and structure of a business plan…………………………….2 C.. 30 v . Developing a mission……………………………………….. What is expected from the investor/lender?…………………………13 F.. Who prepares a business plan?…………………………………. 17 H. 11 e.... Who reads the business plan?………………………………………. 6 1... Planning period…………………………………………………….. What are the steps in the planning process?…………………… 7 a. Getting ready………………………………………………. 12 g..
.. Main highlights……………………………………………………. Key data……………………………………………………………... Costing………………………………………………………... ownership and management…………………………. Legal form. 60 A. Quality assurance and control……………………………………… 57 H. Product attributes…………………………………………………. 40 CHAPTER IV: PRODUCTS AND SERVICES……………………. Location and premises………………………………………………37 C. Intellectual property……………………………………………….. Historical development and track record of the business…………. Positioning…………………………………………………………. Example of an executive summary………………………………… 33 CHAPTER III: BACKGROUND…………………………………… 36 A. 50 b. General organization/operating units………………………………. 55 G. Production process…………………………………………………. Market strategy……………………………………………………. 58 I. Buyer's standpoint………………………………………. Product life cycle……………………………………………………46 E. Pricing………………………………………………………… 50 a. CLIENTS AND COMPETITORS….... 43 C.. Seller's point of view……………………………………. 31 C. 58 CHAPTER V: MARKETS...63 F. 32 D. Sourcing……………………………………………………………. 42 B.. Financial requirements…………………………………………….65 G.. Costing and pricing………………………………………………… 48 1. 60 B. 48 2. 38 E.B.. 42 A. Business strategy and mission……………………………………… 40 G.. 46 D.. Competition………………………………………………………… 62 E. 38 D. Market characteristics……………………………………………… 61 C. 52 F.. markets and clients………………………………… 36 B. Product description and history…………………………………….. Research and development………………………………………….. Main products. Projected sales……………………………………………………… 69 vi . Clients……………………………………………………………… 62 D. Introductory remarks……………………………………………….39 F.
70 1. Practical issues venture capitalists will check………………………. 70 A. 109 vii . 106 B. Project management………………………………………………. Order processing and inventory control……………………………. 79 F.… 86 CHAPTER VII: HUMAN RESOURCES…………………………. 104 4. Company structure………………………………………………….CHAPTER VI: BUSINESS OPERATIONS AND ORGANIZATION……………………………………………………. Approvals and licensing requirements……………………………. 81 G. Executive management………………………………………… 90 4. 73 B. Promotion and advertising…………………………………….. Selling methodology………………………………………………… 76 D. Social compliance issues…………………………………………… 107 C. External support services……………………………………… 94 B. Premises………………………………………………………..… 84 I.. 88 1. 75 C. Location……………………………………………………….… 74 1... Middle management…………………………………………… 92 5.. 82 H..... Marketing…………………………………………………………. Team spirit…………………………………………………….. Location and premises………………………………………………. 78 E. 74 2. Attitudes and human characteristics of managers……………… 100 3. Distribution…………………………………………………………. Manufacturing………………………………………………………. 106 A.. Values and norms of the firm…………………………………. Development and social benefits…………………………………. 70 2. 95 1. 96 2.. AND ENVIRONMENTAL AND SOCIAL FACTORS………………….. 94 C.. Board of directors……………………………………………… 89 3. General remarks……………………………………………….. Technical skills and competencies of managers………………. Labour………………………………………………………………. Management information system/reporting………………………. 104 CHAPTER VIII: LEGAL FRAMEWORK..… 88 A. Management………………………………………………………. Shareholders…………………………………………………… 89 2.
Important financial ratios…………………………………………. 141 b. How to prepare a cash flow projection………………………. 146 d. 111 3. 119 C. 120 D.117 A. Total assets turnover ……………………………………. Fixed assets turnover …………………………………… 147 e. Examples of questions lenders and investors may ask………. Debt to equity ratio …………………………………….. 117 B. 135 F. Financial history…………………………………………………….. Dividend payout ………………………………………… 154 4. 145 c. Net profit margin ………………………………………. Some more hints for preparing/improving your cash flow……. 140 a. Operating profit margin ………………………………… 151 d. Designing a cash flow worksheet………………………. Inventory turnover ……………………………………… 144 b. 112 CHAPTER IX: FINANCIAL PLANNING…………………………. Profitability ratios ……………………………………………. Tools for cash flow projections…………………………... 155 viii .. The concerns of investors……………………………………. 110 1. 132 E.. Accounts receivable turnover …………………………. Introductory remarks……………………………………………….. 150 c.. 122 2. 132 4.D. Return on equity ………………………………………… 153 f. Efficiency ratios ……………………………………………… 143 a.. 148 3. 127 3.. The concerns of lenders………………………………………. 139 1. Environmental risks………………………………………………. What is cash flow……………………………………………. 149 b. 129 a. Why do you need cash flow planning?……………………….. Accounts payable turnover ……………………………. Return on assets ………………………………………… 152 e. Liquidity ratios………………………………………………. 142 2.. 122 1. 131 c... 155 a. Gross profit margin ……………………………………. Income statement projections………………………………………. Quick test ratio ………………………………………….111 2. Cash flow projections………………………………………………. Current ratio ……………………………………………. Balance sheet projections………………………………………….. Solvency ratios ………………………………………………. Steps in preparing your cash flow projections…………. 148 a. 129 b..
Internal rate of return ………………………………………… 163 H. Interest coverage ratio …………………………………. 159 G. 187 C. Political/regulatory……………………………………………. Request for funds and other supporting information………………. Risk assessment ……………………………………………… 165 3. Subcontracting………………………………………………….b. Request for funds……………………………………………. Methods for ranking investment projects………………………….. Total assets to total liabilities ratio ……………………. SWOT analysis……………………………………………………. Payback period ………………………………………………. 157 d... 160 2. Managing opportunities……………………………………………... 178 B. Quality/production problems…………………………………… 185 9.. 184 7. 180 3. 183 6. 187 D. General economic environment………………………………… 179 2. Capitalization ratio ……………………………………… 158 e. 179 1...186 10.188 GLOSSARY………………………………………………………….. Client-related……………………………………………………. 164 1. Market………………………………………………………….. Law suits………………………………………………………..182 4. Introductory remarks……………………………………………….. 164 2. Total assets to equity ratio ……………………………… 156 c.. Start-up business financial information ……………………… 167 I..... Changes in public opinion……………………………………….. 185 8. Staffing…………………………………………………………. Net present value ……………………………………………. 160 1. 192 ix .. Types of risks………………………………………………………. Technological…………………………………………………… 183 5. 161 3. Numerical example………………………………………………… 168 PART THREE: CONTINGENCY PLANS CHAPTER X: RISK AND SENSITIVITY ANALYSIS…………… 178 A..
66 Position in the market…………………………………………67 Matrix of strategies………………………………………….2.2.2.1. 163 Tables IV.1. IX.. VI. IX. Where did the habit of five-year planning originate?……….9.6. IV. V. 47 Chain of product cycles………………………………………. IX. 96 Characteristics for success…………………………………… 100 Income statement……………………………………………. 68 The basic characteristics of managers………………………. V.. Making a good impression………………………………….1.3.4.. Regulatory surprises………………………………………… Figures I. IV.4. 122 Sources and uses of cash flows……………. VI.Boxes I. IX.3.8. VII. Comparison of different pricing options…………………….5.1.1. V. 48 The method for setting the price of your product……………. 54 Typical organization chart of a production company…………83 Example of a project plan: construction of a plant for production of mango concentrate………………… 85 Determination of IRR………………………………………. Example: fish processing…………………………………… Example: executive search…………………………………. IV.2.1. IX.3.. 134 Balance sheet………………………………………………….1.1.. 138 Current ratio………………………………………………….2. 66 Analysis of market attractiveness……………………………. 141 Quick test ratio……………………………………………….7..1. III. IX..1. IV.. V.1. Role of the employees in the business planning process…….1. VII.. IX.2. 12 Example: Legal shareholding structure of SBTP Ltd………. 39 Accumulated income during the life cycle of a product……. IX..………………… 126 Example: reconciling cash revenues and disbursements……... 131 Cash flow statement…………………………………………. 53 Analysis of competitive advantages…………………………..1. VII. IX. IV. IX.. X. 142 Inventory turnover…………………………………………… 144 Accounts receivable turnover………………………………… 145 21 55 56 100 182 x .
23.2.20. 159 Income statement: an example……………………………… 171 Balance sheet: an example…………………………………..22.21.18..30.………………. IX... 153 Dividend payout……………………………………………. IX. X.146 Fixed assets turnover………………………………………. 154 Debt to equity ratio…………………………………………. 174 Reconciliation of shareholder's equity……………………… 174 Calculation of provisions for tax: an example……………… 175 Financing plan: an example……………….25. IX.11. 147 Total assets turnover…………………………………………148 Gross profit margin…………………………………………. IX. IX.14.. 152 Return on equity……………………………………………. IX.31. 155 Total assets to equity ratio…………………………………. IX.26.IX.24. IX. 172 Cash flow statement: an example…………………………… 173 Investment and depreciation plan: an example…………….. IX.27. X.28. 189 Opportunities and threats…………………………………… 190 xi .. 183 Strengths and weaknesses…………………………………. IX. Accounts payable turnover…………………………………. 156 Total assets to total liabilities ratio………………………….1. 149 Net profit margin……………………………………………...13.29. IX. 150 Operating profit margin…………………………………… 151 Return on assets……………………………………………. IX. IX. X. IX. IX. 157 Capitalization ratio………………………………………….10. IX.16.17..15. IX. 158 Interest coverage ratio……………………………………….. 176 Examples of damage………………………………………. IX.. 175 Ratio summary sheet……………………………………….19.12.. IX.. IX.3. IX..
PART ONE INTRODUCTION .
For example. well structured and reader-friendly. It is a detailed report on a company's products or services. requirements in respect of infrastructure and supplies. sincere.UNCTAD. By preparing your business plan. It is normally updated annually and looks ahead for a period of usually three to five years. Also. and sources and uses of funds. Some of the most significant are the following: • Getting an integrated view of your business. markets and clients. but its main purpose is to present the future of an enterprise. it should be complete. outline your market segment. How to Prepare Your Business Plan 3 CHAPTER I THE ABCs OF A BUSINESS PLAN A. B. depending on the type of business and the kind of entity. Committing your plans to paper. marketing strategy. It is a crucial element in any application for funding. the business plan process often leads to the discovery of a competitive advantage or new opportunities as well as deficiencies in the plan. you get an integrated view of all issues regarding your business. ensures that your overall ability to manage the business will improve.Why a business plan? There are many important reasons for drawing up a business plan. organization. You will be able to concentrate your efforts on any deviations from the plan before conditions . financing requirements. shape your pricing strategy and define the competitive conditions under which you must operate in order to succeed. Business planning ensures that all these considerations are consistent and properly harmonized. human resources. What is a business plan? A business plan is a comprehensive. The business plan describes the past and present status of a business. Therefore. it helps you to identify better your target clients. whether to a venture capital organization or any other investment or lending source. factual. written description of the business of an enterprise. production techniques.
Using the business plan in informing business partners and other relevant organizations.4 UNCTAD. • Approval from board of directors/shareholders. type and sources of financing and when it is required. selected business partners. In preparing this manual. • Informing employees. Who reads the business plan? Among the readers of your business plan will most probably be key employees. Determining the amount. C. and current or . • Informing lenders. • Recruiting. Using it in recruiting and introducing new members of the management and staff. it has been assumed that the primary objective of preparing a business plan is to determine the financing requirements of your business and to apply for external funding. • Deriving objectives for employees. How to Prepare Your Business Plan become critical. Deriving from the business plan measures and objectives for units and individuals in the organization (management by objective). Using the business plan in the process of application for funds. Using it as a basis for getting approvals from the company board and shareholders. • Mutual understanding within the management team. • Informing partners. Giving it to banks/investment funds that have financed your business in the past and require periodical information for monitoring purposes. • Determining financial needs and applying for funds.. You will also have time to look ahead and avoid problems before they arise. the board of directors and shareholders.
Such venture capital funds are established and supported primarily by Governments or governmental institutions and have a social and macroeconomic development objective. for example through appointing one of their staff members to the board of directors of your company. infrastructure (land. Some of the most important target readers may well be potential lenders or investors. In some cases. you should be restrictive in distributing copies of it. the bank may require the loan to be covered with 200 per cent or more of their value. you may request the recipient to sign a confidentiality declaration. is that they can finance your business by placing equity without requiring collateral. Give it only to persons who you are confident will not pass on information without your consent. Experience has shown that interest rates demanded by commercial banks in some countries can often be too high to be really supportive of the development of a business. Recent years have seen a rapid increase in the number of private venture capital funds that operate on a commercial basis. The interest rate depends on the prevailing macroeconomic conditions in a country. A particular advantage of such funds. tradable securities. buildings. Which parts of your business plan should be distributed to which persons depends on its confidentiality and on the particular responsibility of the persons concerned. Particular characteristics of these funds are: . If you include in your business plan confidential strategic decisions or secrets. They are normally very risk-conscious and require adequate coverage by means of collateral. in the order of preference of the banks. there are many possible sources you can approach with your business plan. cash accounts. as compared with bank loans. they will expect a good share of the profit and will demand a control function in your business. machinery). precious metals. On the other hand. and they will scrutinize your business until they are convinced that they can get substantial return on their equity at a calculable risk. accounts receivable and inventory. How to Prepare Your Business Plan 5 prospective lenders and investors. If you are looking for outside financing to develop your business.UNCTAD. Commercial banks provide loans to viable businesses on standard market terms and conditions. The most important of these are the following: • Commercial banks. • Private investment funds. This may consist of. If some of these assets are accepted as collateral. but also on the risk the bank attributes to a project. • Development funds. The objective of these funds is to make a profit.
6 UNCTAD. The European Bank for Reconstruction and Development (EBRD). if you address yourself to such a fund you have to cover these issues well in your business plan. Côte d´Ivoire. Among the most prominent multilateral development institutions are: The International Finance Corporation (IFC). They exit when the business is financially self-sufficient. The African Development Bank (ADB). etc. are only ready to finance a project if the business plan shows the viability and profitability of the business. They participate in the business only for a limited period of time. United States. Their philosophy and their objective are similar to those of the development funds mentioned above. . like all other funding institutions.). They tend to finance directly large projects (with equity and/or loans) costing $5-10 million or more. Therefore. most development funds. Their common goal is to assist the social and economic development of the regions they cover. located in Washington DC. DC. The Asian Development Bank (ADB). United Kingdom. located in Manila. How to Prepare Your Business Plan They are willing to take more risks than commercial/private venture capital funds. located in Abidjan. They also cover smaller investment projects through intermediaries such as local commercial banks and leasing companies. United States. transferring a substantial amount of know-how. Nevertheless. The share capital of these institutions is held by many Governments. Philippines. located in London. including a strong value-added component. The Inter-American Investment Corporation/Inter-American Development Bank. which is part of the World Bank Group located in Washington. They particularly favour businesses with special social and environmental benefits (creating many jobs. • Multilateral development institutions. being friendly to the environment.
Ultimately. Donors wish their grants to be given only to wellplanned and viable ventures. those employed by the business will assume some of the responsibility in implementing the plan. How to Prepare Your Business Plan 7 • Private investors. implementing a pilot project prior to an investment. the donor will most probably assess your business plan before taking a decision. the planning work and the drafting of the document have to be done by the managers and owners themselves. In a very small company. How to prepare a business plan? 1. and secondly no plan will be implemented successfully unless key employees identify themselves with the targets set and the means committed. Typical examples of applications for such soft loans or grants are for training your personnel. preparing a feasibility study. Firstly. psychological and team-building point of view to involve them at an early stage of the process. Therefore. Quite often they allocate a percentage of their fortunes for start-up or expansion projects. and making environmentalprotection-related improvements. it makes sense from a technical. there may be some possibilities to access government funds that provide soft loans or grants. employees have the best knowledge of the different aspects of the company's operations. • Technical assistance credits/grants. the less the chance that non-viable solutions will be arrived at. Placing money in diverse businesses reduces the overall risk in their investment portfolio. Company employees contributing to the preparation of a business plan are typically: . microeconomic and macroeconomic impact. Their incentive is to get a higher return on investment than on marketable securities or investing in a fund. Nevertheless. Private investors are usually independent and wealthy individuals who are seeking opportunities to put money in promising businesses. even for a grant. They rightly believe that these are the ones that can have a substantial social. contributions have to come from different people.UNCTAD. In larger organizations. Who prepares a business plan? The answer to the question about who contributes to the preparation of a business plan depends very much on the type of business and the structure and size of the entity. The larger the number of management and staff members involved in the preparation of a business plan. Depending upon the type and location of your business. D.
The best skills available within the company should then be used for synthesizing and harmonizing the input provided by the above team members and for producing the actual report. who provide input of central importance for the business plan. and is one of the key figures in talking to investors and lending institutions. • The development and production managers. these persons inform their personnel about the business planning process and ask them to assist by contributing data. works out the financing requirements of the firm. How to Prepare Your Business Plan • The Chief Executive Officer (CEO). This work should not be allocated simply to the least useful member of staff who happens to have time available. who understands best the demand of the market. the prices that they are ready to pay.8 UNCTAD. • The financial manager. Many large entities have highly competent business development managers whose main tasks are to coordinate the business planning process and edit the relevant documents. etc. Most successful ventures prepare a three-to-five year business plan every year. What are the steps in the planning process? A business plan should not be something you prepare once. requirements for new production machinery and equipment. information. This system approach of mobilizing a large part of the organization has the great advantage of stimulating the awareness and motivation of the firm as a whole. Other enterprises do not have adequate internal resources and hire external consultants to guide and facilitate the business planning process. the specific requirements of clients. such as lead times for developing new products. opinions and ideas. personnel needs and raw material requirements. Dynamic planning should be an integral part of managing your business. who should have the main responsibility for supervising the business planning process. then put on a shelf and forget. . who usually puts the financial data of the business plan together. This involves updating last year’s business plan by comparing the planned figures and goals with results achieved and taking into account changes. the moves of competitors. In some ventures. • The marketing and sales manager. its growth potential. 2.
Setting employee objectives 7.UNCTAD. experiences and new ideas. Assessing the situation 2. Getting ready 4. Developing a mission 3. How to Prepare Your Business Plan 9 new information. Monitoring the process . The steps involved in the business planning process are the following: 1. Setting goals 5. Working out the business plan 6.
employees. shareholders and the community as a whole.10 UNCTAD. employees and business partners can be better motivated and support the mission if they know what it is. It states the benefits your business will bring to clients. Developing a mission Before proceeding further you should formulate a clear mission statement for your enterprise. the organization may lose its original raison d’être and its mission may change. A business is often founded on the vision of an individual. partners. It expresses what you want your company to become. Assessing the situation This should be an assessment of how your customers. • Your mission defines what you want to achieve. This should be providing an updated picture of what you are trying to achieve and answering questions such as: . • Your strategy indicates how to get there. Missions are intended to provide a sense of purpose and act as a tool for communicating where the business is heading.. Shareholders. Developing your mission is often the most valuable part of the dynamic planning process since it can change or reconfirm the direction of your business. The mission should be reviewed regularly and if necessary adapted. • Your vision says how you see yourself in the far future. • Your philosophy expresses the values and beliefs of your organization's culture. As the entity grows. competitors and suppliers view your business. A vision shared by all the people concerned with the business is an important factor for its successful development. How to Prepare Your Business Plan a.
Appoint the staff member who will be responsible for coordinating the business planning process and for delivering the final document (business planning project manager) in time. This person should be knowledgeable about the requirements of the readers of the business plan. sometimes at an off-site location has many benefits (getting away from the day-to-day distractions for the purpose of this process). . Getting ready After the mission and the philosophical basis have been defined. How to Prepare Your Business Plan 11 • What business are you in? • What do you do best? • Whose needs do you meet? • What needs do you meet? • What benefits do you generate? Philosophies or values should be included in the written business plan. People are motivated by more than just getting a salary.neutral and independent . The vision. A consistent corporate culture and a good understanding of the entity's direction and values can improve decision-making and staff productivity. Hire one if you do not have a staff member who is available and has the relevant experience and talent in guiding complex business planning processes.can be of value in moderating complex consensus-seeking sessions. Staff may feel better about what they do. Consider the value of an experienced facilitator. c. Very often an external person . Some important matters you need to address when getting ready are: • Appointing a coordinator. They are an important foundation that should be communicated to all levels within your organization and to your outside business partners. mission. • Hiring a facilitator.UNCTAD. you need to start the actual work of preparing the business plan. philosophy and strategy of a firm are usually developed by the top management.
etc. operations and financing targets in such a way as to enable the enterprise to meet its overall objectives. • In the coming year reduce production costs by 10 per cent through greater automation of production lines.12 UNCTAD. sales.). databases and specialized consultants to be considered. Examples of such goals can be: • Over the next three years increase sales volume by an average of 20 per cent per year by intensifying marketing and sales effort in the neighbouring countries (export). How to Prepare Your Business Plan • Defining tasks. • Identifying team members. competencies. . • By the end of the second planning year launch three new products on the local market. Setting goals for the future development of the business is a prerequisite for the preparation of the business plan. The goals should be time-bound. they can still be of great value in setting the “tune” and “spirit” for further work. realistic and measurable. e. reports on competition. responsibilities and expected contributions/deliverables. Gather and organize all the basic information that will be required from internal and external sources (market surveys. This “matching work” is usually conducted in an iterative process until full consistency of all elements of the business is achieved. development. Setting goals. In addition to information available in-house. Identify the people who will be involved in the process and define their roles. there are valuable sources and tools such as industry associations. d. Although these goals will have to be adjusted in the iterative planning process. the timing of these and the overall schedule for the work. Working out the business plan Working out the business plan basically involves synthesizing and harmonizing your marketing. new technological developments. Define the different tasks and steps involved in the process. manufacturing. • Gathering information.
g. Monitoring the process. The objective of your sales manager is to achieve the sales volumes set in the plan. to meet the schedules planned for bringing into production the new product. The development staff have. Setting employee objectives. ideas Business planning Objectives Communication Employees Source: UNCTAD. How to Prepare Your Business Plan 13 f. Systematic monitoring of the implementation of your plan is a very important factor for the success of your business. among other things. monitoring systems and constant feedback should be integrated to ensure successful implementation of the plan and achievement of its objectives. Figure I. Action plans. If the business plan is . The production manager has to meet the quality standards and production rates anticipated.UNCTAD. Participation in this process can have a profound effect on the way your team members view their role in the enterprise. One of the most important actions after your business plan has been completed is to use it as a basis for setting the objectives of units and individuals in your firm. These individual objectives should be fixed in writing and the results of the work should be monitored and assessed periodically. These should form the basis for the financial compensation of the employee.1. and can have an immediate impact on their performance. Role of the employees in the business planning process Mission Goals Information.
new ideas and useful advice.14 UNCTAD. the plan must be adjusted. there could be good potential for synergies and partner cooperation in one or more of the following fields: • Entering new markets through the network of the partner. . action and keeping the plan up to date. Different types of business plans The structure. How to Prepare Your Business Plan completed and then locked up in a cupboard and forgotten for a year. If key assumptions change. • Transfer of technical and management know-how. The key to maximizing the benefits of dynamic planning lies in implementation. • If the investor is an operating company in a related business sector. • Adding the products of the partner to your list to enlarge your assortment. • If the investor is a government-sponsored fund with development aims. F. • Joint development and production efforts to take advantage of economy of scale effects. E. • An experienced person from the investor organization should be assigned to the supervisory board of your entity. your company may get additional political and lobbying support. etc. He/she could bring to the business new contacts with the market. investors and bankers can provide support such as that described below. such as: • The main objective of the business plan. content and depth of a business plans depends on many factors. your employees will never take business planning seriously again. mid-term corrections are recommended. What is expected from the investor/lender? In addition to contributing funds required to run and further develop the business as envisaged in the business plan. Accordingly.
The brief discussion below gives some examples of relevant factors. etc. storage and so forth become less significant as the product/service mix moves towards a pure service business.. complexity and effort spent in producing the business plan have to be kept within limits. If you are in trade. your business plan should cover standard issues such as development of human resources and marketing. In any case. Issues covered in the business plans of transnational corporations are: Global image promotion strategies. . the size. Expansion through acquisition of other companies/mergers. The mix of products and services to be offered can also affect the content of a plan. The corporate business plan of a transnational corporation with an annual sales volume of several billion dollars does not put emphasis on the same issues as an average medium-size company with an annual turnover of a few million dollars. If you are a sole proprietor of a small business. your business plan will not be dealing with issues such as manufacturing process or investments in machinery. • Type of business/industry. etc. How to Prepare Your Business Plan 15 • The stage of the business (start-up or existing company or spin-off). Personal financial information may be required in order to support your statement that you will be allocating a certain part of your own funds as an investment in the business.UNCTAD. You should also provide specific details regarding any personal non-financial assets that you plan to use in your business. In such a case the business plan has to put emphasis on your own person. • Transnational corporation. • Size of the company. You will put more emphasis on obtaining funds to finance the building up of your procurement and sales network and pre-financing the goods you will be trading with. Issues relating to inventory. For a small business. • Type of business/industry. • Financing situation. perhaps you will be drafting the entire business plan yourself. • Sole ownership.
However. sales. you face a special challenge because you do not have an established track record. your plan should include personal information about all persons involved in the start-up venture (previous occupation. etc. In essence. Sales tactics (these could vary in different continents/countries). resources. Long-term product development (5 to10 years or beyond). If you are just starting.).). social and consumer behaviour. in addition to the standard issues covered in the business plan (production. The plan of a business division (unit) of a large corporation does not differ much from the business plan of an independent company. instead of the historical information that an ongoing business would be able to provide.). etc. business achievements. Staff policy (with perhaps the exception of top management in the different countries.16 UNCTAD.. • Start-up business. your ability to sell yourself is a substitute for the historical information that does not exist. you must concentrate heavily on your ability to sell yourself and the partners that you may have as potentially successful businesspersons. Prediction of long-term trends and developments in demographic. experience. How to Prepare Your Business Plan Analysis of global macroeconomic developments and international politics that are likely to influence the business. Instead. etc. It does not matter whether you are using your business plan in an effort to obtain financing or to convince prospective employees to come to work for you. Therefore. • Divisional business plan. . Government relations and lobbying policies.
Obviously. There are also business plans that do not anticipate significant growth or major investments and therefore are not concerned with the issue of raising additional funds. the two following issues have to be properly covered: That the market of the business sector you are targeting has potential for further growth. As has often been mentioned. you need to put less emphasis on the background of the business (which is . and That your entity. • Regularly continuing business. These documents quantify the results you expect to achieve through your operations. Many firms produce such business plans every year. While your business will probably involve certain expenses that are unique to your industry. Regulatory charges (licensing. In such cases. etc. If you are not seeking new money but only intend to keep your present financiers informed. you also need to provide projected profit and loss statements and a cash flow plan.). is well positioned to win a substantial share of this market. Be sure to include any start-up costs that will be incurred prior to the opening of your business. in such business plans. do not forget some of the more common start-up expenses such as: Professional fees (legal or accounting). How to Prepare Your Business Plan 17 As is the case of an established business. less emphasis is put on justifying the market potential to accommodate growth. company registration costs.UNCTAD. If your business plan is produced with the main aim of raising finance to expand your business. on the basis of its history and competitive strengths. • Major expansion of existing business. Market study. one of the primary purposes of producing a business plan is to inform your lenders and investors. • Financing stage. Deposits for rented space. business plans are produced to inform or get approval from the decision-making bodies and existing investors and/or the team of managers write themselves in order to reach a common understanding of their goals and to determine their future priorities and activities.
18 UNCTAD. obviously this will reflect on the project as well. However. Your business plan should be concentrating on the new specific business you are planning. it is important to consider some basic issues regarding its format and presentation. • The cover. Format and organization of a business plan Before discussing the content (substance) of a business plan. Perhaps you are drawing up a business plan not for the entire business of your entity. However. but something as simple as a cover page on good-quality paper may attract their attention (and thus ensure that they give higher priority to the business plan). The cover of the document is often the first impression of a business that any interested parties or investors get. Financiers receive numerous business plans every week. but to emphasize more new developments in the business. then there are a number of points that require special attention. If the plan has to look professional and to be a useful tool. Your cover page is also a way to make your business plan noticed. • Specific project. Starting a new business unit for a set of new products or services. If your company has financial difficulties. G. but only for an isolated one-time investment project such as: Opening a subsidiary/profit centre in a specific country abroad. For such business plans you need only to provide general information about the entire group. The purpose of a cover page is to tell readers what they are about to read and how to reach the author. How to Prepare Your Business Plan already known). as discussed below. if you are approaching new lenders/investors (so-called second and third round and/or the stock market). Your cover should bear the words "Business Plan" and should include: The legal name of the business. lenders or investors will be interested in having a wider picture of your company’s finances in order to assess the overall financial risks. your plan has to contain a more detailed description of the background of your business (including markets and products). .
These are useful to readers for noting their questions and comments. slogan or other identifying graphic or text. Print the plan on good-quality paper. the cover page is the place to put it. and the period it covers.UNCTAD. How to Prepare Your Business Plan 19 The entity's logo. Building an identity is vital if you want people to recognize and remember your business. The address.). Be sure to list headings for major sections as well as for important subsections. If you have not considered these basic marketing tools. If you have prepared multiple copies of your business plan. reconsider the length of the entries. Other contact information. The telephone number. If your table of contents is more than one page long. and colour contrasts should be pleasant to the eye. The fonts used should be easily readable. Print on one side of the paper only. Maintain reasonably wide margins. • Table of contents. . you are advised to do so. if any. Be sure to include identifying information for the business and to name the person who should be contacted regarding the plan. • Fonts. Use a typeface that is easy to read and a font size that is large enough to prevent eye strain. The cover should be attractive and look professional. Your table of contents provides readers with a quick and easy way to find individual sections in the plan. • Paper. Any nice graphic or photograph could make it look even more appealing. • Contact person. The fax number. (If you have spent time and effort on a company logo. This may require tables with financial projections to be spread over several pages in order to maintain legibility. The e-mail address and website (Internet address) if applicable. • Margins. you might also put a copy number on the cover page to ensure control of distribution. the length of your plan and the number of documents you have attached. The date of preparation or modification of the document. Optional: a notice advising the reader that the plan is confidential.
• Samples. It is worth while having one or two persons to read and check the text and figures again. and be sure that these numbers are correct in the table of contents. Include in the appendix samples of advertisements. embossing etc. How to Prepare Your Business Plan • Terms and acronyms. Keep the plan short and concise. Do not go overboard on expensive binders. Some important criteria and considerations in deciding about the timespan to be planned for are set out below. If your business uses specialized terminology or acronyms. use them sparingly and be sure that you define any terms that someone outside your area of expertise would not know. • Size of document. statistics show that most entities tend to produce business plans projecting from three to five years.use them. H. • Binding. Bind the document so that it lies flat when opened. binding. There are entities planning for only one year. Modern word-processing software provides effective spelling and grammar checking tools . marketing material and any other information that aids the presentation of your plan. • Editing. Planning period One of your first questions would probably be when starting the planning work: “For what period of time should the business plan be prepared?” There is no straight answer to this question. The optimum planning period depends on the type of business and kind of company. Limit the inclusion of extraneous material. • Overall quality of presentation. • Page numbers. Be certain to edit the document carefully. Number the pages. Spelling mistakes and grammatical errors do not make a good impression.20 UNCTAD. if required. But not let it look cheap or sloppy. You can always provide additional detail in an appendix. According the form of the plan more importance than its substance can raise doubts among those reading it. but there are also entities planning for 10 years or more. . However.
• Management fluctuation. if you are planning to lease a farm and equipment to grow tomatoes. A few months after you have leased the farm and planted the tomatoes. This means that your business plan should cover a total of four years. Management fluctuation in an average company varies between 10 and 15 per cent per year. planning periods of 20 to 30 years are often necessary for such businesses. more than half of the managers will have changed. you expect probably to have a net loss for the first one or two years. Maximum output is reached when they are about 10 years old. you are in business earlier. It is important that future managers contribute with their own ideas to the planning of the business for their period of time. On the other hand. it means that. If in your company the turnover is about that rate. Therefore. The appropriate business plan period would also depend on the time scale required in order to develop the infrastructure needed for the business. Therefore. • Infrastructure development (project) period. Rubber trees are usually ready for latex production when they are about six or seven years old. In such a case. Projects with typically long planning periods are infrastructure projects. At the other extreme are businesses that are quickly set in motion and do not require major investments in infrastructure. It is psychologically important that your lender or investor sees at least two consecutive years of profit at the end of which dividends can possibly be paid. and the depreciation of capital expenditure must be spread over a long period. your business plan should go beyond the break-even point and also cover at least two profit-making years. If you are starting a new business or planning a major expansion of your existing business. On the other hand. you can bring the produce to the market and generate cash. Power stations. planting of rubber trees and production of latex. motorways and the like take a long time to construct and require substantial investment. you may be able to plan for a longer period of time. In such a case it does not make sense to plan for any period beyond that. How to Prepare Your Business Plan 21 • Break-even point. you should be thinking of a time frame of at least 10 to 15 years. If the business you are planning is the acquisition of land.UNCTAD. if you are in a family business or if the management is a small team of partners committed to the firm. in this case a planning period of between one and three years may be sufficient. your only . within four years. A typical example is the trade business. If you are an intermediate in exporting textile garments.
1. which was one of the largest in the world at the time. Box I. In such a case. which was to deliver the much-needed raw material. Most business plans show growth of the business over time. Other elements of the plan were the huge Tchelyabinsk agricultural machinery plant and the Dnepropetrovsk hydropower station. energy and heavy machinery production. As a consequence. The "flag ship" of industrialization was the colossal Magnitogorsk iron and steel plant. This national industrialization programme formed the central part of the overall economic plan. output and other industrial achievements at the end of the planning period. In this period. Thus. many Western enterprises adopted the habit of planning their businesses on a five-year basis. These came to be known as "five-year plans". the industrial capacity of the country was in a dire state and far behind that of Western Europe and the United States. the rate of growth of a company depends on the time factor required for making itself or its .3 billion of which was allocated to heavy industry. The entire economic development programme of that country was based on consecutive and centrally planned five-year cycles. you do not necessarily need a business plan for more than a couple of years. 23. You can engage a transportation company to deliver the products directly from your supplier to your buyer and thus you do not even need storage space. The completion period for Magnitogorsk and all peripheral and associated industries was forecast to be about five years. At the end of the revolution. The time frame of the first plan (1928-1932) was chosen so as to include start-up. An important assumption is that the number of buyers will be increasing as the firm becomes better known in the market. This five-year rhythm was adopted later by other socialist Governments. How to Prepare Your Business Plan infrastructure may be a small office.22 UNCTAD. Why did the Soviet leadership choose a five-year cycle? The explanation goes back to the first five-year plan for the years 1928-1932. • Market/client development period. It was during the mid-1920s that the Soviet leaders drafted an ambitious industrialization plan at the core of which was steel. it became customary to plan the development of the Soviet economy on the basis of five-year plans. Source: UNCTAD. Where did the habit of five-year planning originate? The former Soviet Union offers an interesting example of how planning periods are determined by the time scale required to complete infrastructure projects. Furthermore.9 billion roubles was invested in the economy. a total of 64.
people passing in front of your shop (most of them while commuting every day) will very soon discover the appetizing sandwiches in the window. This does not mean that somebody has to plan in detail month by month. But if you are setting up a small firm to provide services in relation to Internet access. • Macroeconomic stability. There can be a danger of more competitors coming into the market but no threat of product substitution. you may find that it would take five to eight years for you to acquire a reputation and for the sales curve to begin to flatten. you can be almost sure that for many years there will be no radical change in the product or the way it is produced. in the case of the gallery. inflation and interest rates over the past five years have been stable (varying only within a band of a “few” per cent). Not only is this market completely open for any competitor to enter without a major investment. you can reasonably plan for a period of another five years. word of mouth plays an important role. Technologies have life cycles. you may need to plan the business for a longer period of time than in the case of the fast food shop. it takes a great deal of time for art lovers from the region to discover your gallery. • Product technology. Here.UNCTAD. In the first case. Consequently. If. The business plan period would also depend upon the type of product. on the other hand. but also technological developments occur so rapidly that projections beyond two to three years would not be sensible. these parameters vary significantly and there is no reason to believe that a more stable and predictable situation can be reached. In the second case. you can afford to make financial projections for a longer period of time. How to Prepare Your Business Plan 23 products known. Average period As a general practice. familiarize themselves with the art you are selling and decide to buy. Therefore. from the product and technology point of view. If you plan an art gallery for selling paintings and sculptures. you may find that you achieve the maximum amount of sales within a few months. you can reasonably plan the business for five years or more. If. If you are operating in an environment of stable and easily predictable macroeconomic conditions. or week . for an "average" business a four-year plan is reasonable. for example. there is no sense in making financial projections over a period longer than two to three years. if you establish a fast food shop in the main passage of the central train station. you cannot be sure how your business will look after two or three years. But. If you consider setting up a facility for producing cotton T-shirts or blue jeans. its technology and the technology used in producing it.
identified opportunities. Executive summary This is arguably the most important single part of your document. I. The above information can be conveniently structured in your business plan in to eight chapters. • The human resources. equipment. etc. the main highlights and the financial resources required. For subsequent years. infrastructure. Content and structure of a business plan After you have considered the purpose of your business plan and have done the necessary background preparation. It provides a high-level overview of the purpose of the business plan.24 UNCTAD. you have to make some assumptions about how sales and costs are expected to develop. For the first year you may have to plan (budget) on the basis of actual costs (actual salaries.) and most probable sales (confirmed orders. as follows: 1. it is time to consider the actual elements that you will include in the written document. the products and/or services you will provide and the position of your competitors. The cash flow that is tracked monthly during the first year of operation may be projected by quarter in the second year. organizational and administrative processes you will apply. raw material and financial resources you need in order achieve your goal in business. How to Prepare Your Business Plan by week. This should contain five types of information as follows: • The mission of your business and the objectives you want to achieve. and annually in the third and fourth years. • The technical. • Your targeted markets and clients. The most usual practice is to update the business plan on a yearly basis. The level of detail will decrease as your plan extends further into the future. etc. • The qualitative and quantitative results you expect to achieve.). . rent. what is going to happen over the next 48 months.
manufacturing. Business operations and organization Location and premises. key data. . Financial planning Financial history (financial statements). competition. social compliance. history. production process. order processing/inventory control. environmental risks. constitution/ownership and management. Background This is the section that provides summarized entity-specific information. It gives the reader an initial overview of the business before specific details are provided later on. cash flow. Human resources Management (shareholders. and business strategy and vision. project management and management information systems/reporting. describing the business organization. executive/operations management. positioning. research and development. middle management. marketing strategy and projected sales. funding requirements and other supporting information. board of directors. external support services) and personnel. How to Prepare Your Business Plan 25 2. clients. 4. 7. Products and services Product description and history. and environmental and social factors Approvals and licensing requirements. principal products and customers. 8.UNCTAD. balance sheet and important ratios. marketing and selling methodology. Markets and clients Market characteristics. costing and pricing. product attributes. 5. distribution. location and premises. company structure/organization. projected income statements. quality assurance and control. 6. development and social benefits. Legal framework. sourcing and intellectual property. 3.
Other relevant and important information. . How to Prepare Your Business Plan Appendices Product literature.26 UNCTAD. But do not feel constrained to follow this format exactly if another way makes more sense because of the specifics of your business. Historical financial statements and auditor’s reports. Legal documents (for example. company registration). Market research. Asset valuations. The following chapters in this manual discuss criteria and considerations that may be of use to you when preparing the above-mentioned chapters of your business plan. Curriculum vitae of key management persons. The above chapters are presented in the order in which they usually appear in a typical business plan.
How to Prepare Your Business Plan 27 PART TWO BASIC ELEMENTS OF A BUSINESS PLAN .UNCTAD.
28 UNCTAD. How to Prepare Your Business Plan .
Therefore. and should take only a few minutes to read. • Polish your executive summary. • Even though your executive summary is the first part of your plan. . Not all of these plans are reviewed in depth. It is what most readers will read first.UNCTAD. thus greatly enhancing the chances of obtaining the financing you are looking for. Numerous business plans are submitted to lenders every week. Ask for their opinion and suggestions. Important points regarding your executive summary are as follows: • It should be between one and three pages long. even though your whole business is well described later on. comprehensive and interesting to read. • The words should be chosen carefully and should be crisp. write it last. Lenders or investors in particular read executive summaries before looking at the rest of a plan in order to determine whether they are interested in this business and want to learn more about it. you may include a few sentences from other important sections. only a small fraction of them are read beyond the executive summary. In fact. Have several people read it . a short summary highlighting the key points of your business plan helps to persuade the reader to study the complete document. • In drafting your executive summary.both those who know your business and those who do not. The statements in the summary should be consistent with the information and wording in other parts of the business plan. How to Prepare Your Business Plan 29 CHAPTER II EXECUTIVE SUMMARY The executive summary is probably the most significant part of the entire business plan.
However. . Purpose of the business plan 2. Highlights 3. • To raise new capital from outside investors or lenders (or to inform and assure present investors or lenders about the progress of the business they have financed). When writing your business plan you may have various objectives in mind. Purpose of the business plan This is a short section stating the main purpose for developing and presenting your business plan.30 UNCTAD. The readers you are targeting could also be interested in different aspects. How to Prepare Your Business Plan The contents of the executive summary can be divided into three parts as described below: 1. Financial requirements A. the basic objectives of your business plan that you probably need to mention are threefold: • To ensure for yourself the viability of the business you are planning to start (or expand or simply continue the same way).
UNCTAD. How to Prepare Your Business Plan 31 • To establish the basis for developing a detailed plan of activities..) • Markets and clients What is your primary market? (Local? Regional? Export?) What is the size of the market and its growth potential? What is your market share? How will it develop? Who are your most important clients? Who are your main competitors? ..
realistic or pessimistic assumptions? • Borrowing. the second part.. total assets and equity. Financial requirements If one of the main objectives of your business plan is to mobilize additional funds.. What kind of capital stock is offered to investors? (Preference shares? Common shares? Convertible loans? Other?) What is the anticipated return on . How to Prepare Your Business Plan • Financial features This paragraph should include historical and projected key financial data such as revenues.32 UNCTAD. net profit. What type of borrowing do you require? (Overdraft? Term loan?) How and when do you plan to repay the money? What guarantees or collateral are you able to provide? • Equity. It should also include the main assumptions used in forecasting. etc. • Major action plans In this paragraph you should briefly summarize any major action plans you have for the future.
sterilizers. Example of an executive summary Executive summary of NileJam in Egypt The present business plan is established with a view a to a major expansion anticipated by NileJam. These house the following facilities: • A cool storage unit of 4. NileJam specializes in the production and marketing of jams and marmalades. Together with his wife and three relatives he started producing orange jam.). strawberries. The main products are 250 gram glass jars containing processed fruit of the region (oranges. Its mission is to add value to fruits of the region by producing superior-quality jams and marmalades and sell these to national and international markets at competitive prices. • Fruit processing lines (sorting. sugar and the final product. washing.). figs. mangoes. crushing. his daughter Fatima Machfus and his son Ahmed Machfus took over the . This summary highlights the key points of the business plan. The company is located in a small town called El Amriya. Hassan Machfus established NileJam in 1974. evaporators. • The main storage building for keeping the empty jars. How to Prepare Your Business Plan 33 investment? When may investors expect it? What are the exit terms for the investors? D. This town is situated on the western edge of the Nile Delta and about 30 kilometres south of Alexandria along the desert road to Cairo. etc. The infrastructure consists of four connected buildings constructed on a piece of land of two hectares owned by the company. Its objective is twofold: to be used as a basis for developing cooperation with a new business partner in Europe and to seek bank loans to finance investments planned within the foreseeable future. apricots etc.000 cubic metres capacity.UNCTAD. The fruit was bought from neighbouring farms. • Offices and canteen. He delivered the product in 5 or 10 kilogram plastic containers to pastry shops and hotels in Alexandria. peeling. After his retirement in 1999. filling machines. The company employs 220 full-time and 180 part-time (seasonal) staff.
However. mainly as a result of the company's gaining market share from competitors thanks to faster delivery service and better quality.34 UNCTAD. Delicia was given the option of a 20 per cent participation in the equity of NileJam. 10. administration and sales/marketing functions. The total market for exports in the above-mentioned countries is roughly 90 million Egyptian pounds and the share of NileJam is on average about 6 to 7 per cent. which specializes in the supply of food products to hotels and restaurants in the European Union. while Ahmed is in charge of product development and production. The company now has about 10 per cent of the Egyptian market. NileJam is a joint-stock company with a share capital of 5 million Egyptian pounds. The other one third is exported to surrounding Arab countries. Revenues over the past three years have grown steadily at about 25 per cent per year. A recent major success of the company is its agreement with Delicia Foods Inc. Kuwait and Libyan Arab Jamahioiya. particularly Saudi Arabia. the new cooperation requires the following investments: • Construction of two new production lines according to the quality standards and specifications of Delicia (mainly evaporators/concentrators and filling/packaging equipment). according to the recipe of Delicia. About two thirds of the total production is supplied to the Egyptian market and distributed through five chains of food supermarkets. A decision on this option will be made within two years. Under the agreement NileJam is to produce. which is estimated to be worth about 120 million Egyptian pounds. Fatima supervises the finance. Also. This new cooperation is expected to contribute substantially to the growth of revenues and profitability. . under the brand name and.0. The corresponding net profit margin was 9. Fatima and Ahmed each hold 50 per cent of the shares. Net profits are expected to increase gradually to 15 per cent by the end of the third year. NileJam has an exclusive agreement with a single distributor.0 and 10. How to Prepare Your Business Plan business. Last year’s total sales were 18 million Egyptian pounds. Financial projections are showing Nilejam´s a sustainable growth of 30 per cent over the next three years.5 per cent respectively. For each of these countries. They are jointly responsible for the executive management of the firm. of Denmark. individual portions of jam (30 gram containers). Today.
The fixed assets of NileJam.5 million euro and 3 million Egyptian pounds.000 cubic metres. Therefore. with an estimated value of 9 million Egyptian pounds (including land. buildings and equipment). How to Prepare Your Business Plan 35 • Expansion of the existing cool storage capacity by another 2. . The owners of NileJam are prepared to contribute with a shareholders' loan of 2 million Egyptian pounds. are offered as collateral for the loan. the external financing required is 1. Delicia has agreed to provide a loan of 0. These funds are to be available on 1 January of the coming year.UNCTAD. The assets of NileJam are unencumbered and the company has no debts at the present time.5 million euro. The interest rate assumed in the financial projections is 8 per cent for the euro and 12 per cent for the Egyptian pound loan..
This will be a useful preparation before the details are set out later. this section should briefly describe: • Your most important products or services. Main products. A. how it started. How to Prepare Your Business Plan 36 CHAPTER III BACKGROUND This section of your business plan may consist of a few pages of background information that is specific to your particular business. • Your present and future market share. The reader should be given a rapid overview of what your business is.UNCTAD. national. . • The main strengths and weaknesses of your products and services compared with those of your competitors. • The existing and international/export). markets and clients Without going into much detail. • The size of the target markets and their growth potential. The business background section generally covers the topics discussed below. regional. • Their distinguishing features or innovative characteristics. (Consumers? Which demographic category? Businesses? What type of businesses?). • What they look like and how are they used. targeted markets (local. how it developed over the years and where it is heading. You should also briefly describe how the business is organized and the resources and infrastructure required for running it. • Your customers.
• A refrigeration building with a total capacity of 300 cubic metres. Location and premises Later. The open plan offices on the first and second floors accommodate 80 software developers and information technology consultants.UNCTAD. Typical examples of descriptions of a manufacturing entity and of a service provider are given below. The underground floor contains the air-conditioned computer server rooms.600 square metres. The plant consists of four buildings: • A building covering an area of 900 square metres for storing equipment and fruit before processing. . Production of mango concentrate The main assets of the business are a mango tree plantation and a factory for processing the fruit in Burkina Faso. archives. The third floor is split up in to individual offices for the administrative personnel. The factory is situated at the south-eastern corner of the plantation along the north-south road. a special section will describe in detail the location and premises of your business. • An office and a canteen with a total area of 400 square metres. It is located 30 kilometres south of Ouagadougou on the road leading to the border with Ghana. you should give a short summary only. Software development The offices of the company are located in a new three-storey building four kilometres away from the centre of Chennai on the road to the international airport. How to Prepare Your Business Plan 37 B. management and meeting rooms. The company occupies the entire building of 1. material storage rooms and a canteen. In the present section. • A factory housing two fruit-processing lines. 75 per cent of which are planted with fruit-bearing trees. The plantation covers of 80 hectares.
)? . • Number of countries to which you are exporting. • Number of clients (per category). expertise. tons etc. Typical data are: • Number of personnel. revenues) Key data are useful for quickly grasping the size of the business. the board of directors and the management.).UNCTAD. where? • Who are the shareholders and who holds the majority/control of the company? • Who are the key managers? What is their background and what strengths do they bring to the business (experience.. Legal form. • Number of affiliates (domestic. D. etc. ownership and management The human resources section of your business plan should include detailed information about the owners. • Total production (in numbers of products. How to Prepare Your Business Plan 38 C. special abilities. Key data (personnel. foreign). total production. • Annual revenues and profits.
as shown in figure III. it is easier to convince the reader that there are good chances of success in the future. China 35% 35% 30% SBTP . If your company has done well until now.1. If not. How to Prepare Your Business Plan 39 • Do the management and other employees hold shares? If so.Shanghai Bio-Tablets Production Ltd Shanghai. China Source: UNCTAD. you have to have strong arguments to prove the viability of your business. Germ any SPD-Shanghai Pharma Distribution Ltd Shanghai. An organization chart showing the legal and shareholding structure of the business. and where were subsequent ones? . China 100% BioChem Ltd Shanghai. Example: Legal shareholding structure of SBTP Ltd China-EU Development Fund Beijing. unless there have been very unfavourable developments. it has a reasonably good basis for being successful in the future.1. Figure III. E. Particular questions of interest are: • Who started the business and when? • How did the business idea start? • Where was the first domicile. what is their participation? This short section should give potential lenders or investors enough information to understand which forces drive the business and who the decision makers are. Historical development and track record of the business If your company has a long history and a successful track record. China BioChem Ltd Frankfurt. is an attractive feature.UNCTAD.
" G. The objective is to add value to the product locally and to reduce transportation costs and losses. rising transportation costs and greater losses caused by mangoes rotting while waiting to be sold/transported.UNCTAD. production capacities. number of clients. Business strategy and mission In this section you should summarize your business strategy and mission. sales/revenues. The margins have been declining owing to increasing competition. "The new strategy is to build on the plantation site a plant for processing mangoes and producing dried chips. How to Prepare Your Business Plan 40 • What were the original products? How did these develop into the products of today? • What was the growth rate in the light of key data (number of personnel. development unit. General organization/operating units In this section you should elaborate on the main operating units (production unit. marketing and sales. subsidiaries etc.)? • Are there any particular achievements? F." "The mission is that consumers benefit from buying an extraordinarily tasty and healthy product at a reasonable price.) and the relationship and interactions between each of them. equity. etc." "The vision is to become the largest supplier of high-quality dry mango chips to the European markets. Here is a typical example: Production of dry mango chips A company has been producing and exporting mango fruits to Europe for many years. . total assets.
How to Prepare Your Business Plan 41 A diagram shoving the main elements and units of your business.UNCTAD. Marketing and sales R&D Production Distribution Service . will be useful for the reader of the business plan. such as the one below.
how long it lasts. How to Prepare Your Business Plan CHAPTER IV PRODUCTS AND SERVICES In this section of your business plan. A similar issue to discuss is how long the product or service will last and whether you intend to upgrade or replace the product or service at some point in the future. A. emphasizing any distinguishing features that may give you a competitive advantage. Another issue to discuss is whether you expect to sell items on a one-time or infrequent basis. There should be a particular focus on how the product or service will be used.42 UNCTAD. describe your products or services. engineering studies and sales brochures. how it works. elevator suppliers. Where appropriate. if any (as annexes to the business plan).). The following specific information should be included. etc. sketches. include photographs. Product description and history Provide a description of your product in detail. but in terms understandable to persons who are not experts in the field. Some business are interested in product updates or after-sales service almost as much as in selling the initial product or even more (software providers. Explain how it looks. general product specifications. you are probably not going to provide the same service to the same client within a short period of time. what it does. Discuss what market demand your products or services will meet. Go into as much detail as necessary for the reader to have a clear understanding of what you are selling. For example. . diagrams. what variations and options are available. If you are selling cars you expect that repairs and routine maintenance will make a considerable contribution to your business. if you are opening a food supermarket you are going to count on the same customers returning on a regular basis. etc. and outline the plans for future development. But if you are a civil contractor specializing in the installation of roof insulation. or whether repeat sales or after-sales services are an important part of your business.
Travel along the river from Kiev to the Black Sea and then back to Kiev. including visiting cities along the way such as. It includes: • • • • • Air travel from abroad to Kiev. Example 1: Tourist tour through Ukraine on a boat Take as an example a travel office that offers package tours to foreign tourists interested in spending a holiday in Ukraine. Important questions to deal with are: When did the first products in the series enter the market? What were the initial difficulties encountered with the product? What are the features of the new product compared with old designs? B. which illustrate this type of analysis through practical examples. • Air travel from Kiev back to the home country. Dnepropetrovsk. . How to Prepare Your Business Plan 43 If relevant to your business. Two days sightseeing in Kiev. An effective way to present a particular product or service is to show a features/benefits analysis. Consider the following two boxes. The package offered is a two-week boat cruise along the river Dnieper. Product attributes In this section you should concentrate on the features that make your product or service unique and preferable for customers. Two weeks accommodation on the boat. A feature is a specific product attribute or characteristic. compared with renting a car and making the tour individually).UNCTAD. The tourists wish to see as much as possible of this country within the time and budget available to them. a short history of the product should be included for the reader to understand the evolution of your business. Zaporozhye. Odessa and Sevastopol and Yalta in the Crimea. The table below sets out the features/benefits of the programme (for example. A benefit is the advantage a customer or user will derive from the product or service. Daily excursions to the countryside.
service. Learning about history. Boat will be moving mostly during the night and will be anchored during the day when people go on excursions. cabin and meals. excursions. How to Prepare Your Business Plan Features Boat travels along a low-trafficdensity river in an idyllic and serene part of the country. Relaxation. etc. entertainment on board.44 UNCTAD. Excursions are guided by knowledgeable staff who are accommodated on the boat and do this work regularly. Benefits No inconvenience and waste of time through often packing and unpacking personal belongings. Tourist can plan his/her budget with precision. the country's heritage and Cost (and price) effective means of touring. . The package deal includes everything for a lump sum price: air travel. cultural folklore. Tourists will always sleep in the same rooms (cabins) throughout their vacation. Optimal use of time for seeing as much as possible of the country.
in the car disc player and in the portable player. How to Prepare Your Business Plan 45 Example 2: Recordable compact disc for music Take as another example the vinyl compact discs (CDs) for recording music or data. Large amount of data can be compactly stored within a small and light piece of vinyl material.UNCTAD. Flexible and universal in use. The table below gives a features/benefits analysis of such products. . who most probably also has a compatible player. Clear and clean sound with no effects of electrostatic. scratches. CDs do not take much space to store and are convenient to carry around. . etc. Can be used in the home stereo system. dust. Globally standardized product. Features Digital recording and replaying by using a laser beam technology. Benefits Music can be copied and reproduced with practically no losses. Can be given as a present to a friend.
especially potential investors. Product life cycle Each product has a life cycle. Therefore. D. readers of your plan. Be realistic about the effort and the time it will take to develop it. as well as any plans for development of new or related products in the light of changing market needs. it will become obsolete and will have to be abandoned. These points are often underestimated. The first phase of the cycle is development. Sooner or later the product will reach maturity. . will scrutinize your development plan to determine whether you have taken into consideration all issues that could lead to delays or cost overruns. set up the manufacturing line.46 UNCTAD. Describe the plans for future development of the product. and this leads to serious financial difficulties before the product is ready to be sold and bring in cash. How to Prepare Your Business Plan C.1. Describe the current stage of your product or service development and give a clear indication of the effort/cost involved and the time required for completion. The income in such a cycle is shown graphically in figure IV. etc. Research and development In this section you should describe any research and development activities that are required before you launch your product. Then comes the phase of selling the product. build and test the prototype. During this phase the firm has to invest to develop a concept. design the product and the process for producing it.
personal computers and fashion articles. .1.UNCTAD. Many companies start working on the development of a new product as soon as the previous product enters in the market. or in introducing it into the market. the income from the sales of existing products is partly used to finance the development of new products.2. How to Prepare Your Business Plan 47 F ig u re IV . may result in a serious gap in cash flow or/and affect the overall profitability of a business. A typical chain of product cycles is shown in figure IV. Your financial projections will then show how this timing affects the overall cash flow and profitability of your business. In this example. Being too quick or too slow in starting the development of a new product. it is important that your business plan deals with the timing of the cycles of the future generations of products. Almost every year suppliers put new models of such products on the market. or even before. Therefore. Optimum timing of different product cycles is very important for the overall success of a company. Typical examples of products with limited life cycles are cars. .
2. incur costs in developing methodologies and tools. Costing By estimating the cost of production and the directly connected overheads you set up the basis for developing your pricing policy and for preparing the financial plan of your business. T im e E. training their staff and preparing documentation. This budget may include the costs of any fundamental research. for example. The cost of your business is composed of four basic components that need to be briefly discussed in your business plan. C h ain o f p rod u ct cycles S ource: U N C T A D . Be sure to include labour. Development costs are relevant not only for companies making products. How to Prepare Your Business Plan F igu re IV . Service businesses also incur costs in developing their services. product development and design work as well as the costs of producing and testing a prototype. These are explained below. . materials. Costing and pricing 1. Consulting companies. consulting fees. certification costs and the costs of professionals such as attorneys. • Cost of product development.48 UNCTAD.
You can work out the average "cost of goods" for each product by adding all related costs mentioned above and dividing by the number of products produced. Overheads also include variable expenses. This unit cost will be a useful indicator in developing your pricing policy and assessing your competitiveness. When planning costs. a failure to meet industry standards and mistakes occur. Expense categories include marketing. sales and overheads. • Cost of goods. the cost of goods is the cost incurred in the production of the products. which remain constant regardless of how much business your company does. For a manufacturing company. the cost of goods includes the purchase of inventory and associated costs such as transportation and insurance. In such a case. . • Operating expenses. In such a case those costs can be treated as any other investment of the company (for example. When working out the costs of your goods. In many cases regulations allow for the costs of developing a product or a service to be entered on the asset side of the balance sheet. For a retail or wholesale business. How to Prepare Your Business Plan 49 Design and development costs expected in the future are often underestimated. such as travel expenses. The depreciation period is dependent on the life cycle of the product developed as well as on the tax regulations. Overheads include fixed administrative expenses such as management and secretariat. be alert in identifying any measure that can lower your costs. also provide a contingency plan for what will happen to costs if problems such as delays. equipment leases. To establish the total of your operating expenses. the purchase of machinery and equipment) and thus be depreciated over a period of time. Also. Such problems are common. the costs included are those for materials. you add up all the expenses incurred in running your business. supply of electricity and office material supplies. labour and overheads related specifically to product manufacturing.UNCTAD. the real costs of past development work are often neglected and not fully included in the price of a product.
The value that your product brings to your clients is the primary factor determining the price they are ready to pay. As mentioned earlier.50 UNCTAD. Buyer's standpoint The buyer’s price acceptance will depend upon three main factors: • Value. Pricing When establishing your price policy. part or the whole of the development costs (depending on the stance of the tax authorities) can be entered on the asset side of the balance sheet and then depreciated over a period of time. Suppose you are selling a specific electronic component to a supplier of complete systems. This component part would be of great value to your client if it forms a crucial part for the operation of the entire system and if his/her business is a profitable one. How to Prepare Your Business Plan • Depreciation and interest on capital. The examples below illustrate some types of product values.. This includes the depreciation of the equipment and infrastructure that are required in order to operate your business. a. a good balance of these two considerations has to be found. 2. . The interest expense for any loans needed to finance equipment or working capital is also included in this category.
Obviously.e. How to Prepare Your Business Plan 51 The value of a consumer product can often be measured by how much it contributes to cover basic or important needs of daily life. and although your clients can afford to pay the price. Aesthetic and psychological factors can also play an important role. some people are prepared to pay huge sums of money for a piece of art (say a painting) for only one simple reason: they just like it very much. this piece of art is of great value to them. The competitive choice in the market place is an important mechanism that keeps prices under control. For example. • Competitive choices in the market place. if they can afford it and if the price is competitive. Consequently. Your target clients are those who will ask for your products.UNCTAD. People will buy it if it is of value to them. • Affordability. Some products can also be of great value to clients even if they do not meet a primary or practical need in their daily life.. can they include the price of your product or service in the overall price they are charging their clients without being too expensive themselves? The above consideration is also important in differentiating between need and demand in the market. If your product fails to satisfy one of these three conditions you will probably not sell it. Although your product may be good value. those who need them but can also pay for them. . an ordinary pharmaceutical product (such as an aspirin) or a basic food product (say a loaf of bread) can often be of immense value to people when they need it. For example. Your pricing policy should consider all three criteria discussed above if you are to be successful in selling your product. before fixing your own prices you have to examine the products and prices of your competitors. i. you can be sure that they will buy it from elsewhere if it is cheaper there.
Your forecast is as follows: If you set the price of a bike at $310. people in town were buying their bikes in the nearest. a friend of yours. • Then you estimate the costs of production for the different options. You will be the only supplier in town. Your market is your home town with a population of 25. You will be selling them directly to the end users from the shop of your small factory.52 UNCTAD. With option 2. maximizing the volume of sales or maximizing the margin per unit sold. • Together with a marketing consultant.000 inhabitants. Seller's point of view From the seller's point of view. For $400 you could sell 160 per year. or they may make the extra effort and go to buy it cheaper in the neighbouring city. Then. there could be various policy options in setting the price. you have to make a strategic decision and set a price that serves your plans better: . and also because of economies of scale in your overhead expenses. How to Prepare Your Business Plan b. Until now. some people may not buy a bike at all. you have surveyed the characteristics of your target market and analysed the buying behaviour of your potential clients. You came to the conclusion that the number of bikes you may expect to sell will depend upon the price you fix for each bike. you make your overall calculation as shown in table IV. you can maximize profit. you could expect to sell 260 bikes per year. larger city. The above options can be demonstrated by a simple example: • Assume that you are planning to set up a small business assembling mountain bikes. and with option 3. wheels and brakes.1 and you discover the following: With price option 1. Important options are maximizing total profit. Now. you can maximize the margin for each bike you sell. For $350 you could sell 210 per year. The cost per unit will be decreasing with increasing production because for bigger orders you will be getting better prices from your suppliers for components such as frames. Faced with the higher price. you can maximize the overall sales volume.
your decision is also justifiable.1. How to Prepare Your Business Plan 53 • If you wish to gain more clients. Figure IV. • If you choose option 2. . but not necessarily to expand the business. In this way you are also establishing a reputation as a supplier with reasonable prices. It is the preferable option if you are looking to maximize net profits in the foreseeable future. neither sales nor profit are maximized. • With option 3. but you get the best margin for each bike sold. There are not many advantages with this option.UNCTAD. option 1 is perhaps the most appropriate. Comparison of different pricing options Dollar Expected Price per Sales unit (No..3 gives an overview of all considerations discussed above in fixing the price of your product or service. Table IV. except that you have less work to do in managing the business and can still make a reasonable profit. become known quicker in the market and expand the business by introducing more products later on.
operating expenses .54 UNCTAD.development costs . The method for setting the price of your product Define your product Estimate your costs: . . How to Prepare Your Business Plan Figure IV.3.cost of goods .
The description of the process could be as follows: • Catching the fish with a fleet of four fishing boats (200 tons each) by trawling nets through the 400 kilometres long lake. Therefore. Production process Most investors will provide money only for a business that they understand. • The packs are frozen by passing them for 10 minutes through a shockfreezing machine of the “Antarctic” type (maximum capacity 1. the fish packs are quality controlled and a label including the price is attached to them. • Transporting the fish from the harbour to the near by factory in three refrigerated trucks (eight tons each). filleted and vacuum-packed in plastic bags.2 contain examples. Example: fish processing As an example. In the written business plan you only need to state the costs and prices of your products. How to Prepare Your Business Plan 55 The above considerations may be of use in establishing your expected costs and developing your pricing policy. describe the process of delivering the service. processing and selling frozen fish to supermarket chains abroad. Boxes IV.8 tons per hour). starting with the preparation of the raw materials and finishing with the last stage of making your product ready to be sold. • At the end of the process line. . assume a business of catching. Each bag contains one kilogram of fish fillet.1 and IV. giving a breakdown of the main elements and summarizing the key assumptions and methods you have applied. With a service company.UNCTAD. This work is done by 40 people working along both sides of a 25 metres long process line. F. • The fish is manually washed. explain to the reader the different stages of the production of your product. Box IV.1.
Example: executive search As a service example take the search for and selection of executive personnel. Source: UNCTAD. • Further shortlisting through interviews. Source: UNCTAD. . • Pre-selecting candidates on the basis of their credentials. Part of your production process discussion should give a justification of the make-or-buy strategy for the different elements of your product. This should also apply if you are in a service business. A make-or-buy strategy deals with the issue of whether you will manufacture all components of your product in-house. or buy some specific components from outside and integrate them into the final product. The boxes are maintained at a constant temperature of minus 18 degrees Celsius. you might decide to engage an administration service firm to do your invoicing. • Presenting two to three candidates to the client and providing advice in the final selection. This may increase profits by enabling you and your partners to spend more time on money-generating activities.2. Then they are placed in the main deep freezer of the factory until delivery. Box IV. This process would most probably involve the following: • Establishing the job profile together with the client.56 UNCTAD. • Design of the campaign. How to Prepare Your Business Plan • The frozen products are placed manually in cardboard boxes with a capacity of 12 kilograms each. If you are starting a business developing and selling software. • Search via a confidential network and/or the media. accounting and other logistic tasks (buy)..
How to Prepare Your Business Plan 61 B. substitution danger and client loyalty. sex. population shifts and changing customer needs.UNCTAD. This should be a description of your target market. • Market size. company size. Friendly competitors. innovation potential of the industry. Chambers of commerce and industry associations. occupation. Clearly state the sources and assumptions used and try to be realistic in the estimates. Support any growth estimates with factors such as industry trends. Specialized market survey consultants. using lifestyle. business organization and other characteristics to describe the consumers or company clients likely to buy your product or service. susceptibility to recession. Do not overstate either the size of the market or the potential share you expect to get. otherwise the credibility of the entire business plan will be in question. age. geography. You should also include comments about any special features of your target market. possible sources are: Government statistics bureaux. government policy. There are many sources of information to tap in creating a complete picture of your market. medium and long term. In addition to information you yourself have gathered over time. Here you should summarize particulars regarding the current size of your target market and its growth potential in the short. new technological developments. such as industry profitability. socio-economic trends. Data bases accessible through the Internet. Market characteristics In this section you should cover two main aspects: • Market characteristics. . Commercial banks (these can sometimes be very knowledgeable and frank about the market in their region).
naming the companies and their trade marks. C. their . A description of the main competitors.. if you are in the business of delivering office materials to companies. you should provide the following: • Description of competitors. Presenting your business in the landscape of its competitors shows that you understand your industry and are prepared to cope with some of the challenges to your company's success. In this section. Competition This section indicates where your products or services fit in the competitive environment of the market. their size and locations. How to Prepare Your Business Plan Remember to cite all sources for your data.62 UNCTAD. quality and service (are they primarily cost. Particular issues to be covered are: • Who they are? • Where are they located? • Why do they buy? • When and under what circumstances do they buy? What types of concerns do they have? • What are their expectations concerning price. you may not want to target service companies with fewer than 20 employees or manufacturing companies with fewer than 100 employees. D. For example.
If this is the case. and how their products/services compare with yours in price. take care in combining the above features. However.UNCTAD. you will successfully differentiate yourself from most of the competition. It may also be useful to describe briefly which companies in your sector or associated fields you do not consider to be competitors. image. marketing. production capability. Describe also how your competitors could possibly react to your strategy. How to Prepare Your Business Plan 63 annual sales and their market share. • Those whom you do not consider to be competitors. But do not make the mistake of saying that you can provide . You can say that you are providing products of very good quality at reasonable prices. Where possible. • Relative strengths and weaknesses. technology. you will have to dispel that misunderstanding by explaining why these businesses are not in competition with you.. E. quality and other respects. The reader of your business plan may misunderstand who your competitors are. assess the strengths and weaknesses of the competition in areas such as management. distribution networks. Positioning How do you want to position yourself in the market? What do you want your identity to be? How do you want your clients. If you think that there are competitors a share of whose business you can capture. financial resources and cost/price advantages. explain why you can do it better and how you will do it.
Not many people will believe that. The image it acquired in the end was summed up in the words: “Still expensive but not necessary of best quality”. The position you choose will form the basic element of your image promotion. In trying to use the excellent brand name to penetrate the mass-product segment it confused the market. • European shoe manufacturer. Many companies have attempted to include in their portfolio products of different qualities (price levels) and thus target different segments of the market. A shoe manufacturer of traditionally highquality/high-price (niche market shoes) attempted to expand the business by starting production also of medium-quality/medium-price shoes under the same brand. the introduction of the latter did not damage the image of the firm as a supplier of luxury pens. low-price and reliable cars. it started more recently also to produce low-price plastic pens. This has been done successfully. Caran d’Ache was for many decades a supplier of expensive gold-plated pens.64 UNCTAD. but some have failed. it started also producing models to cover the luxury/high-price segment. Some have been very successful. important questions to be examined are: • What are the chances of the market accepting your new product? • What is the potential for damaging the image of existing products? . At a later stage. Toyota was known for many years as a supplier of simple. In an effort to diversify and expand its business. The good brand name of the luxury product helped in penetrating the market for the cheaper product. The following are typical examples: • Japanese car manufacturer. If you are planning to expand your business by introducing new products of a different quality/price level. Furthermore. The lower quality of the cheaper products damaged its image as a supplier of exclusive shoes. With these features it penetrated the world markets and became one of the largest mass-production suppliers. This was done successfully. • European pen manufacturer. How to Prepare Your Business Plan best-quality products at the lowest price and that you are also able to provide the best service in the market. advertising and overall marketing campaign.. Step 2: Rate the features of your target market by using the criteria listed in table V. This could give you interesting hints for developing your business strategy and positioning yourself in the market. The average at the bottom of the table gives an overall rating of the attractiveness of your market. The analysis can be done in four steps as follows: Step 1: Rate your business by using the criteria listed in table V. Step 4: Table V. . How to Prepare Your Business Plan 65 • What are pros and cons of introducing the new product under a new brand name? F. Step 3: Mark in table V.2. This exercise can be repeated for different business segments or products of your firm. it is perhaps useful to rate your business through a simple portfolio analysis. Although not every business plan includes a portfolio analysis.4 may give you some indications and suggestions about possible measures you might choose to undertake.3 the position of your firm in the market (by using as coordinates the results from step 1 and step 2).1. You can also try to indicate the position of some of your competitors in this diagram. Market strategy After you have examined the attractiveness of your market and you have examined your competition.UNCTAD.
Branch profitability 4. . How to Prepare Your Business Plan Table V. Management 7.1. Recession susceptibility 7. Security of supply (materials/spare parts) 10. Own brands.2. Analysis of competitive advantages Competitive advantages/ success criteria 1. Market size 2. Product/service quality 4. Market growth 3. patents. Substitution danger 8. Innovation potential of the industry 5. Regulatory/public opinion risks 1 2 3 4 5 6 7 8 9 << Very negative very positive >> Overall evaluation/summary Source: UNCTAD. Technological know-how 5. Marketing know-how 6. Analysis of market attractiveness Market evaluation criteria 1.66 UNCTAD. Table V. Client loyalty 9. Competition intensity 6. etc. Financial resources 9. Cost structure/cost advantages 3. 10. Market share 2. Location/distribution advantages 8. Spare capacity 1 2 3 4 5 6 7 8 9 << Competition is stronger we are stronger >> Overall evaluation/summary Source: UNCTAD.
3. Position in the market 9 Evaluation of market attractiveness 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 Evaluation of competitive advantages Source: UNCTAD.UNCTAD. . How to Prepare Your Business Plan 67 Table V.
etc. quality upgrading. Selective investment and growth Consider in particular building up strengths (management improvements.). human resources. Harvest/diversify Maintain your position and get as much as you can from the market. possibly through the development of new products. new technologies. How to Prepare Your Business Plan Table V. expand geographically etc. Medium Partnership Divest Low Consider joining forces with a partner. networks. Low Medium High Relative competitive advantages Source: UNCTAD. Gradual development Strengthen your competitiveness through incremental improvements (as you earn) and shift emphasis to the most attractive market segments of the business.68 UNCTAD. cost reduction. . perhaps with a strong company interested in entering your type of business/market or you type of clients. perhaps with a company interested in some of the strong features of your company (infrastructure. Specialize in the few products/services that you can do best. location.). Maximize investment and grow Market attractiveness High Partnership Consider joining forces with a partner.). Matrix of strategies Concentrate Concentrate your activities on niches. Selective investment and growth Identify the most attractive growth segments of your market and invest in them (intensify marketing / promotion. etc. Consider diversifying and entering new markets.4.
Your projections derived from this section will be an important input to the financial planning section of your business plan (projected income and cash flow statements). sincere and pragmatic businessperson. Justify your sales projections by explaining the underlying assumptions made.UNCTAD. . the size of your market and the share you expect to get. This should include sales in units and cash for the planning period of your business. being too conservative about the growth of sales will not encourage people to put money in your business. It is therefore recommended that you use "best case". For existing businesses. Projected sales The estimated sales of your business should be based on your assessment of the advantages of your product or service. The first year should be broken down by month or by quarter. Lenders or investors look critically at forecasts of sales since they form the main basis of your income and thus your ability to service your debts and pay dividends. the current client base and client gains anticipated in the foreseeable future form a sound basis for the sales forecast. taking into consideration seasonal effects and variations. Be realistic about your projections in order to maintain your credibility as a serious. "worst case" and "likely" scenarios to create a spread of sales projections. On the other hand. How to Prepare Your Business Plan 69 G. Experienced lenders/investors know that new businesses very seldom experience a sales boom right from the first or second year of operation. whatever is appropriate for your industry.
The way you organize and operate your business is an important factor for your success. most lenders are aware that it needs much more than that to run a profitable business. The sections below discuss some of the most important operational and organizational issues that need to be covered in a business plan. Specific questions to be answered are: . Location and premises 1. despite the superiority of your product and interest in buying it. The same applies if you do not have an appropriate management information system or if the duties and responsibilities of the personnel in your organization are not well defined. a building contractor has to be very well organized in all matters of project planning and control. How to Prepare Your Business Plan CHAPTER VI BUSINESS OPERATIONS AND ORGANIZATION In the previous sections you may have convinced the reader that you have a superior product and that there are sufficient clients that would be willing to buy it at a fair price.70 UNCTAD. you should explain the considerations that made you select the present location of your business. A trader in tropical fruits has to plan carefully storage. it is unlikely that your business will remain profitable for long. However. If you do not have a well-functioning infrastructure in a suitable location and if you do not have an efficient manufacturing and distribution system. For example. A. Location In this part of the business plan. The types of operational and organizational issues you will be facing depend on the type of business you will be operating. transport and distribution.
restaurants. How to Prepare Your Business Plan 71 • Local market. Are raw materials. etc. suppliers of consumables.UNCTAD. shopping facilities.) Is the cost in transportation of raw material and finished products reasonable? Is there any . etc. How do the cost of premises and utility rates compare with those in other areas? Can you get a similar site on more advantageous terms in another area? • Transportation. the owner of a metal processing shop that produced components for foreign toolmakers decided to completely relocate his business. spare parts and other supplies readily available in the region? • Utilities.) • Living conditions. water for industrial use and cooling. The main reason was that a foreign car manufacturer that had recently moved into the area had caused a dramatic rise in salaries. ship. The shop was not able to operate profitably any more in this place. adequate telephone lines. hotels. repair and maintenance workshops. Are the necessary utilities to accommodate the present and future expansion needs of your business available at your location? (Electricity supply. aeroplane. visitors and their families for living and working in the region? (Housing. Can you find in the vicinity skilled managers. schools. rail. Are there the necessary services to support your operations in the region? (Law and accounting offices.) • Cost of premises. components. waste depositories. etc. sink for discharges of effluents. hospitals.) • Material supply. How easily can your location be reached? What means of transportation are available? (Road. etc.) • Supporting services. gas supply. cultural and recreational centres. Are suitable infrastructure and appropriate services available to employees. Is there a market for your products or services in the region? Or have you chosen your location because it is just a suitable place in which to produce? • Availability of workers. religious centres. specialists or workers whom you need to operate the business? Are there any plans for major industrial development programmes that are likely to strongly compete with your business for human resources? Do you see any critical limitations in this respect? (In one case.
This is particularly true for those who have their clients in the region where their company is located. but because you will provide your clients with the image of a real discount shop. Transportation costs were not an important consideration at that time. Are there any plans for changes or projects in the region that may affect your business? (New housing complexes.) • Local authorities. etc. expansion of industry. rapid economic growth in the region often has disadvantages for some businesses. Are there any present or foreseeable competing businesses in the immediate neighbourhood? What could be the impact of their presence? • Image. training schemes for employees and attractive conditions for leasing land and buildings? Are the local regulations reasonably flexible? Are procedures for obtaining permits and licences efficient enough? . They will perhaps see only an increase in their production costs. Is your location compatible with the image of your business? Do clients visit your premises? (For example. However. transportation and associated energy expenses started to be an important issue when planning product costs.) • Economic growth. They will not profit from the enhancement of the local buying power.) • Future development. But if you operate a discount (lowbudget) shop for electrical home appliances. The stimulation of the economy will eventually enhance the buying power of their clients. new motorways.72 UNCTAD. Do the local authorities support the development of business in the area? Do they provide any special incentives such as local tax reductions. After the transition to a market economy. if you have a boutique for highquality and expensive jewellery. The result was that some of these businesses with production facilities in remote areas were not commercially viable any more. Is the area showing high economic growth? (Most entrepreneurs wish to see high economic growth in their region. Not because you will pay less rent. which is a phenomenon accompanying economic growth..) Will these changes have beneficial or detrimental effects? • Competition. you would rather be located in a back street. perhaps you should ideally be located in an exclusive street in the centre of the town.
a permit may be required. Did you apply for it? Have you received it? (Never underestimate the time required to obtain a permit.) • Expandability. etc. Are the premises of appropriate size? Can you expand if necessary? (For example. short transport distances. storage space and office infrastructure. appropriate working environment. How to Prepare Your Business Plan 73 • Site accessibility. Particularly critical are greenfield construction projects. Particular issues to be addressed are set out below. They may be aware of cases in which . if you are running a specialized law practice and you are planning to charge your clients the upper-level rates of the market.) • Layout. simpler facilities on the outskirts of the city would be adequate. The lender or investor will carefully check any permit required. acquiring paintings and sculptures. setting up spacious and representative reception and meeting rooms. you are advised to briefly describe in your business plan your premises and their suitability for your business. Are the layout and the architectural design appropriate to performing the daily operations in an efficient way? (Optimum flow of personnel and materials. adequate storage capacity. In some cases permits were in the end not granted at all. Can the site be accessed easily by employees and clients? Is the transport of materials and goods practical? 2.the procedure for obtaining permits have been very slow. getting elegant furniture. But if you are in the software development business and your clients do not visit you regularly in your offices. • Licences. by having the option of renting nearby some more . you may need to have representative offices in the centre of the city. will be an advantage to the development of your business. Does the appearance of the premises match the type of your business and the image you like to give to it? (For example. etc. Premises Your business operations can be performed in an efficient and effective way only if you have the appropriate production facilities.with or without a good reason .UNCTAD.) • Representation. Can the premises be utilized for the planned business? Is any application to the local authorities necessary in order to change the use for which the premises were previously licensed? Will you make any structural alterations? If so. As your lender or investor is certainly aware of this requirement. In such a case.
Lenders are very sensitive on this matter. It is therefore usual that the work of developing the marketing concept and supervising its implementation is placed under the direct responsibility of top management. if you are starting a new business you may not want to invest immediately in real estate. you may be faced with the choice of renting property or buying it now. Will the premises comply with fire. Marketing consists of the following four major elements: 1. General remarks For many companies. Market study Study the market environment and future trends to understand the demand for products or services in your field. health and safety regulations? • Environmental issues. The trends of the local real estate market could have a major impact on your decision. Marketing 1. Do you have proof that the site you are going to buy or lease is environmentally sound and that there is no existing contamination and liabilities from the past? If you are not sure. an environmental survey has to be carried out. .) Or do you have already have to bear the extra costs of renting more space that you may need in the future? • Safety regulations. How to Prepare Your Business Plan space later on. highly effective marketing is the key to success. On the other hand. buying may provide some protection against the risk of escalating rental expenditure. • Buy or rent. Are you planning to buy or to rent the premises? What are the considerations for this decision? (For example.) B. You might also want to see first how your business develops before you enter into more substantial financial commitments. Identify the geographical markets and types of clients to be targeted.74 UNCTAD. in view of other financing priorities. If real estate prices are rising quickly.
The present section concentrates on describing how you plan to promote and advertise your products. 2. When developing your products. 3. when communicating with your clients and when fixing your prices. Important features that your marketing efforts have to define are . Specific objectives are: • Make your product or service known. Selling and distribution concept Select channels for selling and distributing your products or services in the market. presentation/packaging. Product promotion Develop and execute a promotion.UNCTAD. . How to Prepare Your Business Plan 75 2. • Build up its image. you have to keep in mind your marketing concept. advertising and Public Relations campaign to inform the target clients about your products or services and the benefits they can derive from them. etc. An important characteristic of marketing is that elements of it form an integral part in most of your business activities. Promotion and advertising The purpose of your promotion and advertising campaign is to communicate information about your product or service to the market. price.finishing. 4.apart from the technical specifications of the product . It is therefore obvious that marketing elements are to be found in most sections of your business plan. Product development Develop the products demanded by the market.
and have they been professionally trained to sell? Who will define. This section should include a description of all media that you plan to use for advertising (Internet.). If you are employing agencies or outside specialists to assist you in the advertising and Public Relations work. competence and benefits they will provide to the promotion work. Selling is the process for: • Finally convincing your clients to buy it. brochures. The selling section of your business plan has to demonstrate that you are well organized with regard to managing the selling process. coordinate. exhibitions. Who will sell your products. magazines. C. It should also describe your public relations programme. include information about the efforts. radio and TV. trade fairs. • Establishing ways of communicating its attractiveness to your clients. product sheets etc. etc. Selling methodology In marketing you are concerned with: • Assessing the demand for your product. sales/promotional materials (such as brochures and product sheets). monitor and control the overall sales effort? Who will bear the overall responsibility for the sales? . Specific questions to be discussed are the following: • Selling responsibility. it would be an advantage to include some of these as an attachment to your business plan or at least have them available to show when meeting your lender or investor.76 UNCTAD. If you have copies of advertisements. package design. billboards. newspapers. Through such information you will show to the reader that thought has been given to this issue and that the appropriate channels have been chosen for attracting clients to buy the products. direct mailings. etc. How to Prepare Your Business Plan • Show benefits to users.
mailings. What hesitation and resistance do you expect from possible clients? How do you consider encountering them? What arguments would defend your position? What are the unique selling points your salespeople have to emphasize? • Client decisions. How do you plan to train the salespersons? How do you plan to transfer the necessary knowledge of the product to them and enhance their selling skills? (Internal or external training. How much time elapses between your clients becoming aware of your product or service and their decision to buy it. • Targets. cold calling/direct client visits.) • Selling process time. on-thejob training programmes. and finally pay for it? (The answer to this question is an important factor for your cash flow projections and for determining the financing requirements of your company. But if you are an auditor and you want to acquire the financial audit. CDs and technical back-up material.UNCTAD. shops. established sales and distribution networks access to valuable clients. brochures. What selling methods will you apply? For example. How to Prepare Your Business Plan 77 • Selling channels.) • Arguments. have you set for each salesperson or selling method? • Selling aids. describe the benefits of using them. What sales volume and activity targets. What special advantages do they bring to the business? (Lobbying connections.) • Selling methods. What selling aids. telephone selling. you cannot by pass the Chief Information Officer. will you provide to the sellers? Include also details of in-house sales support such as technical service. duration. • Training. etc. types of courses. videos. Who exactly makes the buying decision. such as visits per day. participation in fairs/exhibitions. advertisements and mail ordering.) . such as leaflets. and what other people can influence that decision? How can you approach them? (If you sell office material to companies. etc. Will you be selling directly to your clients? Will you be using sales representatives. you know that the procurement officer is the right person to approach. the Chief Financial Officer is your contact person. distributors or agents? If you will be using third parties for selling. If you want to sell PC hardware and software. market knowledge.
• Handling complaints. If you do not do anything.e. On the one hand. What payment terms and conditions are you proposing to your clients? This issue is of the utmost importance for your cash flow development. Describe how you balance these considerations.78 UNCTAD. for the purpose of improving your cash flow you would like your clients to pay you as soon as possible. the odds are that he will stay with you. Which orders are currently on hand (value. by being alert and informing their colleagues if they see an opportunity. you will probably lose him and you may also lose other clients to whom he is talking. it would be convincing to show these to the lenders or investors concerned. Are there any concrete proposals with a reasonable chance of being accepted by the clients? Vague letters of intent from prospective clients are usually not sufficient to convince investors or lenders about the future viability of the business. to initiate the process of selling another product of your company for which they are not directly responsible? (For example. and from whom? Are there any documents that can prove that there is a pipeline of committed orders? If so. How to Prepare Your Business Plan • Payment terms. • Incentives. On the other hand. i.) D. etc.) or are expected in the immediate future. Manufacturing If you are in the business of manufacturing products. how do you intend to deal with such problems? • Orders on hand.) • Order processing. with a clear division of responsibilities? Do you have the common problem of production personnel complaining that delivery schedules agreed with the client are too short or the prices too low? If so. What incentives do you have in place for motivating salespeople to meet their targets? How does their compensation depend on the amount they sell? How can you motivate your salespeople to cross-sell. you would like to offer to your clients convenient payment terms so that they can continue buying from you. Important issues to be covered are: . How are the orders transferred from the salespeople to the order processing people? Is this transfer smooth. your business plan should include a section on the manufacturing process. What procedures do you envisage for handling customer complaints? (If you take quick action to satisfy a complaining client.
Briefly discuss the worst and the most probable scenarios of production interruption in your factory. You should demonstrate that you have established appropriate logistics for ensuring that your product will . Which resources and services are required in order to keep the manufacturing line running (energy and cooling media. adjustments and manual control of the production line. testing/inspection of the final product. etc. spare parts. How to Prepare Your Business Plan 79 • Make or buy. Provide a rough layout sketch of your manufacturing unit. Begin with the preparation of raw materials and continue to finishing and packaging the end product. What plant and major equipment will you need and what are the main specifications? (Rated capacity.). showing the ground plan and main dimensions of the facility and the arrangement of the main equipment. • Major equipment. Distribution This section should describe the channels and mechanisms by which your product or service will be reaching the end user. sizes.) E. spare capacity. • Resources and services. maintenance service. Which parts of the product do you make yourself and which parts do you purchase? Do you make the final assembly of the product yourself or do you contract it out? • Manufacturing process.) • Layout. What are the critical factors in achieving the required quality of the end product? (Type of production machinery used. etc. etc.UNCTAD.) What measures are you envisaging to ensure the quality of the final product? • • Interruption risks.) Quality factors. etc. What are the probable incidents (machinery breakdown. power consumption. Briefly describe the different stages of the manufacturing process and the flow of materials and goods. engineering support.
you can sell a new type of floor cleaning chemical through door-to-door selling. sharing scheme for income. How to Prepare Your Business Plan reach the clients in time. Are the distribution channels compatible with the image of your product? (For example.) • Impact on quality. but for fine handmade silk carpets you would want to sell through special galleries/boutiques. door-to-door selling. • Image compatibility. price margins by shops. if you distribute perishable goods such as flowers. the company had to stop advertising the ecommerce service for some time until it switched its logistics and restructured its assets (sold supermarket space). Is the quality of the products adequate when they reach the final consumer? For example. Are the distribution channels chosen compatible with your capacity and the structure of production and delivery? Here is an example of a company in the food business. the demand in the supermarkets dropped considerably. However. etc. in perfect condition and in a cost-effective way.80 UNCTAD. what type of agreements do you have with them? (Division of responsibilities. The demand increased so fast that it could not manage the home delivery logistics properly. Hence. mail order. On the other hand. wholesalers. this kind of distribution is not recommendable for high-quality cosmetics. tropical fruits or fresh fish. Then it decided to start selling through electronic commerce (home delivery for orders received via the Internet). Or you can sell machine-made woollen carpets through a supermarket store.) • Intermediaries. for how long? • Compatibility. electronic commerce/Internet etc. Particular questions that will probably be of interest to the lender or investor are the following: • Distribution channels. What are your primary distribution channels? (Retail stores. It has been using chains of supermarkets to sell its products for many decades. which resulted in an ineffective way of utilizing the infrastructure and equipment invested in over many years.) . Is the entire distribution chain under your control or are you using intermediaries such as supermarkets and distribution agents? If the latter is the case..
Your lenders or investors will most probably be interested to know more about it. Particular questions of interest are: • Registering orders. but if you start delivering to clients in another town 50 kilometres away. This part of the chain is critical to the successful development of the business.UNCTAD. How to Prepare Your Business Plan 81 • Costs. Is the packaging of your product suitable for the distribution and transportation channels that you have chosen? Can you be sure that the product reaches the client in a perfect condition? The more stages in the distribution channel and the more loading/unloading. How is a new client order entered into the company system by the sales department? Who takes on the responsibility for delivery in accordance with to the terms and conditions agreed with the client? What are the . An important link between manufacturing and selling is the internal work of your firm in processing the client orders and controlling the inventory of finished products. F. Either you establish a second production unit in this town or you leave the business to somebody else there. Can your products be sold at a price that includes such mark-ups? • Packaging. A basic question that you would be asking yourself is how far you can deliver the pizzas economically. transportation costs. import duties and so forth have to be added. Is the chosen distribution channel cost-effective for the type of products.) Can your product bear the mark-up required by the • Mark-up. A one-kilometre distance is certainly no problem and five kilometres may also be no problem. you are probably not competitive. If the work is done efficiently it ensures the satisfaction of your clients and reduces the costs of your company. quantities and markets that you are targeting? (Suppose that you operate a pizza home delivery business and you produce all the pizzas in one central facility. On top of this. the more robust your packaging has to be. you have described your capability in manufacturing your products and your competence in selling them to the market. Order processing and inventory control In other sections of your business plan. The importer may require another 20-30 per cent. distributors? If you are distributing your products through shops in foreign countries you have to assume that the shops will add a mark-up of say 100 per cent.
the size of the company. An organizational chart is particularly useful in: • Providing evidence to the lender or investor that you have seriously considered the future of your business.82 UNCTAD. divide it in distinct functional units.). What procedures do you apply to monitor whether the client is satisfied with the product or service? • Inventory control. What mechanisms and schemes do you apply to control the inventory of your products? How do you optimize the inventory to ensure that it is not too much (binding cash and occupying a lot of storage space) or too little (reducing flexibility to supply clients fast enough). They enable the reader to quickly grasp the way you plan to structure your business. • Confirming that you have identified the people required for operating the business. Company structure In planning your business you have most probably thought about how you would like to structure the company. G. • Making clear to everybody in or outside the company who is responsible for what. family business etc. the profiles and competences of managers available. They define responsibilities and lines of reporting of middle and higher management. the ownership situation (partner organization. Naming persons in the chart helps to give a sense of reality to your business plan. you should compile an organizational chart and include it in your business plan. Factors that play an important role are the type of business. and the style of management.e. How to Prepare Your Business Plan interfaces and how are the responsibilities split between the salespeople and the people producing the product and delivering it to the client? • Client satisfaction. Organizational charts are very useful pieces of information. If this work has been done. i. There are many different ways to structure a company. . You probably have also identified the head of each of these units. the industry.
These should also meet regularly to discuss and decide about division matters.1. Note: Each box should include the name of the responsible manager and his or her deputy. It consists of three major divisions.UNCTAD. the three division managers and the Chief Executive Officer (CEO) form the higher executive management of the company. . Figure VI. The division manager is the link between middle and higher management. The department managers (middle management) of a division and the responsible division manager form the management of a division. He or she plays an important role in the transfer of information. Typical organization chart of a production company Chief Executive Officer Technical R&D Production Quality control Marketing & sales Marketing Sales Client service Client relations Finance & administration Accounting Human resources Logistics Procurement Information technology Source: UNCTAD. In such an organization. opinions.1 is a typical example of an organization that is often seen in production companies. How to Prepare Your Business Plan 83 Figure VI. suggestions and instructions between the two management levels. This team should meet regularly to discuss and decide on important company issues. Each division consists of a number of departments.
such as developing a new product. the project cannot happen any faster than this. and if so. you may have to demonstrate to your banker or investor that your projects have been thoroughly planned and that you have established schemes for monitoring their progress. . Project management In your business plan you may anticipate the implementation of one or more projects. Each activity on the critical path has to be completed before the next one can begin. Below are some important steps and methods for presenting a plan for such projects. These allow you to record information about the project. There are various cost-effective computer software packages available for drawing up and monitoring project plans. how. establishing a new affiliate abroad or refurbishing your production machinery. For each activity. Therefore. • Assign responsibilities for each activity and for the overall coordination of the project.84 UNCTAD.2. This means that unless the time taken for the different activities can be shortened. The success of your business will depend upon your ability to complete these projects successfully within the budget and according to schedule. • Break the project into small tasks (modules) or clearly defined activities as in figure VI. This path is the longest path through the diagram and indicates the shortest possible period of time for completion of the project. constructing a new building or plant. make changes with relative ease and view project information in various ways. Act immediately if a target is missed or a problem appears. set measurable targets and milestones. • Set up a mechanism for monitoring whether the targets have been met. which shows activities related to the construction of a plant for producing mango concentrate. • Identify the critical path. How to Prepare Your Business Plan H. A project can be anything.
Building painting and finishing works . grass) .Installation of evaporators Commissioning .2.Conceptual design of plant .Engineering .Excavation for building .Contracting/ordering of equipment .Licensing and approvals .Building construction (civil works) .Piping and electrical installation .Detail specifications .Installation of telephone lines .Normal operation = critical path Source: UNCTAD.Site preparation . flowers.Pilot production . .Installation of fruit peeling line .Garden work (trees.Installation of fruit washing/sorting line .System cleaning and flushing .UNCTAD.Functional tests .Installation of water supply and sewer . How to Prepare Your Business Plan 85 Figure VI.Construction of access roads .Installation of power supply lines .Manufacturing equipment by suppliers Construction phase: . Example of a project plan: construction of a plant for production of mango concentrate Activity 1 2 3 4 Months 5 6 7 8 9 10 11 12 Preparation phase .Foundation work for building .
Important questions that need to be briefly answered in this section of your business plan are: • Periodicity. new orders. How to Prepare Your Business Plan I. Status of projects in implementation (in particular.). on-line. proposals rejected. . etc. with projections over the coming months (these are important in confirming that you have sufficient cash to operate the business). Sales (business opportunities identified. etc. Income statement (with breakdown of the revenue and expense sides) and balance sheet (with breakdown of the assets and liabilities). or number and type of clients serviced. It helps you understand of the dynamics of the business and puts you in a good position to guide it in the right direction. Special/unexpected developments/events. What is the content (output) of the MIS reports? Typical reports of special interest to you.) • Content.). depending on the type of business.86 UNCTAD. quarterly. etc. Production output (number and type of products produced. Other information (personnel fluctuation. proposals pending. could be those on the following: Liquidity status. How often will you receive and use the reports produced by your MIS? (Monthly. and production capacity utilized. Your MIS should assist you in monitoring whether your business is developing as anticipated in your business plan. information relevant to cost and schedule control). etc. proposals made. annually. Management information systems/reporting The readers of your business plan are most probably aware that the use of an effective management information system (MIS) is an important requisite for conducting your business successfully. It serves as an early warning system. market indicators. Financial ratios.). It can therefore be expected that lenders or investors may want to see an outline of your MIS.
group discussions. How to Prepare Your Business Plan 87 • Information recipients Who receives reports via the MIS or who has access to them? What kind of information/reports are foreseen for different functions and persons? • Processes/actions. that data are fed into the system in a timely fashion. • Information technology systems. people will lose their motivation to provide the data. information provided is complete and meaningful.) • MIS input/responsibilities.) Experience shows that enforcing the procedures for collecting and feeding the appropriate data into the MIS of a company is one of the most challenging tasks of management. This is particularly true where the data have to be collected throughout the organization. • Persisting in communicating to people the significance of the MIS system. bilateral discussions.UNCTAD. The general tendency is that people who are responsible for providing the information do not give high priority to this task. for example. What processes are used in discussing results and taking actions? (Periodic meetings of the general management. If too much data are required and if their purpose and usefulness are not obvious. • Disseminating MIS output to the people in your organization to whom this information may be useful. Possible improvement measures that often help are: • Reducing the amount of data and information collected to what is really necessary. What kinds of software and hardware are used to process the data and to generate reports? . etc. etc..
skills and experience to achieve the objectives and goals. • Demonstrate that they have the required talents.88 UNCTAD. competence and ethics. Issues such as projections of future market potential. The same will apply if the management presented does not appear to have the required experience. an investor does not have the technical knowledge necessary for judging with confidence the viability of a specific business. there is a common belief that the qualifications of the management are one of the most important criteria for a lender or investor in deciding to invest in a venture. if they believe that the management has the necessary experience. the management section of your business plan should: • Show that the key members of the management team have been identified. regardless of how great the business opportunity appears to be. How to Prepare Your Business Plan CHAPTER VII HUMAN RESOURCES A. For the above reasons. competence and reputation. On the other hand. are available and keen to join the team. It often happens that despite a well-presented business plan. It is also important that the individual skills of the members of your team complement each other and that they can cover jointly all the functions and disciplines necessary for running the business. . product competitiveness or technological trends can often be very difficult for persons not directly involved in the business. Management Most lenders and venture capitalists base their investment decisions mainly on the strength of the company's management. they will be more inclined to finance the business. no serious lender or investor will ever finance a business before the management has been properly examined. In general. However. track record.
Depending upon the structure of a company and the role of its shareholders in the business. etc. the lender will be keen to have more information about your and your partner’s background. In this case. 2. Its role and responsibilities are. for example. management functions and input/support to management are provided by the following groups: • Shareholders. In addition to standard information on personal assets and liabilities. paying particular attention to the private financial situation. Suppose. some lenders or investors may go so far as to require copies of tax declarations. Board of directors The shareholders of the company appoint the board of directors. court cases. records of unpaid debts. • Middle management. How to Prepare Your Business Plan 89 Depending on the structure and type of business. lenders or investors may require more detailed information about their background. among others. to: • Take overall responsibility for the company on behalf of the shareholders. • Executive management. Shareholders In this section you should briefly describe the individuals who own and control your entity (their name. • External support services. . • Board of directors. 1. that you are starting a new entity as a sole owner or together with a few partners and that all of you will be active in the business. • Develop a company strategy. Therefore. the management section of your business plan should present the key persons of these groups as discussed below.UNCTAD. activity/occupation and equity participation) and their involvement in strategic or operational decision-making processes.
good reputation or special knowledge relevant to your business. • Ensure the implementation of an appropriate accounting. search for board members who can provide this know-how. business activity. . How to Prepare Your Business Plan • Ensure the establishment of an appropriate organization. responsibilities and competencies of each individual. It adds credibility to your business since a strong board of directors is always considered to be a valuable asset to a company. financial control and financial planning system. The general practice in many countries is that members of the board are not employed by the entity and are not engaged in the daily business operations. the managers of many small and medium-size businesses use the skills of board members to receive expertise and support which they cannot afford to hire. 3.90 UNCTAD. and any special tasks they may have. If. including the expertise. you operate a small engineering company and you do not have any experience in finance. Executive management In this section you should describe the structure of executive management. education and expertise. statutes of the company and specific objectives. In any case. Demonstrating that your executive management team possesses complementary skills will help to convince investors that your business has a promising future. If you can choose or suggest such members yourself. • Report to the shareholders in required format and at the required intervals. If the board members have special industry connections. • Supervise the management to ensure that it complies with the laws and regulations. considering that the board exercises all strategically important functions listed above and bears the ultimate responsibility for the company. • Nominate and dismiss the executive management of the entity. In this section you should outline who are the members of your board. Do not forget that the individual members of the board can help enhance the standing of your business if they enjoy high esteem in the business community and/or work for reputable organizations. it is worth briefly mentioning these facts in your business plan. lenders and investors will ask who its members are. for example. listing their names. select those who complement existing management. However.
you should also describe the skills of these individuals. is highly specialized in the production of concentrates from tropical fruits. other functions that may need to be represented in executive management are technology management. Depending on the type of business. • Production management. For example. how many years. • Special experience. what type of business. talents and areas of high competence (examples: has excellent understanding of the Russian market and has many contacts in the Russian Federation. • Any special achievements (examples: as a sales manager of company X doubled the sales volume within three years. in concise sentences. If your firm is in biotechnology and develops new medical products. has long experience in general management of companies with over 100 employees. quality management. your chief research and development officer is a key person in the organization. registered four patents in the food processing sector. • Professional history (which company.UNCTAD. etc. • Marketing and sales management. your IT manager will be a central figure in the management of the company. In such cases. developed and implemented a programme which . if you are in the electronic commerce business. which functions). should relate to the following: • Present employment and function. • Financial management (Chief Financial Officer-CFO) and administration. information technology management. research and development management. Specific information to be given for each of the above managers.). How to Prepare Your Business Plan 91 Readers will be particularly interested to know who will be managing the following important functions: • General management (Chief Executive Officer-CEO). etc. • Education.
team-based decision-making processes. 4. you are probably thinking seriously about developing middle management capacity. In such a case. open information policy. etc. It could be advantageous to include complete résumés of the key persons as an attachment to the business plan. etc. fairness in personnel assessment.). many of the functions mentioned above have to be combined and performed by yourself or only partially shared with the others. you should explain what amount of time you expect to allocate to each type of activity and what the priorities are.92 UNCTAD. You should also mention what you are planning to do when the business has grown so much that you are not able to deal alone with all these functions any more. stocks and stock options as an incentive. respect for individuals. fringe benefits. How to Prepare Your Business Plan resulted in reducing the costs of production by 20 per cent within one year. . etc. • Training schemes.). The management section should also include a short description of the company's policies for enhancing the performance of its managers and for ensuring their strong commitment to the business. Since one-person business will be hard to sell to the lenders or investors. • Cultural elements promoted by top management (regular and efficient communication. success-based bonus schemes. sales and even managing the finances of your business. Particular issues to be mentioned are: • The main criteria and the process for selecting managers. If you have a small business and you work on your own or with only few other persons. • Specific measures to retain key experts. try to dispel fears by appointing a well-regarded supervisory body and experienced partners/employees. • Policies for remunerating managers (proportion of fixed to variable salary.). Middle management If your company will be growing from a small to a medium-size enterprise. You may have to assume responsibility yourself for production.
the quality of the work deteriorates. 75 employees. this team may have some difficulties in managing the business successfully. The sensitive process of change should be accompanied by a well-conceived information and . there would be only three department (middle) managers reporting to him or her and the rest of the employees in the division would be reporting to the department managers. How to Prepare Your Business Plan 93 In such a case. the obvious thing for a growing company to do is to introduce a second (middle) level of management. your considerations and the measures you plan to implement should be adequately discussed in your business plan. efficiency and finally profitability. for example.. But if the business grows to. The result is that no proper supervision is provided. In such a case instead of 15 persons reporting to the division manager. Therefore. In such cases the executive managers keep assuming more responsibilities and overload as the business grows. the motivation of the employees diminishes and the managers get burned out too quickly. Difficulties often arise in growing companies that do not implement measures to develop sufficient capacity of middle management early enough. what are your plans to recruit suitable middle-level managers from outside? • Introducing another level of management is a major step with important repercussions on the structure and culture of your firm. The rule of thumb says that one manager cannot effectively supervise the work of more than 7-10 subordinates fulfilling different functions. to divide a division of 12-15 persons into three departments of 4-5 persons each. In a company with 35 employees. say. with repercussions on the working climate. They end up managing directly more people than they really can.UNCTAD. a team of 3-5 division managers may be able to operate the business without needing to have a middle level of managers. Experienced lenders and investors have often seen the difficulties some companies fall when the number of their employees increases from 30-40 to 7080.
as well as what experience and/or contacts they provide to your business. from where and how will you recruit them? • Are the workers trained? If not. how will you train them? • What are your plans for ongoing training? . B. accountants or public relations/marketing agencies. Whether you are going to start a new business or intend to expand an existing one. mention which strengths the firm or individual possesses. • You are a manager who is capable of integrating and building up the indispensable networks. Other important questions that have to be answered are: • Are there sufficient local workers available? If not. By properly selecting and effectively using external support services you demonstrate to the reader that: • You have acquired and are utilizing all the knowledge and resources necessary for running the business. name these and mention what type of service you will be getting from them.94 UNCTAD. Labour This section of the business plan provides details of the workforce you need in order to run your business. you need to indicate the number of people required and what skills they need to possess. lawyers. How to Prepare Your Business Plan consultation scheme with employees throughout the organization. In your description of each support service. 5. External support services If you are using or plan to use external support such as specialized industry consultants. They will form the pool of talents from which your business can draw the executive managers of the future. Have you developed such a scheme? Developing competent middle managers is also significant for the longevity of your business.
not in ideas . C. no expected growth. they will be critically observing your management team in order to evaluate its strengths and weaknesses and to assess the values. In the negotiation process and during the due diligence stage the investor will be examining in detail the success and failure factors of your business. An investor may even particularly ask to meet all key people before a final decision is made.UNCTAD. In particular. And they will probably have plenty of time and many opportunities to do this as the negotiation and due diligence processes are often long and intense. They involve many functions and disciplines.). current and prospective? • Which benefits. no restructuring etc. The general impression from the people in your business will certainly influence the final decision to invest or not. norms and overall culture of the firm. As a prominent venture capitalist once said: I invest in people. incentive plans and other schemes do you envisage for motivating people to work for you? In other words. Practical issues venture capitalists will check The final decision of a venture capital fund to invest in your business will not be based on your business plan alone. How to Prepare Your Business Plan 95 • What are the labour costs. Therefore. many of the senior managers of the company have to become involved in them and thus exposed to the investor. you still need to answer some of the above questions in your business plan.. Investors would be interested to know whether your existing employees and present staff policies are adequate to ensure successful continuation of your operations.
96 UNCTAD. • Values and norms of the firm.1 summarises the basic characteristics managers should have in order to be of value to their firms. It is therefore very probable that the prospective investor will be looking at these characteristics. The ability to listen.1 The basic characteristics of managers Position General management Responsibilities Communicating Necessary abilities The ability to communicate clearly and effectively in written and oral form. How to Prepare Your Business Plan Particular features on which an investor will be placing emphasis are: • Technical skills and competences of managers. Technical skills and competencies of managers Table VII. • Attitudes and human characteristics of managers. • Team spirit. You should be aware of these while planning your business or when interfacing with venture capitalists later on. Detailed criteria and considerations that investors will apply in assessing the above features are summarized below. receive input from others. Follow up to ensure that these decisions are implemented. consider all relevant factors and make decisions quickly. The ability to explain ideas and put forward arguments. 1. • Compatibility of business type and people’s culture. Table VII. Ensure that major decisions are taken in agreement with the other members of the management. Making decisions .
Negotiating Planning Problem solving Objective setting Team selection Leadership Inventory and quality control Operations . and follow up thoroughly. The ability to establish suitable inspection standards and quality control procedures. anticipate problems and know how to avoid them. hirer and appoint or promote the right managers to the appropriate positions. and set up effective systems for managing the inventory of raw material. The ability to solicit different points of view from all sides. etc. The ability to develop and implement action plans. The ability to understand the strengths and weaknesses of people. The ability to properly define and set objectives with management (derived from the overall business objectives of the firm) and to monitor and assess their completion. establish attainable goals. The ability to gather and analyse facts. select. moderate and arbitrate fairly for mutual benefit (everybody should feel satisfied with the result). How to Prepare Your Business Plan 97 Overview Good overview of most of the key disciplines and functions involved in the business. production. finance.UNCTAD. implement solutions effectively. it is necessary to have substantial knowledge of product development. human resources. balance opinions. marketing. The ability to develop a vision. define tasks and assign them to the management team. define a business mission and inspire and motivate others to pursue it. identify obstacles. finished goods or goods in process. Although they are not directly responsible.
The ability to produce detailed up-to-date and projected income and cash flow statements and balance sheets as well as to analyse and monitor the overall performance of the business by using financial ratios. short. Maintain close contacts with the clients and be quick and flexible in responding to their requirements. Purchasing Financial management Statements and ratios Control of funds and cash Fund planning and raising Marketing/ sales management Evaluation and research Client orientation Planning . How to Prepare Your Business Plan Manufacturing Experience of the manufacturing process. Have an understanding of the needs of the clients and make an effort to satisfy them. advertising and sales programmes with sales representatives and distributors. material and people’s skills in an effective way. Make sure that costs remain within budget and cash flow is under control. and ability to use machinery. openness to continuing improvements. The ability to conduct thorough market studies by using the best available information. cost and quality needs of the client.and service-oriented. understanding of time. and to derive clear and correct conclusions. The ability to forecast financing needs and structure debt/equity. The ability to identify the most appropriate sources and suppliers (considering cost.98 UNCTAD. delivery time and quality) in order to effectively negotiate contracts and to optimally manage the schedule of buying products and services. etc. The ability to develop effective promotion. Familiarity with sources of funds and procedures for obtaining them. The ability to be client.versus long-term loans. The ability to design and implement overall and individual systems for effectively executing and monitoring all money operations and particularly spending of the firm. to properly interpret and analyse the results.
supervising and. motivating the sales force. human resource development concepts. The ability to obtain market share by organizing. etc.UNCTAD. How to Prepare Your Business Plan 99 Product continuation The ability to determine service and spare parts requirements. scheduling and planning techniques. to assess situations in which help is needed and to initiate actions and follow them up. Support Engineering and R&D management Development Engineering Research Technical skills Human resources management Culture Conflict Help . people and performance assessment schemes. most important. testing and manufacturing. track customer complaints. The ability to listen to and understand human problems and needs. The ability to guide product development so that a product is introduced on time and within budget. outplacement. and supervise the establishment and management of the service organization. keeping a bottom-line balance. In-depth knowledge of recruiting strategies. and meets the customers' needs. Ability to deal with differences openly and resolve them through teamwork. with attention to costs. Product distribution The ability to manage and supervise product flow from manufacturing through the channels of distribution to the end user. The ability to supervise the final design through engineering. The ability to create an atmosphere and attitude conducive to high performance and rewarding good work verbally and monetarily. The ability to distinguish between basic and applied research. modern compensation and incentive schemes. training procedures.
patents. the moderator of the negotiations asked the investors: “What was the main reason that made you finally decide to invest in this firm?” The answer of the head of their delegation was short but meaningful: “These guys make an honest impression”. federal and. a deal was made and an agreement was signed. etc. liabilities and points of potential conflict and in developing measures for protection against these. United States. Some investors place even greater emphasis on such characteristics. potential investors will be assessing the attitudes and human characteristics of the managers in your firm. The investor United States investor was planning to use the Swiss firm as a basis for entering into the rapidly growing electronic banking business in Europe. warranties. international regulations concerning all aspects of employment and business operations. 2. While saying good bye at Zurich airport. Attitudes and human characteristics of managers In addition to technical and administrative skills and entrepreneurial competencies. was negotiating to invest $13. general managers and lawyers). Experienced in and knowledgeable about the intricacies of incorporation. Intellectual property rights Compliance Source: UNCTAD. State. After two weeks of intense and complex negotiations involving six to seven persons from each side (accountants. specializing in computer software and services for processing inter-bank payments and security transactions. licences. Making a good impression An investor from New Jersey. incentives. in identifying all possible pit falls.5 million in a firm in Baden. Knowledgeable about regulations and procedures of commercial law. How to Prepare Your Business Plan 100 Legal management Contracts Experienced in structuring clear and complete agreements. Box VII. copyrights. Switzerland. Source: G.1.UNCTAD. . Experience in compliance with local. default. technical specialists. etc. Malcotsis. marketing and sales managers. if necessary.
Not afraid to admit they are wrong or have made a mistake. they work hard but they also know how to keep a good balance and do not neglect family life. religions or ethnic groups or nationalities. motivation or the momentum of work if things for the future are suddenly not very clear or if a situation involving paradoxes and discrepancies arises. Can quickly adapt to changing situations and implement changes. Have no prejudice against people of other cultures. Can take advice from others. How to Prepare Your Business Plan 101 On the other hand. Characteristics for success Characteristics Orientation Distinctive success traits Do not lose orientation. Collective spirit Balanced life Problem solving Objective thinking Cultural sensitivity . They are committed to their work.2 lists some typical characteristics of managers that play an important role. Table VII. If necessary. Integrate in to the company and the management team and feel part of it. Once a CEO placed a banner with the following slogan in her office: “If you do not have a solution for your problem. Respect and are sensitive to other cultures and are able to operate across cultural barriers. many cases are known in which investors walked out of negotiations and no deals were concluded despite the high potential of the businesses and the experience of the management. and follow their own way and interests. They will always look at options to solve problems that stand in their way and they take the initiative in implementing solutions. Try to make individual objectives compatible with the overall objectives of the business. personal hobbies and interests. effectively and with confidence. social responsibilities. mistakes and failures.2. Try to understand themselves and assess their performance on a continuous basis and learn from their successes. Maintain optimism and positive attitudes for the future even in adversity. they ask for advice from others but do not overwhelm them with their problems. They do not isolate themselves. Wrong attitudes and character deficiencies of management are good reasons for investors not to invest in a business. They know how to solve problems quickly. Table VII.UNCTAD. and health. then you are also part of the problem”.
Ability to cope with changes. Social responsibility and environmental consciousness Trusting others No power need Realism Coping with overload Have the stability to withstand stress and strain. Willingness to assist others in self-improvement. setting realistic attainable goals. Criticism is accompanied with suggestions for improvement. Conscious in complying with social standards and in making a contribution that benefits people. No aggressive attitude or narrow. Ability to occasionally distance oneself from the business. face problems directly and promptly. Ability to delegate responsibility and not keep everything under direct control. rigid thinking. prestige. Appreciation of strengths of others. Good and stress health and physical stamina to work long hours. others and even competitors. Take initiative and charge of a given situation. no fear of failure and no preoccupation with own concerns. Direct in criticism and substantiate this with concrete facts and reasoning. highest priority and less urgent. suppliers. authorities. Avoid rumours and gossip. employees. How to Prepare Your Business Plan 102 Fairness and openness Honest and fair attitudes and conduct towards everybody: own firm. Pro active and not just following. Pragmatic and down-to-earth forecasting on targets and achievements that can be reached. Responsibility Independence Achievement orientation . Focus on achieving a standard of excellence. No false optimism. status. high demands. commitment to making things better. Tendency to guide the actions of others rather than dictate. to relax and recover. not feeling guilty about real or imaginary mistakes. optimism regarding what people can accomplish. Strong tendency to take responsibility. clients. society as a whole and the environment. belief in their potential for improvement. No tendency to feel threatened by perceived attempts to undermine authority. obstacles and work overload. inspire others by being an example.UNCTAD. shareholders. Ability to trust and inspire people. influence and control. No great need for power. knowledge of the individual effort it takes to achieve something. Not easily influenced and not any difficulties in taking decisions. asking for honest feedback and use this for further improvements. Ability to distinguish between important and less important.
Competitiveness Perfectionism Originality Not oppositional Relationships Enthusiasm Self-approval and motivation Source: UNCTAD. no tendency to cover mistakes. No excessive need to be liked or approved by others. . Develop ideas and initiatives of their own. No tendency to place excessive demands on self and others. no need to look for flaws and criticizing everything. no negative cynical attitude or sarcastic sense of humour. not seeking the feelings of security within a bureaucracy. They are diligent in planning activities properly. Become fascinated and enthusiastic about things and are able to spread positive attitudes and enthusiasm to others. Form healthy. take losing in good part and try to learn from experience.UNCTAD. strong desire to know about things and to experience things directly. Do things as well as necessary but not as well as possible. fixed ideas and a “win-loose” orientation that distorts perspective and goals. positive interpersonal relationships that are meaningful and reciprocal. but on the other hand they do not slow processes and make them extra costly by over-planning. No excessive concern to avoid mistakes. No preoccupation with detail that distorts perspective and judgement. Give and derive satisfaction from interactions with others. Maintain competitive spirit and happiness in winning but do not develop “winning obsessions” and aggressiveness. No preoccupation with the opinions of others and no tendency to say and do only what others think and expect. no tendency to view rules as a source of comfort and security. freedom from feelings of guilt and worry. Strong intuition. No need to win at all costs. Able to be selfmotivated without the need for compliments or influence of other people. Not scrutinizing everything. not systematically asking tough questions. No preference for staying unseen and unnoticed. energetic approach to life. Do things well but are not perfectionists. do not tend to make others feel uncomfortable. positive about the future and ability to enjoy things. do not always have to be right and to be the best. openness to new experience. Leave space for improvisation. Fair. How to Prepare Your Business Plan 103 Self-actuation Self-directed individuals with strong self-discipline.
• All are clear about their role and the division of responsibilities. • Core team includes at least three members. prospective investors may be interested to see how the management team works as a whole. • All team members share the same vision: success! • The team has a consensus about the mission. Team spirit In addition to assessing characteristics of individual managers. 4. Characteristics of a successful management team are: • Strengths and weaknesses of team members complement each other. objectives and strategy.UNCTAD. • Core members know their weaknesses and are ready to fill the gaps. . Examples are: • We strive to do the best for the benefit of our clients. • They bonded together. • We are always available to our clients. • They work in a spirit of mutual respect and friendliness and support each other. • The team covers all core disciplines and functions of the business. • The ownership structure is clarified between team members (shareholders). very seldom more than six. Values and norms of the firm Successful companies have specific values and norms by which all employees live and which the top management cultivates. • Most team members have been working together for a long time. including in difficult times. How to Prepare Your Business Plan 104 3.
• Bringing value to our shareholders is a major objective. • Our integrity is uppermost. even if we lose money. not individual goals. and if so. • We strive to be market leader in volume/in quality. Investors will most probably seek to ascertain whether the firm has made a commitment to endorse any such values and norms.UNCTAD. How to Prepare Your Business Plan 105 • Our knowledge and work should benefit our community and society as a whole. • Team results are uppermost. whether these are indeed applied in practice. • Our employees are our most valuable assets. .;
new water supply lines. • Development of products or processes that have a positive impact on the environment (i. The sections below briefly describe the concerns of lenders and investors and give a list of typical questions asked by them before they decide to finance a project. encourage more recycling.). • How your business could be affected and what would be the consequences for the lenders or investors. Your business plan needs to contain answers to the above questions.e. school/kindergarten. The lenders or investors will probably come back and ask for more details. etc. • Whether the management of your entity is aware of them.110 UNCTAD. Experienced lenders and investors are aware of these risks and therefore wish to know: • Whether there is an audited environmental report available. products and processes that use less energy. the financial consequences have been so serious that investors have lost their investment. In a number of cases when investors had to pay enormous amounts of money to resolve problems they did not anticipate when investing in the business. fewer material resources. Typical examples of such situations are: cleaning up contaminated soil on factory sites. water purification plant. In some cases. new electric/telephone lines. • Which measures are planned to prevent or mitigate damage. How to Prepare Your Business Plan • Infrastructure/services established by your firm which can be shared by the community (new access roads. . • What the environmental risks of your business are. medical service. You should be prepared to provide them. Environmental risks Loans to entities plagued by environmental problems have become a major concern for lenders and investors in recent years. or lenders never got back their loans. etc. D.). upgrading production systems releasing hazardous wastes exceeding given limits and modifying environmentally unacceptable products.
The lender's maximum potential loss in this case is also limited to the principal and accrued interest of the loan. fines etc. product or production equipment not in compliance with present or future environmental standards or market expectations). • Risk of high compensation payments and even bankruptcy. In addition. The concerns of investors The risk involved in equity participation is mainly related to the: • Risk of the company's reduced earning power. a potential image . In the case of equipment being used as collateral. The potential losses of investors are limited to the amount paid for their investment. compensation payments. • Risk of the potentially reduced value of collateral. the environmental risk is related to the loss of its value if the product or the process involved is environmentally problematic (e. The concerns of lenders The environmental risk involved for the lender is mainly related to the: • Risk of the customer's potentially reduced solvency. 2. The risk of reduced value of collateral becomes easily apparent in cases of real estate. including income lost since payment. impairing the creditworthiness and solvency of the business of the borrower. • Risk of degradation of the company's assets. when potentially contaminated sites are involved. How to Prepare Your Business Plan 111 1. loss of market share. As long as the lender does not take possession of the real estate the maximum potential loss of the lender is limited to the principal and accrued interest of the loan.g.. Non-compliance with environmental standards may cause serious economic damage through withdrawal of permits.UNCTAD. • Risk of losing reputation.
give details. Treatment of waste. the general public and other pressure groups? • Legislative information Which of the following environmental laws and regulations in your opinion apply to your business? How are you going to comply with them? General protection of the environment.112 UNCTAD. give details. Air pollution control. If the investor is actively participating in the management of the company. Handling and storing of hazardous materials. customers. Other. 3. Disaster prevention (factories and plants are a potential risk to the environment because of possible operational accidents). Examples of questions lenders and investors may ask • General information What are the main environmental issues that your business faces from the points of view of legislation. Waste water discharge. and pressure from suppliers. If investors control the business. Has the business ever been prosecuted for failure to comply with environmental legislation? If so. Are you aware of any impending changes to the laws and regulations that will affect your operations? If so. the personal liability of the responsible management members may arise. Noise abatement. How to Prepare Your Business Plan loss could be associated with the case. . depending on the applicable laws. their liability might even go further.
treatment and disposal of waste. are they within the limits? Has the company ever violated the regulations? Are any gases.. Has the company ever been subject to any legal action in connection with air pollution (including nuisance complaints)? • Liquid effluents Are there any liquid effluents that are produced by the entity? If so.UNCTAD. Are any significant environmentally related changes planned in the entity’s operations or regarding materials used. and storage areas for hazardous materials. waste incineration or waste treatment activities on site? If so. How to Prepare Your Business Plan 113 • Site details What was the site used for prior to the company’s current occupation? Has a survey for potential contamination/groundwater monitoring been carried out? If so. what are the results? • Operations with environmental relevance Include information with regard to generation. Are there any power generation. comment on how they conform to laws and regulations related to the protection of the environment. effluents and emissions. provide details with particular emphasis on the costs to be incurred for the implementation of the necessary changes. where are they discharged to? . produced and/or stored? What precautionary measures have been taken in case of plant failure with potential environmental consequences? Is there a written accident prevention plan? Is there any emergency response plan? • Air emissions Are any of the air emissions subject to regulation? If so.
were they satisfied with the monitoring and control procedures in place? Are changes in the control and monitoring procedures planned? If so. and period of storage. procedures to prevent and monitor leakage / spills. how will they affect the plant? What will the costs be? .. How to Prepare Your Business Plan Are discharges subject to licensing and regulation? If not.114 UNCTAD. provide details of any containment measures.. Are effluents stored on the site prior to disposal? If so. provide details. has confirmation of this been obtained from the regulators? If so..
was the fire officer satisfied with the precautions taken? Is the store adequately ventilated? Are there any hazardous wastes generated which require a disposal licence? If so. Are the containers protected from accidental damage and corrosion? Are the measures to contain accidental spills/releases adequate? Are drums adequately labelled? Is there evidence of previous spills/releases? Are inflammable substances located in a contained store? Are fire precautions adequate to control fire risks. has this licence been obtained? Have the terms of the licence ever been broken? ..UNCTAD. How to Prepare Your Business Plan 115 Are there any above.or underground storage tanks on site? Is the entity aware of any leaks or spills. when. and what was the result? Do the tanks have alarms/level indicators/cut-off devices? How often are tanks emptied? Is there a spill prevention plan? Is such a plan required by the regulators? If so. taking into consideration the quantities stored? Is the store licensed? If so.
e.116 UNCTAD.. dust. smell. where is it and in what condition is it? Do any of the batteries. fumes. transformers or other electrical installations on the site contain PCBs? .g. noise.
Your lender or investor will particularly want to know what you will be doing with the money you get and how you plan to generate the necessary cash flow to pay it back. when you will need it and when you will pay it back. change the advertisement mix. Introductory remarks Financial planning is a key element of your business plan. The two most important features of your financial planning are: • An indication of how profitable your business is expected to be in the future. and possible financial risks involved. • A definition of additional funds required for developing your business. It is as important for you as it is for your lender or investor. change your human resource policies. etc. For you Financial planning is an integral part of your overall business management concept.. each one of these actions will eventually have an impact on your financial statements. How to Prepare Your Business Plan 117 CHAPTER IX FINANCIAL PLANNING A. and if so on what terms and conditions. change the focus to new markets. how much money you need. you must keep in mind a number of critical considerations. While developing your financial plan.UNCTAD. will depend on how attractive and convincing the projected financial results of your business are. For your lender or investor The financial statements presented in your business plan (historical and projected) are the principal tools that will be used to analyse the performance of your business. A decision on whether your business will be funded or not. All decisions and assumptions you make will be reflected in the financial projections which are to be included in your business plan. as follows: . If you introduce new products. i.e. refurbish your machinery.
It is a great advantage that financial statements are standardized and regulated documents. since your business has probably only a few assets and no financial history. Your projections warn that if these costs rise by more than 25 per cent. • Standardization and regulation of financial statements. a cash shortage can cause the early termination of your business. suppliers. Even if revenues from sales are higher than expenses. rents. Let us say that you plan to start a business for growing pineapples. frequently involve start-up costs that are not applicable to on going businesses. Assessing your expenses.118 UNCTAD. you need to assess your assets and borrowing capacity. wages. the actual receipt of cash has to occur in time to meet expenses when they are due. Regardless of how good the idea of the business is. pesticides and insecticides. How to Prepare Your Business Plan • Adequate back-up reserves. The timing of revenues and expenses is critical to all businesses. • Contingency plan for unexpected costs. payments to suppliers) and non-recurring (e. The inability to service liabilities causes companies to fail. without adequate capital it will probably fail. • Basis for start-up businesses. both recurring (e. The type of financial information that you will need for preparing your financial plan depends on whether your business is an established enterprise or is just starting. Without adequate cash reserves. You must have a contingency plan. banks etc. whether new or established. borrowing capacity or other means of meeting expenses. unexpected repairs). Inability to pay in due time may damage your reputation and trustworthiness with employees.g. If you are writing a plan for a new business. or business expansions. However. herbicides. you are probably going to experience a period during which cash outflow exceeds cash inflow. • Timing of cash movements. These start-up costs should be included in your projected financial statements. Statistics on the reasons for business failures (bankruptcies) show that the single most common cause is shortage of cash. You used your financial statement projections to study the impact of changes in the cost of fertilizers. This might include securing credit from a bank until the costs decrease again or until the market price of pineapples possibly increases.g. your lender or investor is going to have to rely almost entirely on financial projections. your monthly revenues might not be sufficient to pay your suppliers and employees if you cannot increase the price of your pineapples in due time. This issue will be discussed extensively in the cash flow section. Start-up businesses. is vital. . Whether you are starting a new business or whether you are taking a large step in expanding your existing business.
UNCTAD. If so. • Income statement projections/budget. • Cash flow projections. How to Prepare Your Business Plan 119 "Standardized" means that there are no surprises or inventive and difficult computations involved in their preparation. "Regulated" means that the format of your financial documents will be dictated in large part by accounting conventions in your country and the specific requirements of your auditors. It is also fortunate that the use of the International Accounting Standards (IAS) is becoming increasingly common practice in most countries around the world. • Request of funds and other supporting information. most of your work is already done. B. They include standard terms that only have to be worked out mathematically for each specific business. The following sections provide guidance for preparing these elements. A proven track record is persuasive evidence of your chances of continuing success. you have been creating and maintaining financial records since the inception of your business. Financial history Results of past and ongoing operations will support the credibility of your business plan. • Important financial ratios. Most probably. • Balance sheet projections.. If you are preparing a business plan for an existing business.
expenses and net profit of your business. and the cash balance at the end of the period (per month or quarter for the last year. It shows your revenues from sales. If you have scattered the data in such a way that they have to search everywhere and piece together information that was supposed to be in one place. For the third and following years estimates can be presented on an annual basis. the cash you spent. An income statement for a business plan should be broken down by month or by quarter for the first year. It is an advantage if the format and type of information included in the financial history section are similar to those of the financial projections (discussed below). liabilities and shareholders' interest. and per year for the years before). • A balance sheet. Income statement projections The income statement is also called the profit and loss statement. these financial statements are the most objective pieces of evidence that most lending institutions and venture capitalists will look at in order to support or to contradict your forecasts for future performance. This projection (which is basically your budget) should include seasonal effects (for example. How to Prepare Your Business Plan • An income statement. expenses and net profit (or loss). This will enable the reader and yourself to get a better overview and quicker understanding of the development of your business. The second year can be broken down quarterly. Analyse the results of the income statement briefly and include . • A cash flow statement. which lists the sales revenues. they will not look favourably upon the rest of your plan. concise and easy to follow. which lists the cash you generated. For existing businesses. if you are in the pharmaceutical business you may have higher sales in the cold months of the year owing to the higher consumption of medications and vitamins). C. you are going to make sure that you present them in a format that is accurate. The net profit (or loss) is equal to revenues minus expenses.120 UNCTAD. which lists the type and book value of your business's assets. • The financial ratios derived from your income statement and balance sheet. With this in mind.
you need to document why such growth can be attained. Avoid large sales or expense categories that are lumped together without backup information about the components. If this is also the case with your plan. It can be because similar companies have had this growth path.UNCTAD. In other words. . If your business already exists. Many business plans tend to show rapid annual growth projections of 30. if you say you expect your firm to grow by 30 per cent in the first year and by 40 per cent in the second. 40. or because of projections from a specific market researcher. industry association or other sources. How to Prepare Your Business Plan 121 this analysis in your business plan. because the industry is growing at this rate (indicate the source for these data). 50 per cent or more. include income statements for previous years (financial history section). provide the basis for your assumptions.
The two basic elements of your business's cash flow are the cash inflows and cash outflows.1 contains an example of the major items included in an income statement. Table IX.... ..... ..... How to Prepare Your Business Plan Table IX.. etc.......... ............. general and administrative expenses = Operating profit (EBITDA)* - (Dollars) Planning years. ...1. *EBITDA: earnings before interest.... . ...122 UNCTAD.. income not yet received in cash..new company Xxx1 . ........ ........ ....... .... ...Selling......... . . ... .. ... ... ... . . .... ........ .... ... .... ... xxx2 .... . .. xxx4 . . ... depreciation and amortization.... . .. . Income statement Item Total net sales + Other operating revenues = Total revenues .Cost of goods sold = Gross profit . ........ ... . D.... ...... ....... .... .. It contains non-cash items such as accruals........ Xxx3 .. .... Cash flow projections 1... ..... .... What is cash flow? An income statement shows the profit (or loss) made during an accounting period..... ...... tax...... A cash flow statement shows a company’s in-and-out flow of cash and how cash is generated to cover outgoing payments. ...... Depreciation Interest expenses / + income Extraordinary charges / + credits Corporate tax = Net profit (loss) Source: UNCTAD.............
Rental payment for premises. A manufacturing business's largest outflows will most likely be for the purchase of raw material and other components needed for the manufacturing of the final product. Examples of typical sources of cash revenues are: • • • • • • • • Cash from direct sales (sales against cash) of products and services. an inflow occurs only when you collect money from the customers. Collection from accounts receivable. . Professional fees (legal. Cash dividends to shareholders in the business. How to Prepare Your Business Plan 123 Cash inflows are the movement of money into your business. your largest outflow is most likely to be for the purchase of retail inventory. training and consulting). If you grant payment terms to your customers. Purchasing fixed assets. Management bonus. If your business involves reselling goods. Patents. trade marks and distribution agreement fees. Rental (or lease) payments for equipment and furnishing.UNCTAD. Inflows are from the sale of your goods or services to your customers. Interest earned from bank deposits. audit. Licences. Personnel salaries. Capital increases in cash (new money put into the business by shareholders). registrations and permits. Dividends received from financial investments of the business itself. for example purchasing equipment. Examples of typical cash disbursements are: • • • • • • • • • • • • • Payments for raw material procurement. Outflows are generally the result of paying expenses or investing. paying back loans and settling accounts payable are also cash outflows. Proceeds from new loans. Advertising and promotion expenses. Cash outflows are the movement of money out of your business. Payments for procurement of finished/semi-finished products. Payments for buying machinery and equipment. Proceeds from sale of real estate or equipment. Commissions and/or royalties to agents. Other cash revenues from business operations. The funds received from a bank loan are also cash inflow.
Interest payments to the bank for working capital credits. Utilities (electric. Offering discounts for immediate or fast payments might be one way of improving your cash flow. equipment.124 UNCTAD. How to Prepare Your Business Plan • • • • • • • • • • • • Other rental payments (including vehicles). etc. etc. Credit terms are the time limits you set for your customers' promise to pay for the merchandise or services purchased from your business. • Accounts receivable. To manage your cash flow properly. Interest (and principal) payments to the bank for mortgages. Postal expenses (mail. Insurance premiums (for premises. • Inventory. courier. Accounts receivable represent sales that have not yet been collected in the form of cash. you must know the time it takes your customers to pay. gas and water).). Some of the most important elements that need special attention when you are preparing your cash flow projections and in managing your cash flow are: • Credit terms and policy. tariffs. Other business expenses (not elsewhere listed). Communications (telephone. Inventory describes the extra merchandise or supplies that your business keeps in stock for meeting demands of customers. Tax payments (duties. fax. telegrams. A credit policy is the blueprint you use when deciding to extend credit to a customer. Cash payments for office supplies. equipment. Motor vehicle expenses. An appropriate credit policy is necessary in order to ensure that your cash flow does not become the victim of a credit policy that is too strict or one that is too lenient. Credit terms affect the schedule of your cash inflows. An excessive amount of inventory hurts your cash flow by binding funds that could be used for other purposes. Repair and maintenance expenses paid (for premises. This is done through well-timed and highly coordinated production . on income. Internet provider). Although your credit terms and policy may say that clients have to pay within 30 days of receiving the product.). vehicles). vehicles). An account receivable is created when you sell something to a customer in return for a promise to pay at a later date. The “just-in-time” concept introduced by many companies in recent times has as a main objective to minimize the amount of inventory (stock of products). you may find that some of them take 60 or 90 days or more.
• Accounts payable. "near" meaning 30 to 90 days. you need to examine regularly your schedule of payables and have tight control of them. Accounts payable are amounts that you owe to your suppliers and are usually payable in the near future.UNCTAD. . Arranging for favourable (longer-term) credit terms and paying on time (and not earlier) improve the cash situation of your company. For the best cash management. Without trade credits you would have to pay for all goods and services at the time you purchase them. The above-mentioned sources and uses of cash can be conveniently divided into three categories as indicated in table IX. How to Prepare Your Business Plan 125 and distribution processes involving all major suppliers of raw materials and clients in the planning and execution work. This reduces the costs of storage space but also improves cash flow.2.
others) ♦ Patents.2.. others) ♦ Patents.126 UNCTAD. plant and equipment) ♦ Long-term financial investments (shares. . How to Prepare Your Business Plan Table IX..
including the lender himself. you can arrange in advance for other sources of funds to get you through temporary cash shortages. It also shows the net cash amount available at any time. a cash flow projection will provide you with the tool to keep your business decision-making on track and your inventory purchasing under control. It is possible to show a good profit at the end of the year. and when. Improving your cash flow will make your business more successful. Through proper cash management you may find that you have some spare cash. you need to look at each of the important components that make up the cash flow cycle in order to determine whether it is a problem area. It will also serve as an early warning indicator when your expenditures are out of line or your sales targets are not met. For you Used properly. It will specifically tell you how much money is needed when it is needed. on which you could earn some interest if you place it in a bank deposit account. and yet face a significant money squeeze at various points during the year. and where it will come from. Why do you need cash flow planning? A cash flow projection shows sources and uses of cash for the period under consideration. Analysing your cash flow will also help you to spot any problem areas in your business. 2..UNCTAD. As in any good analysis. Handling any cash surplus is just as important as the management of money into and out of your cash flow cycle. the completed cash flow forecast will clearly show your lender what additional . If your cash flow estimates show that you will occasionally not have enough money to pay your bills. It shows which amounts of cash are expected to come in and go out. Accelerating your cash inflows and delaying your cash outflows (but still paying within the time frame agreed with your creditors) are necessary measures for improving and managing your business. A proper cash flow forecast will give enough time to devise remedies. A cash flow projection is an important instrument for you as well as for your lender. Furthermore.
When making your cash flow projections you may have to distinguish between three different time frames as follows: Short-term cash flow accounting. They are made on a month-to-month basis and will help you to predict the amount of any short-term loans required for covering. These cover the entire period of your business plan (3-5 years) and are of use in establishing requirements for long-term bank loans or equity. This will give you some indication of your business's capacity to generate the resources necessary for expansion. If the performance projections are realistic. you can always work harder to please the next customer or regain the disappointed one. expansion in infrastructure. If you fail to satisfy a customer and lose that customer's business. if any. putting it in a deposit account which gives you higher interest than your settlement account). These are typically made for the first year of your business plan (or your budget for the coming year). A sound cash flow is essential for any successful business. This predicts the anticipated cash revenues and disbursements of your business on a week-to-week or even a day-to-day basis. they will also provide support for the feasibility of a term loan for purchasing equipment or for building up a distribution network. Medium term cash flow projections. This is typically the case when planning long-term product development. for example. A very important purpose of long term cash flow planning is to predict your business's ability to take in more cash than it pays out. How to Prepare Your Business Plan working capital. Some business people claim that appropriate cash flow management is even more important than the ability of the business to deliver goods or services. such projections show a substantial liquidity surplus over several months. If.128 UNCTAD. Long term cash flow projections. buying of new machinery. This is to ensure that your bank account is optimally managed and has sufficient cash to cover payment transactions over the coming weeks. you have to discuss with your banker the best way to invest some of this money (for example. Your business plan will probably not be concerned with such short-term operational control. It is obvious that management of cash flow is a very important element in making your business successful. seasonal liquidity shortages. the business may need. etc. Proper treasury management is important for enhancing the profitability of your business. But if you fail to pay your suppliers or your employees. you may soon be out of business. . on the other hand.
For existing operations. It is also recommended that you make adjustments for this year's predicted trend in the industry if any such information is available and you can get it. be sure to reduce your figures by about 40-60 per cent a month for the start-up months in the first year.UNCTAD. it will be entirely acceptable to show each month's projected sales at least 5 per cent higher than your sales of the previous year. Steps in preparing your cash flow projections Preparing a cash flow projection involves three steps as follows: Step1. sales revenues from the same month in the previous year provide a good basis for forecasting sales for that month of the following year. . the forecast sales to identified client groups should be the foundation for your projected revenues and should be based on existing sales of competitors of similar size. How to Prepare Your Business Plan 129 3. if analysts of the economy and the industry predict a general growth of 5 per cent for the next year. Furthermore. Forecasting cash revenues Step 2. For example. Reconciliation of cash revenues and cash disbursements Step one: Forecasting cash revenues Find a realistic basis for estimating your sales each month. How to prepare a cash flow projection a. Projecting cash disbursements Step 3. For new operations. Include notes to the cash flow to explain any unusual variations from the numbers of the previous year.
This is an important principle of the cash flow projection and should be applied whenever you are in doubt about the amount to enter and when to book it.200 in July that is how it must be shown on the cash flow spreadsheet. Normally. This involves linking the cash flow status of each month to the cash flow status and respective activity of the preceding and succeeding months. total cash payments for goods purchased and any other expected expenses have been estimated for each month of operation. If it is to be paid in two instalments $1. if you plan to pay your supplier invoices in 30 days. cash outlays will appear two or even three months after the goods purchased have been received and invoiced.400 annually. Exactly the same principle applies to all other cash expenses. it is necessary to reconcile the cash flow. Step three: Reconciliation of cash revenues and cash disbursements . follow the principle of not averaging purchases. For example. Your insurance expenditure is an example of a different type of expense. Your commercial insurance premium may be $2. How to Prepare Your Business Plan If you sell products on credit terms or with instalment payments.200 in January and $1. It is important that sales be considered only at the moment when cash is received. this would be treated as a $200 monthly expense. If you can obtain trade credit for longer terms. Once total collection of cash. beginning with a summary for each month of the cash payments to your suppliers (accounts payable). Each month must show only the cash that you expect to pay in this particular month to your suppliers. But the cash flow will not see it this way. The cash flow wants to know exactly when it will be paid. you must be careful to enter only the part of each sale that is to be collected in cash in the specific month you are considering (realized accounts receivable).130 UNCTAD. Step two: Projecting cash disbursements Project each of the various expense categories. Any amount to be collected after 30 days will be termed as “collections on accounts receivable” and will be shown in the cash flow projection in the month in which it will be collected. the cash payments for January's purchases will be shown in February. Again.
Example: reconciling cash revenues and disbursements (Dollars) Planned Actual April April Item Opening cash balance 12 000 Total cash revenues 10 000 Total cash disbursements 15 000 Closing cash balance 7 000 (carry forward to next month) Source: UNCTAD. b. Then add the total of the current month’s revenues and subtract the total of the current month’s expenditures. Remember that the income statement. Designing a cash flow worksheet There are various ways of structuring a cash flow worksheet.4. as the latter will be based on data and assumptions made in the other two financial statements. The reconciliation example given in table IX. balance sheet and cash flow worksheet have to be consistent. To derive the optimum benefit. In another part of your worksheet there will be all the details of cash inflow and cash outflow for your own purposes. How to Prepare Your Business Plan 131 The reconciliation section of the cash flow worksheet begins with the balance carried forward from the previous month’s operations. An appropriate format is given in table IX.3. This adjusted balance will be carried forward to the first line of the reconciliation part of the next month to become the base to which the next month’s cash flow sources and/or uses will be added and/or subtracted..3 indicates that there is a need to borrow funds in order to cover the cash shortage in June. The cash flow statement shows the main headings (aggregate amounts) that are appropriate to be included in a business plan. it is recommended that it be structured to show separately the inflows/outflows from (a) operating (b) investing and (c) financing activities. .UNCTAD. Table IX.
This can lead to under funding. One of the great advantages of these spreadsheets is that they allow you to change input parameters easily and to see immediately how your business and the cash requirements respond to different assumptions about the course of the business. • Compare planned and real figures. Lotus 123 or any other standard business software can be very useful for creating cash flow worksheets. Most companies experience a gradual increase in sales. 4.. • Include effects of seasonal variations and business cycles in all cash flow projections. patterns of cash movement emerge. For example. • Avoid large cash flow categories that are lumped together without backup information about the components. if you are in the accounting business. Look for significant discrepancies between “planned” and real figures. Some more hints for preparing/improving your cash flow When developing cash flow projections. if you are in the business of selling winter sports articles. As the true strengths and weaknesses of your business unfold before your eyes. Seasonal variations are particularly noticeable in the agricultural business. How to Prepare Your Business Plan c. if the figures of . Tools for cash flow projections Computer spreadsheet programs such as Microsoft Excel. On the other hand.132 UNCTAD. which means that your funds will prove inadequate for meeting your obligations. • Do not underestimate cash flow needs. the following important considerations are to be kept: • Avoid an unrealistically rapid increase in sales that generate cash. it will be useful to have a second column for the actual figures alongside each column of the planned figures. Since you will use the cash flow forecast to compare regularly each month's projected figures with each month's actual figures. spring and summer months are those with the least flow of cash in your business. For example. your cash flow will show peaking values in spring when you charge your clients for preparing their annual reports and assisting with their tax declarations. in which farmers harvest.
The most obvious measure is to minimize expenses. Two of the most common uses of extra cash are paying of your debt and investing the cash surplus. . It may be necessary to delay stock replenishment. • Improving your cash flow. • Using cash surplus. • Negotiating deferment of larger payments in the event of a cash flow emergency. • Negotiating longer terms for payables to your suppliers.e. • Trying to borrow from the bank the necessary additional funds (however. • Decreasing accounts receivable (through faster invoicing. leaving your business occasionally short of cash. or apply to the bank for an increase in the limit of your credit line. The cash flow gap represents an excessive outflow of cash that might not be covered by a cash inflow for some time. Deciding how to use your cash surplus requires some planning and is also part of the business planning process. may experience a cash flow gap from time to time. cash inflows lag behind your cash outflows. Although business. Think of this money shortage as your cash flow gap. Other important steps are: • Decreasing inventory.. How you handle your cash surplus is just as important as the management of money going in and out of your cash flow cycle. offering a discount for quicker payments. Cash outflows and inflows rarely occur at the same time. Preparing a cash flow budget is the best way to eliminate the cash flow gaps in your business. you will have to show your lender when and how you will be able to repay the loan). this is an unmistakable signal that it is time to revise the year's projections. etc. large or small. More often than not. the amount of operating expenses. etc. A cash surplus is a situation when the cash coming into the business exceeds the cash required for covering the expenses of your day-to-day operations. it does not necessarily mean that the business is in financial trouble.UNCTAD. Never leave cash inflow to chance. How to Prepare Your Business Plan 133 the business fail to meet your cash revenue projections for three consequent months.). Approaching the bank should be done well in advance of the day on which the additional funds are required. Improving your cash flow means increasing or accelerating your cash inflows or decreasing or delaying your cash outflows. i.
... ….. .. ….. …. ….. …..134 UNCTAD. ….... …. *EBITDA: earnings before interest..... …. …..... …. …. ….. …. ….. …. depreciation and amortization.. …. ….. Cash flow from operating activities: Operating profit (EBITDA)* .... …... …. …. …. …. …. …. …...Extraordinary charges / + credits . …. ….... ….4 contains an example of the major items included in a cash flow statement... …. ….. Xxx3 …. …..Interest expenses / + income . …... …. ….. ….....Dividends paid out = Total cash flow from financing activities Total net increase (decrease) in cash Cash balance (beginning of the year) Cash balance (end of the year) Source: UNCTAD. …. ….. Table IX.... ….. …... ….. …. …. ….. …. How to Prepare Your Business Plan Table IX.. ….. ….... …. …. ….. …. ….new company xxx1 ….. ….. ….. …. …. …. ….Repayment of funds borrowed + Sale (purchase) of marketable securities + Increase (decrease) in share capital ... …. ….. …. Xxx2 ….... ….. ….. ….. …. ….. ….Corporate tax Changes in working capital: + Decrease (increase) in accounts receivable + Decrease (increase) in inventories + Increase (decrease) in accounts payable = Total cash flow from operating activities Cash flow from investing activities: Sale (purchase) of property. …. …... …...... ….4. plant and equipment + Sale (purchase) of long-term financial investments + Sale (purchase) of patents. ….. Xxx4 ….. ….. …. …. tax. …. trademarks and licences = Total cash flow from investing activities: Cash flow from financing activities: Proceeds from new loans . …. Cash flow statement (Dollars) Item Planning years.. ….. …. …. ….
but does not in itself reveal how the business got there or where it is going next. Balance sheet projections The balance sheet is a statement of your company's relative wealth or financial position at a given date (say 31 December of each year). Assets must be valued in money terms and they must . How to Prepare Your Business Plan 135 E. You must also look at the information in each of the other financial statements (including historical information) in order to get an overall picture of the financial situation of the business. • Assets. That is one reason why the balance sheet is not the whole story. • Retained earnings. If your business already exists. Analyse the balance sheet briefly and include this analysis in your business plan. Liabilities • Long-term liabilities.UNCTAD. • Reserves. • Current assets. It is often referred to as a “snapshot” because it gives you the picture of the business at a specific moment. you will need to include an “opening” balance sheet. • Current liabilities. Assets are those things owned by your business that carry a certain value. They include all the physical and monetary items that are necessary for operating your business. The balance sheet of a company limited by share capital consists of the following categories of items: Assets • Long-term assets (called also fixed assets). If your business plan is for a start-up business. include the balance sheets of the last two to three years. Shareholders' equity • Share capital. As in the case of the other financial statements. avoid large asset or liability categories that are lumped up without detailed information.
followed by marketable securities. it is entered the first. Current assets Current assets are entered in the balance sheet in the order of their liquidity. Liabilities are generally divided into two groups. etc. or they can sustain losses from the business operations. Over time the value decreases by the accumulated depreciation. Assets are generally divided into two groups. it leaves a business in one of two ways: the owners can withdraw assets from the business. • Liabilities. Liabilities are obligations/debts of your company to third parties. longterm assets and current assets (short-term).136 UNCTAD. Since cash is the most liquid of all assets. It enters a business in one of two ways: through investments by the owners (shareholders) or through profits retained in the business. long-term liabilities and current liabilities (short-term). How to Prepare Your Business Plan be valued at their original cost. Liabilities come from two sources. inventory. They are claims that creditors have on your business. Long-term liabilities Long-term liabilities are those that must be paid during periods longer than one year. They can be placed in the business through a borrowing process. The process by which they are “consumed” in the financial statements and therefore disappear from the balance sheet is termed “depreciation of fixed assets”. The three important positions in the balance sheet are: Share capital Paid in by the shareholders/owners. . or they can be unpaid expenses incurred during business operations. accounts receivable. Current liabilities Current liabilities are those that must be paid within one year from the statement date. Shareholders' equity (or net worth) represents those assets that were placed at the disposal of the business by the owners of the company. Long-term assets Long-term assets (fixed assets) such as plant and equipment are being “consumed” by the business over a number of years. • Shareholders' equity. Accordingly.. Assets = liabilities + shareholders' equity . For any business and at any point in time the assets of the company should be balanced with the liabilities plus the shareholders'/owners' equity (that is the reason for the name “balance sheet”).UNCTAD. The retained earnings remain as wealth to the company.
…...… ….. …. …. …. ….. …. …. …. ….. …. xxx3 …. …. …. xxx4 …... …. …. How to Prepare Your Business Plan Table IX. …. …. ….. ….... ….138 UNCTAD. …. …. …. …. …. ….. …. ….. …. ….. ….. ….. …. …...... …. …. ….... ….. …. …. …. ….. …....... ...... ….... …. ….. ….. …. …. Long-term assets: Land.. …. …. ….. Xxx2 ….. ….... …. …... …... …. …. …. …... . …. trademarks and licences) = Total long-term assets Current assets: Cash and and equity Source: UNCTAD. …. Balance sheet (Dollars) Item Planning years-new company Xxx1 …... …... …... ….. ….… ….. plant and equipment + Long-term financial investments (stocks. ….. …......... …. Table IX. ….. …. ….. bonds) + Goodwill (patents.. …...5 shows the major items included in a balance sheet.5. .. …. …. …........ ….
so that you compare and spot important trends. In many cases.000 of assets to generate those sales. • Monitoring the changes in the performance of your business over a certain period of time.000. it does not seem too good (5 per cent). Lenders use financial ratios to assess a business that is applying for a loan.000 sales figure may seem impressive.000. By routine calculation and recording specific ratios at the end of every accounting period chosen you may see possibilities for improvement in key areas. In order to assess how your business is doing. . • Comparing the performance of your business with other businesses in the industry. A $3. Such comparisons are the reason why financial ratios have been developed. How good is that? If this profit is earned on sales of $250.000. • Assessing whether certain operations of your business need fine-tuning.UNCTAD. How to Prepare Your Business Plan 139 F.000.000. These are used as indicators for: • Providing a picture of the financial health of your business through evaluating its ability to generate profit. Important financial ratios Financial ratios are derived from information included in the income statements and balance sheets of your business plan.000. your income statement may show a net profit of $50. ratios are computed for a number of years (past and future projections). but not if it takes $3. pay its bills on time and utilize its assets efficiently. When developing your business plan you will be looking at ratios derived from both historical financial statements and financial projections. you will need to examine some of the figures in the financial statements not only in absolute terms but also in relation to other parameters of the business.000 are required to yield a net profit of $50. For example. but if sales of $1. and some suppliers use them to determine whether to extend credit to you. it may be very good (20 per cent).
The liquidity ratios are: • Current ratio. Your creditors may often be particularly interested in them because they indicate the ability of your business to generate the cash needed to pay your bills. Solvency ratios These ratios are explained in the following sections. there are only 15-20 ratios that are regularly used in business planning. These can be grouped in to four different types as follows: 1. However. This information should also be highly interesting for you. since inability to meet your short-term debts is a problem that deserves your immediate attention. Liquidity ratios 2. Liquidity ratios Liquidity ratios are probably the most commonly used of all financial ratios. Profitability ratios 4. 1.140 UNCTAD. . • Quick test ratio. Efficiency ratios 3. Liquidity ratios are sometimes called working capital ratios. How to Prepare Your Business Plan There are several dozens standard ratios that can be worked out.
Hence. This assures them that you will have enough working capital to run your business in the foreseeable future.Extraordinary charges / + credits .6 exemplifies the current ratio. general & administrative expenses = Operating profit .Provisions for income taxes = Net profit (-loss) Property. + Long-term investments + Goodwill (patents.Selling. trademarks & licenses) / Current liabilities Balance sheet Liabilities & equity Loans (un-/secured) = Long-term liabilities + = Long-term assets Bank loans (overdrafts) + Payables + Taxes. Generally.Depreciation . How to Prepare Your Business Plan 141 Lenders commonly examine liquidity ratios when they are assessing loan/credit line applications. Once a loan/credit line is allocated to you.6. accounts receivable and inventory. say over the coming one-year period. or a combination of both. Current ratio Table IX. your current ratio shows the ability of your business to generate cash to meet its short-term obligations. plant & equipment . your lender may request that you continue to maintain a certain minimum ratio as part of the credit arrangements. Lenders often require that you have a current ratio of 2:1 or better. stocks and bonds.UNCTAD. provisions + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders equity Source: UNCTAD. A decline in this ratio can be attributed to an increase in shortterm debt. steps to improve your liquidity ratios are sometimes necessary. Table IX. This ratio indicates the amount of current assets. that can be converted into cash to pay your short-term liabilities. a. . Current ratio Current ratio = Current assets Income statement Assets Revenues (sales) . such as cash.Interest expenses / + income . a decrease in current assets.Cost of goods sold = Gross profit .
which is rather low.25. p la n t & e q u ip m e n t .P r o v isio n s fo r in c o m e ta x e s = N e t p r o fit (.E xtr a o r d in a r y c h a r g e s / + c r e d it s . . For example.000 in current liabilities). If you manage to get $15.00 (you will have $50. . if the total amount of your current assets is $50.lo s s ) P r o p e r ty. p r o v isio n s = L o n g . g e n e r a l & a d m in istr a tiv e e xp e n s e s = O p e r a t in g p r o fit .S e llin g .000 the current ratio is equal to. Quick test ratio Table IX. long-term borrowing to repay the short-term debt can also improve this ratio.in v e n to r ie s I n c o m e s ta te m e n t A s s e ts R e v e n u e s (sa le s ) .000 as a long-term loan in order to refinance an equal amount of short-term debt. How to Prepare Your Business Plan If your business lacks the cash to reduce current debts.I n te r e s t e xp e n s e s / + in c o m e . + L o n g -te r m in v e stm e n ts + G o o d w ill (p a te n ts . For example. The difference between the two is that the quick test ratio subtracts inventory from current assets and compares the resulting figure with current liabilities.D e p r e c ia tio n .7.C o st o f g o o d s s o ld = G r o s s p r o f it . The idea is simply to take steps to increase total current assets and/or decrease total current liabilities as of the balance sheet date.t e r m lia b ilitie s + B a n k lo a n s (o v e r d r a fts ) + P a ya b le s + T a xe s. Other possibilities may appear if you carefully scrutinize the elements in the current asset and current liability sections of your company's balance sheet.000 in current assets to $25. the ratio will increase to 2. Quick test ratio Q u ic k te s t r a tio = C u r r e n t a s s e ts .7 exemplifies the quick test ratio.142 UNCTAD. The quick test ratio serves a purpose that is similar to that of the current ratio.000 and your current liabilities are $40. Table IX.
and where there is room for improvement. by looking at the following ratios: • Inventory turnover. • Accounts payable turnover. you should keep in mind that they give only a general picture of your business's ability to meet short-term obligations. In evaluating the current ratio and the quick test ratio.UNCTAD. . you are concerned with optimizing the use of your assets and being a cost-effective producer. which may not be sold so easily. Efficiency ratios As a business owner/manager. • Total assets turnover. This signals that your quick current assets can cover your current liabilities. This can be obtained only through a detailed cash flow projection. In general. a stable current ratio with a declining quick test ratio may indicate that you are building up too much inventory. Converting inventory to cash or accounts receivable also improves this ratio. a quick test ratio of at least 1:1 is satisfactory. 2. The quick test ratio can be improved through many of the same actions that would improve the current ratio. • Fixed assets turnover. You can determine how efficient your business uses its assets. How to Prepare Your Business Plan 143 Many lenders are interested in this ratio because it does not take into account inventory. Over time. • Accounts receivable turnover. They are not an indication of whether each specific obligation can be paid when due.
g. Inventory is the amount of merchandise. To compute this you need to estimate the average inventory over the year. provisions + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders‘ equity Source: UNCTAD. the efficiency of your inventory management may have a significant impact on your cash flow and on the overall performance of your business.Interest expenses / + income .Extraordinary charges / + credits . parts. For example. The shorter the period. A high inventory turnover is a sign of having slow moving or obsolete items in the inventory.000. trading.Depreciation . Table IX.8. multiply by 365 days and divide by the cost of goods sold.144 UNCTAD. if the total inventory of your computer equipment business is $300. plant & equipment .Provisions for income taxes = Net profit (-loss) Property. service). + Long-term investments + Goodwill (patents. supplies or other goods your business keeps in stock for meeting the demand of its customers. How to Prepare Your Business Plan a.Cost of goods sold = Gross profit . trademarks & licenses) = Long-term liabilities + = Long-term assets Bank loans (overdrafts) + Payables + Taxes.000 on average. general & administrative expenses = Operating profit . The most significant inventory ratio is the inventory turnover in days. These are the days (on average) before inventory is turned into accounts receivable or cash through sales.8 exemplifies the calculation of inventory turnover. the . Inventory turnover Inventory turnover = Inventory X 365 days / Assets Cost of goods sold Balance sheet Liabilities & equity Loans (un-/secured) Income statement Revenues (sales) . and if the cost of goods sold in a year is $500. the more efficient the inventory management of your firm (the more liquid the inventory). Depending on the nature of your business (e. Inventory turnover Table IX. manufacturing.Selling.
Extraordinary charges / + credits . + Long-term investments + Goodwill (patents. provisions = Long-term assets + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders equity Source: UNCTAD.9 exemplifies calculation of accounts receivable turnover.Provisions for income taxes = Net profit (-loss) Property. Accounts receivable represent sales for which payment has not yet been collected.Cost of goods sold = Gross profit .Interest expenses / + income . A ratio that is high by industry standards will generally indicate that your business needs to improve its credit policies and collection procedures. Account receivable turnover Accounts receivable turnover = Accounts receivable Income statement Assets Revenues (sales) . If your business normally extends credit to its customers. b. which may be quite high for the business you are in.Selling. The result is divided by your annual credit sales. It is calculated by multiplying the average current accounts receivable by the number of days in the year. general & administrative expenses = Operating profit .Depreciation . Accounts receivable turnover Table IX. the payment of accounts receivable is likely to be your most important source of cash inflows. The turnover of receivables in days represents the average period of time it takes your business to convert credit sales into cash. Table IX. The resulting ratio shows the average number of days it takes to collect your receivables.UNCTAD.9. plant & equipment . . trademarks & licenses) X 365 days / Sales Balance sheet Liabilities & equity Loans (un-/secured) = Long-term liabilities + Bank loans (overdrafts) + Payables + Taxes. How to Prepare Your Business Plan 145 average inventory turnover is 219 days.
How to Prepare Your Business Plan If your average value of accounts receivable is say $100. plant & equipment . The resulting ratio shows the average number of days it takes you to pay your bills. general & administrative expenses = Operating profit .Provisions for income taxes = Net profit (-loss) Property. + Long-term investments + Goodwill (patents. Accounts payable correspond to materials and goods your company has bought for which no payment has been made yet. Accounts payable turnover Table IX. The result is divided by the total cost of goods sold (assuming that most of the accounts payable are related to expense items indicated in the cost of goods sold). Accounts payable turnover Accounts payable turnover = Accounts payable Income statement Assets Revenues (sales) .Interest expenses / + income . the receivables turnover is 90 days.Extraordinary charges / + credits .Cost of goods sold = Gross profit .Selling.10. c. If you are in the construction business this may be acceptable. accounts payable are likely to be one of the most important items in the current liabilities position of your balance sheet. If suppliers extend credit to you. It is calculated by multiplying your current accounts payable by the number of days in the year.000 and your total annual sales is $400.10 exemplifies the calculation of accounts payable turnover.Depreciation .000. trademarks & licenses) X 365 days / Cost of goods sold Balance sheet Liabilities & equity Loans (un-/secured) = Long-term liabilities + Bank loans (overdrafts) + Payables + Taxes. this may be too high and you may have to take measures to reduce it. A ratio that is low by .146 UNCTAD. Table IX. Accounts payable in days represent the average period of time it takes your business to pay its creditors. If you are in the retail business of selling electrical appliances. provisions = Long-term assets + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders‘ equity Source: UNCTAD.
machinery. provisions = Long-term assets + C ash & cash equivalents + M arketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders equity Source: UNCTAD. the higher the ratio the better.Provisions for income taxes = Net profit (-loss) Property.Cost of goods sold = Gross profit . A declining ratio may indicate that you have over invested in plant.Interest expenses / + income . trademarks & licenses) / Fixed assets Balance sheet Liabilities & equity Loans (un-/secured) = Long-term liabilities + Bank loans (overdrafts) + Payables + Taxes.UNCTAD. plant & equipment . or delaying payments beyond the agreed dates. trying very hard to get advantageous terms.Depreciation . d. trade marks. Table IX.Extraordinary charges / + credits . equipment.Selling. Generally speaking. On the other hand. How to Prepare Your Business Plan 147 industry standards will generally indicate that there is still room to negotiate better terms with your suppliers. can spoil your reputation and make you an unattractive business partner. Terms with long schedules for payables are good for the cash flow and profitability of your business. Here again an optimum has to be achieved. equipment or other fixed assets. also called long-term assets). buildings. Long-term investments + + Goodwill (patents. because a high ratio indicates that your business has less money tied up in fixed assets for each dollar of sales revenue. general & administrative expenses = Operating profit . Fixed assets turnover Table IX. Fixed assets turnover is the ratio of sales shown in your income statement to the fixed assets on your balance sheet (land. It indicates how well your business is using its fixed assets to generate sales. patents.11 exemplifies the calculation of fixed assets turnover. . licences etc. Fixed assets turnover Fixed assets turnover = Net sales Income statement Assets Revenues (sales) .11..
it is always useful to compare the fixed asset turnover of your business with industry standards or that of your competitors if the data can be obtained. 3. The ratios listed below and explained on the following pages are probably the most important indicators of the financial success of your business.Depreciation .Selling. Profitability ratios You can use a set of ratios to assess the profitability of your business.Extraordinary charges / + credits .Provisions for income taxes = Net profit (-loss) Property. plant & equipment . How to Prepare Your Business Plan As in the case of the other ratios.12 exemplifies the calculation of total assets turnover. + Long-term investments + Goodwill (patents. provisions = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders‘ equity Source: UNCTAD. general & administrative expenses = Operating profit . Lenders and investors will be interested in these ratios as they demonstrate the performance and growth potential of the business: • Gross profit margin.Interest expenses / + income . The ratio of the sales in your income statement to the total assets in your balance sheet indicates how well you are using all your overall business assets to generate revenue (rather than just inventories or fixed assets). Table IX. Total assets turnover Total assets turnover = Net sales Income statement Assets Revenues (sales) . trademarks & licenses) / Total assets Balance sheet Liabilities & equity Loans (un-/secured) = Long-term liabilities + = Long-term assets + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) Bank loans (overdrafts) + Payables + Taxes.Cost of goods sold = Gross profit . Total assets turnover Table IX. .12. e.148 UNCTAD.
Extraordinary charges / + credits . general & administrative expenses = Operating profit . The gross profit margin ratio is an indication of your business's ability to manage the production costs (or cost of goods sold) at a given amount of sales.13 exemplifies the calculation of the gross profit margin. • Return on assets. Table IX. • Dividend pay-out. + Long-term investments + Goodwill (patents. The gross profit is the amount of money remaining from sales after the cost of goods sold has been deducted. • Return on equity.13. • Operating profit margin.Interest expenses / + income .Selling.Depreciation .Provisions for income taxes = Net profit (-loss) Property. if your profit margin has been diminishing over consecutive . Gross profit margin Gross profit margin = Gross profit Income statement Assets Revenues (sales) . How to Prepare Your Business Plan 149 • Net profit margin. a. trademarks & licenses) / Net sales Balance sheet Liabilities & equity Loans (un-/secured) = Long-term liabilities + Bank loans (overdrafts) + Payables + Taxes. plant & equipment . For example. provisions = Long-term assets + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders‘ equity Source: UNCTAD. Gross profit margin Table IX.Cost of goods sold = Gross profit .UNCTAD.. If your net profit is $500. b. including depreciation. it means that you are buying more expensive or/and you are selling cheaper. Net profit margin N et p ro fit m a rgin = N et p ro fit In co m e sta tem en t A ssets R even u es (sa les ) . It is probably the figure you are most interested in looking at. In such a case. a comparison with your competitors or with the average ratio in your sector may give you useful hints about your situation. .150 UNCTAD. Your net profit margin shows you the bottom line: how much money is ultimately available for you to withdraw from your business.P rov is ion s for in co m e ta xe s = N et p rofit (-lo ss) P rop erty.. If you are a manufacturer.S ellin g . The net profit margin ratio takes into account all your costs.E xtra o rd in a ry ch a rg es / + c red its . you may want to take a close look at your production costs to see if they can be reduced without affecting sales. If you are in the trade business and your gross profit margin is diminishing with time.14. interest expenses. g en era l & a d m in istra tiv e exp en se s = O p era tin g p rofit . Table IX.25 (or 25 per cent). L on g -ter m in v estm en ts + + G ood w ill (p a ten ts.In te re st exp en se s / + in co m e . your net profit margin ratio is 0.C ost of g ood s s old = G ros s p rofit .000. How to Prepare Your Business Plan periods and sales have remained the same. Net profit margin Table IX.000 and sales are $2. extraordinary charges and provisions for income taxes. and adjustments on either side (or both) are necessary. It may also mean that your selling prices are not rising as fast as the costs of purchasing or manufacturing the goods. it means that your costs of production are rising faster than your prices. p la n t & eq u ip m en t .D ep rec ia tion .14 exemplifies the calculation of the net profit margin.000.
general & administrative expenses = Operating profit . It shows the percentage of money remaining in the business after all regular costs of operations have been deducted from the .Interest expenses / + income . The operating profit is lower than the gross profit but higher than the net profit. or it could mean that something is not going too well (excessively high costs of production.Selling. plant & equipment .15. It is an indicator of the profitability of the business itself. trademarks & licenses) / Net sales Balance sheet Liabilities & equity Loans (un-/secured) = Long-term liabilities + Bank loans (overdrafts) + Payables + Taxes.Cost of goods sold = Gross profit . Operating profit margin Table IX. interest expenses and taxes. independent of investment plans and how the business is financed. If you fail to meet your target.15 exemplifies the calculation of the operating profit margin. overheads.Provisions for income taxes = Net profit (-loss) Property. This should be determined by taking into consideration the industry standards.UNCTAD. Table IX. it could mean that you have set an unrealistic goal. high overheads or/and low selling prices).). c. How to Prepare Your Business Plan 151 You should have some idea of the range within which you expect your profit margin to be.Extraordinary charges / + credits . Operating profit margin Operating profit margin = Operating profit Income statement Assets Revenues (sales) . but before depreciation. Long-term investments + + Goodwill (patents. The operating profit ratio is designed to give you an accurate idea of how much money you are making on your primary business operations. etc. provisions = Long-term assets + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders‘ equity Source: UNCTAD.Depreciation . It is the profit remaining after deduction of the cost of goods and other operating costs (personnel.
therefore. + Long-term investments + Goodwill (patents. A high return on assets can be attributed to a high profit margin or a rapid turnover of assets. plant & equipment . businesses gearing up for future growth invest in operating assets that do not immediately generate additional sales and. trade marks & licences) / Total assets Balance sheet Liabilities & equity Loans (un-/secured) = Long-term liabilities + Bank loans (overdrafts) + Payables + Taxes. Return on assets Table IX. On the other hand. By looking at the changes in this ratio over time. provisions = Long-term assets + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders‘ equity Source: UNCTAD. Table IX. you can get information on whether your overall costs are trending up or down.Depreciation .Cost of goods sold = Gross profit . How to Prepare Your Business Plan revenues. general & administrative expenses = Operating profit . d. will result in a lower return-on-assets ratio. or a combination of both. This ratio indicates the rate of return generated by the assets of your business. consecutive periods of diminishing ratios may indicate poor utilization of your plant and operating equipment. and why.16 exemplifies the calculation of return on assets. In many cases. . This ratio can be viewed as a combination of two other ratios net profit margin (ratio of net profit to sales) and asset turnover (ratio of sales on total assets). In some cases.Selling.Extraordinary charges / + credits . Return on assets Return on assets = Net profit Income statement Assets Revenues (sales) .Interest expenses / + income .152 UNCTAD.Provisions for income taxes = Net profit (-loss) Property. one or two periods of a lower ratio should not necessarily cause concern
21.D epreciation .21 exemplifies the calculation of the total assets to total liabilities ratio Table IX.Provision s for incom e taxes = N et profit (-loss) Property.Extraordin ary ch arges / + credits . If shareholders as part of the operating management are committed to making a substantial equity contribution from their own money.In terest expen ses / + in come . A ratio of 2 means that 50 per cent of the assets are financed by the shareholders themselves and 50 per cent are financed by externally borrowed money.UNCTAD. in expanding the business (increasing the assets in the balance sheet) but without providing any more funds of your own. c. gen eral & adm in istrative expen ses = O perating profit . you are perhaps interested in a higher ratio. + Lon g-term investmen ts + G oodwill (patents. i. Here again. Here again.e. a higher share of equity. . Total assets to total liabilities ratio Table IX.Sellin g.e. as this means higher equity (more commitment by the shareholders) and therefore a greater ability to absorb any financial losses. Lenders prefer to see higher such ratios. Total assets to total liabilities ratio T otal assets to total liabilities ratio = T otal assets Incom e statem ent Assets R evenu es (sales) . On the other hand. lenders feel more comfortable with lower ratios. The ratio of total assets to total liabilities is another indicator by means of which some lenders are accustomed to assess the debt-equity relationship. plan t & equipm en t . trade m ark s & licences) / T otal liabilities Balance sheet Liabilities & equity Loan s (un -/secu red) = Long-term liabilities + B ank loan s (overdrafts) + Payables + Taxes. The above and the other solvency ratios discussed earlier are examined very carefully by lenders also for another reason. How to Prepare Your Business Plan 157 between 2 and 4. More equity (including reserves and accumulated profit) means higher margins to survive difficult business times in the future. a proper balance has to be found between these conflicting interests. i.C ost of goods sold = G ross profit . lenders will tend to trust the whole business more..
22.Extraordinary charges / + credits . Here again. It examines.Selling. provisions = Long-term assets + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders‘ equity Source: UNCTAD. general & administrative expenses = Operating profit . How to Prepare Your Business Plan d. like the other ratios above. it disregards short-term assets and liabilities and looks only at the long-term debts of the company in relation to the long term committed capital equity. .Interest expenses / + income .Provisions for income taxes = Net profit (-loss) Balance sheet Liabilities & equity Loans (un-/secured) Property. Table IX. lenders would like to see that this ratio does not exceed certain levels that are standard for well.158 UNCTAD.22 exemplifies the calculation of the capitalization ratio.capitalized companies. plant & equipment . Capitalization ratio Table IX.Cost of goods sold = Gross profit .Depreciation . + Long-term investments + Goodwill (patents. Capitalization ratio Capitalization ratio = Long-term debt /( Equity + Long-term debt ) Income statement Assets Revenues (sales) . This ratio is concerned with the capital structure of the company. However. the debt-equity relationship. Such levels depend upon the type of industry and the kind of company. trade marks & licences) = Long-term liabilities + Bank loans (overdrafts) + Payables + Taxes.
If this ratio is declining over time.Extraordinary charges / + credits . It shows whether the expected income from your operations is adequate to pay comfortably the interest expenses. The higher the ratio. Interest coverage ratio Table IX. .23 exemplifies the calculation of the interest coverage ratio.UNCTAD. it is a clear indication that your financial risk is increasing. Interest coverage ratio Interest coverage ratio = Operating profit Income statement Assets Revenues (sales) .Depreciation . Long-term investments + + Goodwill (patents. the bigger your cushion and the more the business is able to meet interest payments when due. How to Prepare Your Business Plan 159 e. Table IX.23. general & administrative expenses = Operating profit .Cost of goods sold = Gross profit . By comparing the operating profit with the interest expense you measure how many times your interest charges are covered by earnings from your operations. This ratio is particularly useful when planning to borrow money for making investments.Selling. provisions = Long-term assets + Cash & cash equivalents + Marketable securities + Receivables + Inventories (goods and materials) = Current liabilities + Share capital + Reserves + Retained earnings = Current assets = Shareholders‘ equity Source: UNCTAD.Interest expenses / + income .Provisions for income taxes = Net profit (-loss) Property. trade marks & licences) / Interest expenses Balance sheet Liabilities & equity Loans (un-/secured) = Long-term liabilities + Bank loans (overdrafts) + Payables + Taxes. plant & equipment .
000 in a project.000 per year over a period of five years. A year later you invest another $50.000 + $ 45.$ 50. Methods for ranking investment projects Investors use a number of methods to evaluate investment projects. • Net present value.000 + $ 45.000 + $ 45. The cash flow is as follows: Year 0 1 2 3 4 5 6 Net cash flow .000. From the second year onwards the net cash you receive is $45. • Internal rate of return.000 Cumulative cash flow -$ 100.000 +$ 30.000 . rank them and select the most attractive among them to finance.000 -$ 60. This was the first formal method developed for evaluating capital investment projects.000 + $ 45.000 -$ 15.000 +$ 75.000 + $ 45.000 . Payback period The payback period is defined as the number of years it will take to recover the original investment from the future net cash flows.000 -$ 150.160 UNCTAD. 1.000 -$ 105. Example Assume that you invest $100. How to Prepare Your Business Plan G. This section discusses three of the most popular criteria applied: • Payback period. it may be advisable to work out these criteria and include them in your business plan. Depending on the type of investment you are anticipating. The easiest way to calculate the payback period is to accumulate the project's net cash flows and see when they sum to zero.$ 100.
discounted at an appropriate percentage rate. 2. 2. The discount rate is based on the cost of capital for the project. including the initial outflow. The steps for obtaining the NPV are as follows: 1. Its disadvantage is that it ignores cash flows beyond the payback period (i. In general. minus the present value of the cost of the investment. . One advantage of this method is that it is easy to calculate and apply. 3. The advantage of this method is that it takes into account the time value of money and takes into consideration the potential of the business over the entire planning period of the investment. The NPV is equal to the present value of future net cash flows discounted at the cost of capital. The NPV can be expressed as follows: NPV = CF0 /(1+k)0 + CF1 /(1+k)1 + CF2 /(1+k)2 + CF3 /(1+k)3………Fn /(1+k)n Where: • CFt is the expected net cash flow at time t. their sum is defined as the project's NPV. and if two projects are mutually exclusive. the project can be normally accepted. Add up all discounted net cash flows over a defined planning period. it has to be rejected.e. The latter depends on the level of interest rates in the economy. investment projects with a relatively short payback period are preferable. the one with the higher positive NPV should be chosen. Net present value The net present value (NPV) method is a useful method for evaluating investment projects.UNCTAD. if negative. If the NPV is positive. How to Prepare Your Business Plan 161 The cumulative total becomes positive in year 5. and so the investment is recovered in that year. the riskiness of the project and several other factors. Find the present value of each net cash flow. it is biased against long-term projects) and ignores the time value of money.
094 + 45.710. Therefore.00 $45.000.13 $29.00 $45.710.000. Take again the example discussed above in the payback period section.875. or the project's cost of capital.03 NPV = $14.37 In this example your original wealth as an investor will increase by $14.000/1.000/1. it is probably a beneficial investment. .710.095 + 45.00 -$50.093 + 45.000.162 UNCTAD. How to Prepare Your Business Plan • k is the expected discount rate.00 $45.26 $31.00 -$45.000.00 $45.879.000/1.090 .000/1. Assuming the cost of capital to be 9 per cent and a planning period of six years the NPV is calculated to be as follows: NPV = .100.871.096 = $ 14.37 The above calculation can also be expressed in a time line as follows: Year Cash flow 0 1 2 3 4 5 6 -$100.832.000/1.50.56 $37.246.000.91 $26.000.60 $34.000.00 $45.000/1.091 + 45.000/1.092 + 45.748.37.
A convenient method for finding IRRs involves plotting a curve that shows the relationship between a project's NPV and the discount rate used to calculate the NPV.04 per cent.).04 Discount rate (% ) Source: UNCTAD. This value of discount rate is defined as the internal rate of return (IRR). Such a curve is defined as the project's net present value profile. This is the upper limit of the cost of capital for which the wealth of the investor would increase. The present value profile for the example described above is shown in figure IX.1. The IRR value is found to be 12. How to Prepare Your Business Plan 163 3.e. Investors obviously expect to see business plans with a cost of capital below the IRR value. Determination of IRR 70000 Net Present Value (NPV) 60000 50000 40000 30000 20000 10000 0 -10000 0 -20000 2 4 6 8 10 12 14 16 18 IRR= 12. the point at which the present value profile crosses the horizontal axis. . The IRR is at the point at which NPV equals zero.UNCTAD. Figure IX. i.1.
If the company's founders have invested in the company. create an exit plan that describes how investors will get their money back. when the money is needed. A common mistake in some business plans is that no clarity is provided in this section. Investors would also like to know who will be making decisions for paying dividends and what criteria will be applied.164 UNCTAD. • Tax advantages/benefits for investors. • Exit plan/strategy. Finally. Request for funds and other supporting information 1. • Minimum or maximum amount of financial participation. • Information on current investors. • Collateral being offered if any. • How new capital and future investors' funds will dilute current and subsequent ownership. How to Prepare Your Business Plan H. • Arguments to prove the soundness of the investment. A common worry of investors is that even if a business is profitable. Request for funds In this section of the business plan you should clearly define the amount of funding and the type (debt or equity) of investment you seek. . the assurance that the company will become a strong candidate to be taken over or an initial public offering are what many venture capitalists will insist upon. • Access to additional funding sources (for further expansion). Investors or lenders will also want to know what they will receive in return for their capital. it may be difficult for them to get a price for their shares remunerating them adequately for the risks incurred and the length. Discuss what effect the capital will have on the potential of the business to grow and to possibly increase profit. include this fact in your plan. of time during which the funds were locked in. It is important to provide a breakdown of how the money will be used. Some investors are encouraged if they see that the promoters are risking their own money in the business. A cash-out option in five years' time or so. In your request include also the following elements as appropriate. which turns potential investors away. • Payback period and return on investment. and what investments have already been made in the company.
Make sure that you do not ask for less money than you think you will need because you think that this will help you to get the money. 2. How to Prepare Your Business Plan 165 Include also future financing needs.UNCTAD. Changes in the rates of exchange affect your exports unfavourably. it will undermine the credibility of your plan and reduce your chance of raising finance and other support. Be sure to document how investors will make money and what return they will get. It is better to ask for more money than having to go back to your lenders and investors and to ask again when you have run out of cash. Should a potential investor discover any non-mentioned negative factors. . Important subcontractors fail to make deliveries. Your sales projections are not achieved. The industry's growth rate drops. Your competitors introduce a new. A key customer cancels a major contract. Risk assessment No business is without risks. This cannot be stressed enough. Design or manufacturing costs exceed your projections." You need to show how much money they may expect to make on their investment and what the risks involved in this investment are. but give an idea of the funds you will require in the future to take your company to the next step to success. you cannot just say something like: "You will make lots of money from this. Your competitors cut their prices. In other words. do not just look at what you need today. better product or service at a lower price. An economic crisis decreases the purchasing power of your customers. An important advertising campaign fails. You will show that you have taken the initiative to raise these issues and are capable of handling them. If you are asking for money. New unforeseen regulatory requirements have a negative impact on sales. The following list of problems is by no means complete. Your ability to identify and discuss them demonstrates your skills as a manager and increases your credibility. but should give you an idea of some possible risks you run and have to cope with: • • • • • • • • • • • • Key employees leave the business. The opposite may also be true.
• Underestimating costs. • You cannot find skilled labour. • Hiring friends rather than the most qualified candidates. if possible. Consider some common mistakes as potential risks. • Underestimating competition. To generate a complete list of risks.166 UNCTAD. examine all your assumptions about how your business will develop and what the chances and opportunities are. the opposite of many of these chances and opportunities may be risks for you. As each coin has two sides. Put yourself in a "what if" situation and then. small companies innovate and large companies copy and get the benefit. Think of ways you can stay ahead of your competitors and retain your unique selling position. you could discuss possible long lead times for subcontracted parts in the "manufacturing process" section of the plan. • Overestimating the growth of sales. . • Trying to do everything for everybody. develop contingency plans to deal with this situation. or the impact of a lower than anticipated response rate to a direct mail campaign in the "sales tactics" section. Evaluate your risks honestly. Some of the most important ones are: • Paying employees too much or too little. For instance. How to Prepare Your Business Plan • Public opinion with regard to your product or service changes to your disadvantage. In many industries. • Underestimating the length of the sales cycle. If you like. This is always a risk you need to consider. you may incorporate the analysis of risks and contingency measures into the various parts of your business plan. • Fast growth which cannot be properly dealt with by the organization.
This personal financial information should identify the amount and source of funding that you have available and are prepared to invest in the business. Therefore. This part of the manual discusses potential risks in more detail. In large part. Be sure to include any start-up costs that will occur prior to opening your business. etc. While your business will probably involve certain expenses that are unique to your industry. your ability to sell yourself is a substitute for the historical information that does not exist. Instead. How to Prepare Your Business Plan 167 It may be wise to produce three different versions of your financial projections. particularly if you are trying to obtain outside financing. are your personal income tax returns for the last few years. Other documents that may be required. • Regulatory charges (licensing. Start-up business financial information If you are just starting a new business as an individual entrepreneur or together with a few partners. Nobody will trust your business ideas unless you are prepared to make a considerable contribution and risk your own money. your plan should include personal financial information instead of the historical information that an ongoing business would be able to provide. It will assist you in identifying and evaluating the uncertainties and risks of your business and in developing suitable contingency plans. cost of incorporation). 3. .UNCTAD. You need to convince whoever reads your plan that you have a genuine opportunity for success. do not forget some of these more common start-up expenses: • Professional fees (legal or accounting). There is no history of operations. an average and a pessimistic scenario. comprising an optimistic. you must rely heavily on your ability to sell yourself (and your partners) as a potentially successful business owner. you face a special challenge because you do not have an established track record. The plan should provide specific details regarding any personal assets that you intend to use in running your business. It does not matter whether you are using your business plan to obtain financing or to persuade prospective employees to come to work for you. The pessimistic scenario should take into consideration the most probable risks. • Security deposits for rented space.
The company is planning to invest in infrastructure. 3rd year. 70 per cent. . The sale of products is the only source of revenue. The sales in the first year are estimated to be $300. These are expected to be about 30 per cent of sales in the first year. three important parameters: The total investment per year as input into the cash flow projection. 30 per cent.168 UNCTAD. cars.25) and cash flow projections (table IX. An investment and depreciation plan is drawn up. • Depreciation. 25 per cent. • Cost of goods (income statement). This plan provides. and 4th year. balance sheet (table IX. also 50 per cent).26) are structured and reconciled. 20 per cent. 60 per cent. The “net book asset value” after subtracting the yearly depreciation. 50 per cent. general and administrative expenses (income statement). furniture and computers. and 4th year. 3rd year.27. In the following years. The basic assumptions and steps are as follows: • Sales (income statement). However. Here again. owing to the effects of mass production (increasing volume of production) this percentage is expected to gradually decrease (2nd year. and 4th year. which is introduced in to the long-term assets position of the balance sheet. • Selling. the business is forecast to grow substantially as the new company establishes itself in the market (growth: 2nd year. also 20 per cent). owing to learning and economy of scale effects this percentage is expected to gradually decrease (2nd year. The primary objective of the entrepreneur is to estimate how much money has to be borrowed from banks in order to develop the company.24). There are no other revenues such as commissions. This is for a new (start-up) company that is planning the first four years of its operation. How to Prepare Your Business Plan I. 35 per cent). The cost of goods in the first year is estimated to be about 70 per cent of total sales. The depreciation per year being introduced into the income statement.000. production machinery. Numerical example Below is a numerical example that shows how the income statement (table IX. as shown in table IX. 3rd year. subletting facilities income from special services. as a result.
. it will be noticed in the cash flow statement that the growth of business (growth of sales and therefore growth of accounts receivable) causes cash to be absorbed. • Accounts receivable (balance sheet). How to Prepare Your Business Plan 169 • Interest expenses (income statement). Thus. • Extraordinary expenses/income (income statement). The assumptions with regard to the inventory are similar to those with regard to the “accounts receivable”. • Inventories (balance sheet). growth of cost of goods and therefore growth of inventory) absorbs cash.28). the company makes losses in the first and second years of its operation. the taxable income is estimated in a separate table (table IX. the first two years include initial costs such as legal fees for setting up the company and establishing an accounting system. 50 days in the third year and 45 days in the fourth year. The accounts payable turnover is assumed to be 75 days throughout the four-year business planning period.UNCTAD. In this particular example. • Accounts payable (balance sheet). It is therefore assumed that tax will be paid for the first time in the third year.. These are usually non-recurring expenses/income. It is assumed that the company will be able to operate with reduced stock owing to improvements in logistics and delivery service. However. Unlike in the case of receivables and inventory. The inventory turnover is 60 days in the first year. 80 days in the second year. Here again the growth of the business (growth of sales. • Tax (income statement). 55 days in the second year. It is also assumed that the authorities accept that the losses of the first two years can be deducted from the profits of the third year. This gradual improvement is expected as a result of the “quickening” of the invoicing and collecting processes with time and also as a result of the increase in the proportion of clients that are “good” payers. The accounts receivable turnover is taken to be 90 days in the first year. As indicated in the income statement. the growth of the business will cause the accounts payable to increase steadily and thus be a source of cash in the cash flow statement.
000 $ 100. How to Prepare Your Business Plan • Share capital (balance sheet). after the net profit has added a substantial amount to the retained earnings.30) (introduced in the position: “proceeds from new loans”) to have a “positive cash amount” plus some contingency at the end of each year. . During the first three years it is assumed that no dividend will be paid. The total dividend is assumed to amount to 50 per cent of the net profit.000 (part of the loan) can be applied as the first repayment at the end of the fourth year.29 shows the reconciliation of shareholders’ equity or the use of profit. In this particular example the needs for additional borrowing are found to be: First year: Second year: Third year: $ 350. The amount placed in the reserves is fixed at 20 per cent of the net profit (see table IX. The primary objective of entrepreneurs is to ensure that they always have sufficient cash (working capital) to operate the business. The business planner has therefore assumed that $70.170 UNCTAD. The first dividend will be paid for the fourth year (to be paid during the fifth year after the annual shareholders meeting has taken place) after two important conditions have been met: The company has made a net profit.000 The first calculation has shown that the cash balance at the end of the fourth year is quite high and more than what is needed in cash to run the company operations. Table IX. Reserves are added only in the fourth year of operation to the shareholders' equity of the balance sheet.000 $ 100. Reserves and retained earnings were built up in the balance sheet. Thus. the final reconciliation of the financial statements can be made by working out the loans required (table IX.000.29). • Reserves (balance sheet). • Loans (cash flow statement). • Dividends. The balance sheet gives the cash available at the end of the year. No changes to the share capital are expected over the four-year planning period. The share capital subscribed and paid in by the shareholders in establishing the company amounts to $100.
The liquidity ratios (current ratio over 3 and quick test ratio over 2) are sufficiently high to ensure that the business will have enough liquid means to cover its running costs. *EBITDA: earnings before interest. depreciation and amortization.. Table IX.new company xxx2 xxx3 xxx4 + Other operating revenues = Total revenues . profitability and solvency ratios show an improving trend as the business grows.UNCTAD. .24. Income statement: an example (Dollars) xxx1 Item Total net sales Planning years.Cost of goods sold = Gross profit . How to Prepare Your Business Plan 171 • Important ratios.31 shows the development of the most important ratios over the four-year period. tax. Table IX.Selling. The efficiency.
plant and equipment + Long-term financial investments (stocks. bonds) + Goodwill (patents. Balance sheet: an example Item (Dollars) Planning year -new company Xxx1 Xxx2 Xxx3 xxx4 Long-term assets: Property.172 UNCTAD.25.. . How to Prepare Your Business Plan Table IX.
. trade marks & licences = Total cash flow from investing activities: Cash flow from financing activities: Proceeds from new loans .Interest expenses / + income . Note: The dividend from the business of the fourth year is effectively paid during the fifth year of operations. Cash flow statement: an example Item Planning years.26. How to Prepare Your Business Plan 173 Table IX. plant and equipment + Sale (purchase) of long-term financial investments + Sale (purchase) of patents.new company (Dollars) xxx1 Xxx2 xxx3 Xxx4 Cash flow from operating activities: Operating profit (EBITDA)* .UNCTAD..Repayment of funds borrowed + Sale (purchase) of marketable securities + Increase (decrease) in share capital . *EBITDA: earnings before interest.Extraordinary charges / + credits . after the shareholders' meeting. depreciation and amortization.
27. Investment and depreciation plan: an example Item Planning years.new company (Dollars) xxx1 200 000 200 000 80 000 80 000 36 000 316 000 10.174 UNCTAD.28. How to Prepare Your Business Plan Table IX.000 8. Reconciliation of shareholders' equity (Dollars) xxx1 Item Planning years new company xxx2 xxx3 xxx4 Beginning shareholders equity + Net profit + Additions to capital . 286 000 328 000 480 000 468 000 .Dividends/withdrawals Ending shareholders' equity Reserves (year end) Retained earnings Source: UNCTAD.
-77 000 -11 500 20 20 -77 000 -88 500 0 0 0 0 95 900 165 515 20 20 0 0 7 400 165 515 1 480 33 103 Table IX.UNCTAD.new company xxx2 xxx3 xxx4 Loans drawn (beginning of year) Basis for interest calculation Interest rate (%) Interest expenses Loan repayment (year end) Loan balance (year end) Source: UNCTAD. Financing plan: an example (Dollars) Xxx1 Item Planning years.30. How to Prepare Your Business Plan 175 Table IX. Calculation of provisions for tax: an example (Dollars) Planning years.new company Xxx1 Item xxx2 xxx3 xxx4 Net profit after extraordinary items Corporate tax rate (%) Net loss carried forward Taxable income Corporate tax Source: UNCTAD.29. 350 000 100 000 100 000 0 350 000 450 000 550 000 550 000 10 10 10 10 35 000 45 000 55 000 55 000 0 0 0 -70 000 350 000 450 000 550 000 480 000 .
0 40% -2% 15% -2% -100% 0% 44.1 2.4 55 80 75 1.7 4.8 6.6 1.4 0.176 UNCTAD.2 60 90 75 1.9 50 70 75 1.9 0.3 4.7 xxx3 3.0 2.2 0.9 50% 14% 30% 13% 89% 0% 5.3 0.6 2.9 1.0 1.8 1.0 0.0 1.0 2.2 50% 15% 30% 18% 77% 50% 3.31.1 1.6 45.6 xxx4 3.7 30% -26% 0% -19% -335% 0% 17.8 3. .4 45 60 75 1. How to Prepare Your Business Plan Table IX. Ratio summary sheet Item Liquidity ratios Current ratio Quick test ratio Planning years.6 1.new company xxx1 3.1 0.3 1.0 Xxx2 3.1 18.
UNCTAD. How to Prepare Your Business Plan 177 PART THREE CONTINGENCY PLANS .
While your assumptions may have been realistically made. Some of these may be relevant to your business and some may not. Making alternative assumptions and planning around them is the best way to deal with possible events that are out of your control. For example. In your business plan you have made assumptions about future interest rates. see what will happen to your financial statements if the banks increase the interest rate to 15 per cent. For each scenario you take parameters that deviate from your original assumptions and then you check what would be the impact on the financial performance of your business. the probability of everything going exactly according to plan is very small. you know the actual result will not be precisely what you have predicted. Introductory remarks Your business plan is based on a number of assumptions. Some are qualitative in nature. profitability and balance sheet will deteriorate so much that your whole firm is seriously endangered?” To be able to answer possible questions you need probably to look at a range of scenarios. etc. your market share.UNCTAD. No matter how carefully you have made these assumptions. Then make a third check and see what will happen if both these disadvantageous deviations occur at the same time. if you have assumed an average interest rate of 10 per cent for your bank loans. The sections below give some examples of the types of risks usually considered in contingency plans. market growth. How to Prepare Your Business Plan 179 CHAPTER X RISK AND SENSITIVITY ANALYSIS A. see what would happen to your financials if the increase were only 3 per cent. Some can be expressed in quantitative terms and thus can be used to analyse how sensitive the financial statements are to a major deviation. If you have assumed an annual growth in sales of 8 per cent. A contingency plan is an . The purpose of sensitivity analysis is to help you to develop a contingency plan that you may or may not include in the business plan. behaviour of competitors. The questions your lender or investor will ask are: “What will happen if one or more of the parameters deviate significantly from your original estimates? How will your financial situation be affected? What is the risk that your cash flow. exchange rates. tax rates.
If you have already considered possible responses to changes in the market. Thus. How can relative movements of currencies affect your production costs or sales? Assume that you source raw material from the United States and you pay for it in dollars. Your cost of production will decrease and margins on sales will increase. etc.). Assume as an example that you are a building contractor. the market potential for construction of new houses may drop by about 20 per cent. But if the opposite happens. If you have a contingency plan. you may have difficulties. excavators. The maximum rate has been fixed at 12 per cent. You have recently invested in new construction machinery (cranes. It is therefore wise to repeat your original financial planning calculation by assuming an interest rate for your loan of 12 per cent (instead of 8 per cent) and a reduction in your original sales volume by 20 per cent. However. concrete mixing machines. How can your business be affected by a substantial increase in the interest rates? Here you need to consider the effect on client demand as well as the necessity to make higher interest payments to your lenders. B. It is critical that you have identified those areas to which your business is vulnerable. It would be interesting to see what would happen in this case to your overall profitability and if and when there would be any critical shortage of cash in your business. Types of risks 1. you are ready to act. you can react more quickly than if you have never even thought of the consequences. General economic environment Interest rates. • • Currency fluctuation. you have already identified the likely causes and impact and considered your responses. whether things go better or worse than expected. How to Prepare Your Business Plan 180 effort to avoid having your business disrupted when market or economic conditions change beyond what you are prepared to handle without major adjustments to your operations. If the dollar becomes weaker or the yen becomes stronger in relation to your currency. in your loan agreement the bank reserves the right to increase the interest rate if the market rates increase. .UNCTAD. For this investment you have borrowed money from the bank at an interest rate of 8 per cent. You also know from previous experience that if the market interest rate increases to over 10-12 per cent. you will profit from the situation. and you sell your final product to Japan and you receive yen.
exporting.1. cotton and iron prices)? 2. importing raw materials and machines.1). • Raw material prices.UNCTAD. it is wise to study how the last recession cycles affected your industry.). The discounting procedure applied under the net present value method (see financial planning section) is a practical way to assess the impact that inflation may have on your investment. In some cases it is found easier to produce financial projections in dollars or other hard currencies. sugar. there may be unpleasant surprises (box X. How cyclical is the industry of your business? How does it relate to the general economic cycle? How do you expect the next recession to affect your business? Although not every recession cycle affects the same industries in the same way every time. How to Prepare Your Business Plan 181 • Recession. etc? How could this affect your business? Importing machinery or raw material for production is an issue that requires particular attention in planning a business. • Inflation. Are there any possibilities that the Government will not issue. How can major changes in world prices of raw materials affect your business (for example. It is probably the best forecast of what will happen next. will withdraw or not renew any licences and approvals or that it will introduce restrictions for entering the market. wheat. Some economies are often confronted with hyperinflation. otherwise. Box X. Political/regulatory • Licences and approvals. oil. Regulatory surprises .
UNCTAD. assets. • Tariffs and quotas. insert them manually into envelopes and sending them directly to the consumers abroad on behalf of the telecom companies. processing of the data by high-capacity computers available in the entrepreneurs' firm. Source: UNCTAD. Are there any government grants or subsidies that are supporting your competitors but not you? How critical can this competitive disadvantage be for your business? • Increase in taxes. When the factory was about ready to begin operating the management set-out importing the highquality steel necessary. and printing monthly invoices. The authorities refused to grant an import licence. A similar problem happened to an entrepreneur who established a business for conducting the invoicing work of foreign telecommunications companies (outsourcing).? How would any such increase affect the overall profitability or viability of your business? . As this was proved not to be suitable. Is there the possibility of a major increase in the tax on your revenues. as the import licence was finally granted. The inability to deliver on time inflicted also considerably damage the image of the firm. the entrepreneur was contemplating abandoning the business. duties/tariffs on your products or equipment? • Government grants. However the issue was resolved. The mistake was that the issue of steel import was not examined with the authorities in the early planning stages of the project. It was an unpleasant surprise to find that the firm was prohibited from importing steel because national regulations protected local steel suppliers. etc. the investor decided to abandon the business at a great financial loss. Could the Government impose new import or export quotas. net profit. How to Prepare Your Business Plan 182 An entrepreneur set up a factory for producing razor blades. but the long delays inflicted great financial damage on the business. As the quality of local steel could not meet the specifications for producing high-quality blades. There was no problem in importing the computer equipment or getting the licence for the international transfer of data. The problem occurred as the company wanted to import the special paper for the printing of the invoices by high-speed printers. insisting on the use of locally produced paper. The service involved the following: receiving from the telephone companies electronic raw data on telephone calls made by their customers.
Possibility of the Government's changing policy with respect to exchange rates (as a result of which. Changes in public opinion • Taste and fashion. for example. ethical or "green" issues that can affect your business? For example. the fur coat business has suffered a lot in recent years because large parts of the population in numerous countries became sensitive about killing rare species for clothing and fashion purposes. • Health (tobacco industry. • New economy (new business principles and beliefs). client protection and free competition will affect some of your products? If so.UNCTAD. foreign currency can be exchanged only at specific banks at an exchange rate fixed by the Central Bank). . Are there any moral. how do you judge their effect on the overall financial situation of your business? • Exchange rate controls. pills for everything. • Communication (Internet. related to environmental protection.). mobile telephones). How to Prepare Your Business Plan 183 • New regulatory requirements. Is your industry stable or is it affected by changes in social taste or fashion? • Ethical and "green" issues. less stress). • Energy (attitudes towards nuclear power generation). safety. Is it possible that new regulatory requirements for example. more fun. eating habits). • Lifestyle (more leisure. 3.
However. Examples of damage Industry Oil/chemical Food processing/catering Transportation (airlines. Could the underlying technology of your product become obsolete and be likely to be superseded by better new products? For example. In most cases. Could the process technology which you are using be subject to fundamental change in the years to come? If so. individual persons inside or outside the company or the community as a whole. How to Prepare Your Business Plan 184 4. Such damage can be mitigated through insurance.) Pharmaceutical Tobacco Damage Pollution caused through spills Food poisoning Injuries or deaths through crashes Health damage through inappropriate drugs Cancer effects . in the 1980s and 1990s we saw a number of companies producing drawing instruments and drawing tables going into bankruptcy. The introduction of computer-aided design has made mechanical drawing instruments obsolete. Law suits There are many possible reasons why a company may get involved in a lawsuit and as a result may have to pay large sums to third parties. buses. Table X. in many cases insurance coverage may be limited and companies may still be obliged to cover the rest.1. • Production technology. this is for covering damage that was caused to entities. trains.UNCTAD. The companies that failed were not able to diversify fast enough to new technologies and products. Typical examples of damage are listed in table X.1. etc. Technological • Underlying product technology. would major investments be needed and could there be a complete change in the cost structure of your product? 5.
etc. Replacement of sold products (or specific part in them) due to faulty design Construction General products Source: UNCTAD. Staffing • Management. How to Prepare Your Business Plan 185 Financial audit/consulting Machinery Wrong valuation / failure to identify liability during a due diligence Injury or death of persons due to accident attributed to inappropriate design. inadequate instructions or material failure Structural failure of a building. 6. Client-related . bridge. What is the risk that new enterprises in the region will start competing for workers. How do you minimize the possibilities of major financial irregularity (fraud) that can do a major damage to your firm? 7. finance manager) decided to leave the company? What would be the impact on the operations of your company? What would be the effect if you could find appropriate managers to expand your business? • Workers.UNCTAD. production manager. if for any other reason you cannot find skilled labour? • Financial irregularity. with the result that salaries increase to much higher levels than you had originally anticipated? Or. How would your business be affected if one or more of your key managers (sales manager.
non-availability of raw material or non-availability of energy or water supply? • • Quality problems. If they do not fulfil the necessary requirements.)? Production failures. What would be the situation of your business if one or few major clients did not pay your invoices for an extended period of time? What would be the impact on your cash flow? What measures would you take in order to get paid? 8. owing to failure of process machinery. This is particularly true for goods such as computer software and pharmaceutical products that require extensive testing and certification. difficulty in obtaining spare parts. products. . Developing a new product necessarily involves a number of uncertainties. due to fire. How to Prepare Your Business Plan 186 • Loss of clients. New products have also got to be tested and certified. clients. production processes. Is such a loss possible in your entity? What would be the implications? What measures have you envisaged to ensure that there will be no such loss (back-up system etc. etc. 1 week. It is therefore not unusual that the actual time frame for and. computer failure. some modifications in the design and construction may have to be made. theft. Devising something "new" involves elements of innovation and creativity and therefore it is not always easy to make accurate predictions about the time and effort that will be required. Quality/production problems • Loss of information. What is the structure of your anticipated client portfolio? What will happen if one or two key clients cease buying your products or service? • Client payments. hackers or any other reason may cause a major crisis for many companies. What is the risk of loss of long-term profitable business by not being able to produce the necessary quality to satisfy the clients? • Delays/cost overruns in product development. developing new products exceed by far the budgeted amount. viruses. Loss of information about the market.UNCTAD. longer)? For example. cost of. Can production be interrupted for a longer period of time (1 day. 2-3 months.
Cost overruns happen often. A typical question is what you would do if you had a major problem with a subcontractor on whom you are highly dependent. • They start competing against you. However. what is the risk that the effort and time required will exceed your forecast? If this happens. • They go out of business and will no longer deliver. and the new price cannot be included in the overall price of your products without making them too expensive for the market. How to Prepare Your Business Plan 187 If you are developing a new product.. • The quality of their product or service is no longer satisfactory. • They regularly fail to meet the agreed delivery schedules. There are many reasons for this.UNCTAD. Subcontracting Outsourcing part of your products or services is often a cheaper and more effective way of doing business. 9. What are your alternatives if one of the above happens? Can you find alternative sources of supply within a reasonable amount of time? Are you maintaining close contacts with a network of diverse suppliers? What is the magnitude of the . the time effort and expense involved in winning an order from a new client are much greater than anticipated. there are always potential risks associated with this approach. the actual staff effort in implementing a new accounting system turns out to be much greater than budgeted. Typical examples of problems with subcontractors are: • They decide to increase their price substantially. Typical examples of situations resulting in cost overruns are the following: the construction of a new annex building takes much more time and effort than projected.
if the industry's growth rate drops.. etc. rent and other overheads. Positive increases (more sales than) would require more working capital for inventory. How to Prepare Your Business Plan 188 financial or image damage you will be facing if one of the above events prevents you from fulfilling your obligations towards your own clients? Are your agreements with your subcontractors suitable for minimizing your risks? 10. Here are some examples: • Your sales volume rises much more rapidly than you assumed. What would be the effect of deviating from planned sales in your case? (For example. They may occur for many reasons.UNCTAD. etc. A decrease in sales means difficulties in financing fixed costs such as wages. How can you increase your production capacity in the short term? How do you quickly find additional suitable employees? Can you outsource some of the work? • Your cash flow increases more than expected. However. Such variations can have an important impact on your financial situation whether they are positive or negative. Market • Sales variation. What do you do with your extra cash? Can you negotiate with your bank and repay your long-term debts . In your business plan you have made assumptions about the structure of the competitive situation in your market. Major variations from your planned level of sales cannot be excluded. accounts receivables. You should also think about how you would deal with the challenge if the business developed much better than you assumed. Managing opportunities In your contingency plan you should not only consider possible deviations from your assumptions that would mean extra risks for your business.) • Stronger competition.
Strengths and weaknesses are internal factors over which you have some influence. • Exploit opportunities. etc. . An important competitor decides to sell his business at a good price. • Develop strategies to deal with threats. What would you do? Buy the whole company and integrate it into yours? Buy only the assets? Buy only the clients? A prominent businessperson once said: My job gets difficult in two situations: when the business goes very badly and when the business goes very well.UNCTAD. How to Prepare Your Business Plan 189 earlier? What is the optimum way to invest the money: expand the business of the company. who is retiring. buy securities. opportunities and threats) analysis while you are planning your business. Specifically. Opportunities and threats are external issues that you cannot control. D. a SWOT will be of value in helping you to: • Build on your strengths. • Your weaknesses. SWOT analysis It is recommended that you conduct a SWOT (strengths. weaknesses. A SWOT analysis will help you in structuring your thoughts.? • Your major competitor sells his business. acquire another firm. analysing your risks and setting up your strategy. for example because there is no successor to the owner.
weaknesses. Strengths and weaknesses Area Production process Management Marketing Intellectual property Premises Strength Reliable machinery with good availability.UNCTAD. Trade secrets. Weakness Poor automation and low efficiency. Information technology Poor in-house IT support to users. opportunities and threats are given in tables X. Modern networks and software/hardware of high capacity. How to Prepare Your Business Plan 190 Typical examples of strengths. . Excellent name in the market. Good cash flow. Creative and good at selling. Finance Source: UNCTAD. Low rent and adequate space available for expansion. Expiring patent. Remote location.2. Debt burden. Poor market research capability.3.2 and X. Inadequate experience in finance planning. Table X.
Threat - Change of habits in market enhances interest in product. - Competition Labour market Financial markets Exchange rates Cheaper imported material. Competition fragmented.3. Some small competitors sell at lower prices. How to Prepare Your Business Plan 191 Table X. The analysis can be particularly effective if people are open. Increasing interest rates result in an increase of expenses. A SWOT analysis is performed by the management team of the entity. Opportunity to sell environmentally friendly products. Locally available skills. realistic. Environmental laws Government policies Limitation on imports of some materials prohibits expansion.UNCTAD. No single strong competitor. Source: UNCTAD. Experience shows that strategic workshops held at yearly intervals produce extraordinary results. self-critical and honest to themselves when it comes to identifying and defining their strengths and weaknesses. at best in an informal and relaxing environment outside the company and away from the hectic pace of daily operations. Disruptive strikes. Opportunities and threats Area Economic trend Market Opportunity Growth makes it easy to get higher prices. Prices are not very competitive for some export markets. Reduction of taxes increases profits. .
Or for expenses incurred during the past year but not payable until the following year. Some businesses that sell consumer products such as furniture or television sets will carry accounts for several months and charge interest. credit balances. . Amortization: Gradual reduction of a loan (typically mortgage) through periodic back payments. Companies to write off intangible rights or assets such as goodwill. Accounts receivable can also include revolving accounts.). The “assets” side of the balance sheet provides information on the employment of funds. equipment. inventory. Assets: Accounting term for everything a company owns and which has a monetary value listed in the balance sheet (cash. Appreciation: An increase in an asset's value. How to Prepare Your Business Plan 192 GLOSSARY Accounts payable: Money owed by a company to its suppliers for the purchase of goods or services bought on credit. Accounts receivable: Money owed to a business by its customers. The issuer promises to repay the debt on time and in full. Balance sheet analysis: Assessment of the figures and ratios in the balance sheet and income statement in order to appraise the standing and creditworthiness of a company or to evaluate the securities it has issued for investment policy reasons. such as department store or gasoline credit cards. real estate. patents or copyrights also use this accounting procedure.UNCTAD. etc. However. Balance sheet: A statement of the assets and liabilities of a business at a given date. Accrual liabilities: Items entered on the “liabilities” side of the balance sheet to account for income already received during the past financial year. Bond: Debt instrument denominated in a round amount that pays a set amount of interest on a regular basis. Bonds are bought and sold on the market. the costs of the products to be delivered will occur in the new fiscal year. whereas the “liabilities” side details the procurement of funds (financing) and the composition of the shareholders’ equity.
in which the funds to meet expected expenses were originally stored. whichever is lower. Fixed assets are depreciated in the accounts by regularly reducing their book value in the balance sheet. How to Prepare Your Business Plan 193 Book value: The value at which assets are carried on the books of account. for example. Cash flow: The flow of money payments to or from a firm. This can be. Depreciation: The decrease in value of an asset through wear and tear or other factors limiting its usefulness. Bottom line: Accounting term for the net profit or loss. The name is derived from the leather bag. Generally. At the same time this amount is subtracted from the inventory in the balance sheet. land. securities or accounts receivable. Call option: Agreement that gives an investor the right but not the obligation to buy a stock. Cost of goods sold: A company classifies all goods and services acquired for later sale as inventory. When the company sells goods. machinery. The book value of a share is the company’s net worth (the difference between a company's assets and its liabilities) divided by the number of shares outstanding. . Cash: Money in the company’s current accounts in a bank and petty cash available in the office. fixed assets are shown at cost less normal depreciation while inventories may be made at cost or market. or “bougette”.UNCTAD. the amount that was originally paid for the goods is recorded in the income statement’s “cost of goods sold” account. In an operating budget the planned costs and revenues. Collateral: Property that borrowers are obliged to turn over to lenders if they are unable to repay a loan. expenditures and income are compared. commodity or other instrument at a specified price within a specific time period. Budget: A plan of future income and expenses during a specified period. such as one year. Capital increase: Increasing the capital stock (share capital) by issuing additional shares or participation certificates against cash in the case of a corporation (joint stock company) or adding to the capital of different types of business structures. including in-kind contributions. buildings. Expenditures are sometimes referred to as “negative” cash flow. bond. inventory of finished or unfinished goods..
“sales” refers to cash received over the counter in exchange for pizzas. Short-term bank loan or notes payable: Amounts borrowed from the bank for less than a year. 2. services provided. Revolving credit: A line of credit that may be used repeatedly up to a specified total. Return on equity: An important measure of how much the company earns on the investment of its shareholders. In some cases. For department stores. rents and royalties. Revenue: Money a company takes in. Shareholders’ equity: The cash the shareholders invested in the business to start it. including interest earned and receipts from sales. Share: A form of security representing a portion of the nominal capital of a company entitling the owner to a proportion of distributed profits and of residual value if the company goes into liquidation. Shares further entitle the holder to vote at annual general meetings and elect directors (equity paper). the amount includes receipts from rents and royalties.UNCTAD. 3 or 6 months. Return on investment: An important measure of how much the company earns on the money the company itself has invested. plus any retained earnings and reserves. plus any additional contribution they have made to the business since then. with periodic full or partial repayment. This position can include loans that are outstanding and are due for payment within the next 12 months. Sales: Money a company receives from the goods and services it has sold. How to Prepare Your Business Plan 198 Retained earnings: Accounting earnings that are not paid out as dividends. “sales” includes cash received. . Security: A financial certificate that indicates that the holder owns a share or shares of a company (stock) or has loaned money to a company or government organization (bond). It is calculated by dividing a company's net profit (income) by the total shareholders' equity. but are retained by the firm for reinvestment in its operations. It is calculated by dividing the company's net profit (income) by its total assets. This measure is also called "return on assets". usually 1. charge account purchases and credit card purchases. For a business such as a pizza takeaway. In this case “sales” does not always equal “cash”.
UNCTAD. How to Prepare Your Business Plan 199 Solvency: Ability of a borrower to meet maturing obligations as they become due. this is the number of times an asset is replaced during a set period. as well as some combination of profits. within a stipulated time and for a certain price. the volume of shares traded on the exchange on a given day. Preferred stocks provide no voting rights but have a set. such as through the use of depreciation and amortization of assets. Also. "turnover" refers to the number of employees replaced during a certain period divided by the total number of employees. such as shares of stock. preferred shares or royalties. Venture capital: Financing for new businesses. guaranteed dividend payment. Also. In trading. In some countries the term refers to a company's annual sales volume. Stock: An investment that represents part ownership of a company. In employment matters. Stock option: An agreement allowing an investor to buy or sell something. claims on debtors who have become insolvent are written off. it is a method of employee compensation that gives workers the right to buy the company's stock during a specified period of time at a stipulated exercise price. investors may receive a say in the company's management. Turnover: In accounting terms. Write-off: Charging an asset amount to expenses or losses. There are two different types of stock: common and preferred. Also called shares. In return for venture capital. . Common stocks provide voting rights but no guarantee of dividend payments.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview.
|
https://www.scribd.com/doc/48283120/Business-development-plan
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
CodePlexProject Hosting for Open Source Software
I am building a module, which will have an apiController with 2 functions:
get userid - return a list of ints (list of favorite pages ids)
get user id + page id - save to DB
I created this record:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.ContentManagement.Records;
namespace YIT.FavoriteArticles.Models
{
public class UserFavoriteArticleRecord : ContentPartRecord
{
public virtual int userId { get; set; }
public virtual int articleId { get; set; }
}
}
My problem is that in order to create a migration i need this record to be a content part,
which means that in order to create instances of this record, i need to associate the content parts to a page.
How can I build this controller with a migration or just connect it to a table I created in the database without the record instances appearing in the admin gui?
Thanks :)
Why did you derive from ContentPartRecord? All you need is an Id column.
if I don't derive from contentpartRecord, AND create a migration with codegen,
how would a be able to create record instances (and save in DB) with my apiController?
And how would I be able to get records based on the userId?
If you have an Id properly defined, it will get mapped, and you can inject an IRepository<T> to manipulate the table.
When I use the Create method of Irepository, do I need to give an id to the record I'm passing it?
or does it generate the id?
for example, is this good enough?
public HttpResponseMessage AttachArticleToUser(int userId, int articleId)
{
try
{
UserFavoriteArticleRecord record = new UserFavoriteArticleRecord();
record.articleId = articleId;
record.userId = userId;
_repository.Create(record);
return Request.CreateResponse(HttpStatusCode.OK, "1");
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, ex.Message);
}
}
And another question, do I need to add something to the migration automatically created for the module by code genartion?
It does generate it.
Your migration should set-up the Id column something like this: Column<int>("Id", column => column.PrimaryKey().NotNull());
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later.
|
http://orchard.codeplex.com/discussions/405383
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
GameFromScratch.com
In this tutorial we are now going to implement a web app end to end using YUI and hosted in Node. It isn’t actually going to do anything much, but it will illustrate everything you need to create a client and server in JavaScript using YUI App and Node. Over time we will add more bells and whistles, but there is actually everything you need here to create a full functioning web application.
After looking in to it a little closer, YUI is incredibly well documented, but actually implementing YUI App Framework in a real world environment there are gaps of information missing. Generally all you are going to find is samples with a gigantic HTML files where all of the script is located in a single file, which obviously isn’t good form nor very maintainable. Unfortunately, when you actually set about splitting your YUI App into separate files and templates, you are completely on your own! In fact, this tutorial may in fact be the first one on the subject on the internet, I certainly couldn’t find one.
That said, there are still some great resources I referred to over and over well figuring this stuff out. First and foremost, was the App Framework link I posted earlier. It effectively illustrates using models and views, just not how to organize them across files in a complex project. The GitHub contributor app was another great sample, but it again, was effectively one giant HTML file. Finally there is the photosnear.me application’s source code up on GitHub. It is a full YUI App/NodeJS sample and is certainly worth reading, but as an example for people learning it is frankly a bit too clever. Plus it renders templates out using Node, something I wanted to avoid.
Alright, lets do a quick overview of how program flow works, don’t worry, it’s actually a lot less complicated than it looks. It is initially over-engineered for what it ends up accomplishing. However, in the end you basically have the bones of everything you need to create a larger more complex application and a code structure that will scale with your complexity.
This ( in the image to the left ) is the file hierarchy that we are about to create. In our root directory are two files, server.js which is our primary NodeJS application, while index.html is the heart of our web application, and where the YUI object is created.
Additionally, in a folder named scripts we create a pair of directories models and views. Models are essentially your applications data, while Views are used to display your data. Finally within the views folder we have another folder templates which is where our handlebar templates reside. If you have done any PHP or ASP coding, templates are probably familiar to you already. Essentially they are used to dynamically insert data into HTML, it will make more sense shortly.
We are going to implement one model, person.js, which stores simple information about a Person, and one view person.View.js which is responsible for displaying the Person’s information in the browser, and does so using the person.Template.
Now lets actually take a look at how it all works, in the order it is executed.
First we need our Node based server, that is going to serve the HTML to the browser ( and do much much more in the future ). Create a new file named server.js
var express = require('express'),
server = express.createServer();
server.use('/scripts', express.static(__dirname + '/scripts'));
server.get('/', function (req, res) {
res.sendfile('index.html');
});
server.get('*', function (req, res) {
res.redirect('/#' + req.url, 302);
});
server.listen(process.env.PORT || 3000);
Essentially we are creating an express powered server. The server.use() call enables our server to serve static ( non-dynamic ) files that are located in the /scripts folder and below. This is where we serve all of our javascript and template files from, if we didn’t add this call, we would either need to manually map each file or you will get a 404 when you attempt to access one of these files on server. Next set our server up to handle two particular requests. If you request the root of the website ( / ), we return our index.html file, otherwise we redirect back all other requests back to the root with the url appended after a hash tag. For more details, read this, although truth is we wont really make much use of it. Finally we start our server to listen on port 3000 ( or process.env.PORT if hosted ). Amazingly enough, these 9 lines of code provide a full functioning if somewhat basic web server. At this point, you can open a browser and browse to, well, that is, once you start your server.
Starting the server is as simple as running node server.js from your command line. This assumes you have installed NodeJS and added it’s directory to your PATH environment variable, something I highly recommend you do. Now that we have our working server, lets go about creating our root webpage index.html.
<!DOCTYPE html>
<html>
<head>
<title>GameFromScratch example YUI Framework/NodeJS application</title>
</head>
<body>
<script src=""></script>
<script src="/scripts/models/person.js"></script>
<script src="/scripts/views/person.View.js"></script>
<script>
YUI().use('app','personModel','personView', function (Y) {
var app = new Y.App({
views: {
personView: {type: 'PersonView'}
}
});
app.route('/', function () {
var person = new Y.Person();
this.showView('personView',{model:person});
});
app.render().dispatch();
});
</script>
</body>
</html>
The most important line here is the yui seed call, where we pulling in the yui-min.js, at this point we have access to the YUI libraries. Next we link in our model and view, we will see shortly. Ideally you would move these to a separate config file at some point in the future as you add more and more scripts. These three lines cause all of our javascripts to be included in the project.
The YUI().use call is the unique way YUI works, you pass in what parts of YUI library you want to access, and it creates an object with *JUST* that stuff included, in the for of the Y object. In this case, we want the YUI App class ( and only it! ) from the YUI framework, as well as our two classes personModel and personView, which we will see in a bit more detail shortly. If you use additional YUI functionality, you need to add them in the use() call.
We create our app and configure it to have a single view named personView of type PersonView. Then we set up our first ( and only route ), for dealing with the URL /. As you add more functionality you will add more routes. In the event a user requests the web root, we create a person model. Next we show the personView and pass it the person model we just created. This is how you connect data and views together using the YUI app framework. We then render our app and call dispatch(), which causes our app url to be routed ( which ultimately causes our person model and view to be created. If you aren’t used to Javascript and are used to programming languages that run top down, this might seem a bit alien to you at first. Don’t worry, you get used to it eventually… mostly).
Now lets take a look at our model person.js
YUI.add('personModel',function(Y){
Y.Person = Y.Base.create('person', Y.Model, [],{
getName:function(){
return this.get('name');
}
},{
ATTRS:{
name: {
value: 'Mike'
},
height: {
value: 6
},
age: {
value:35
}
}
}
);
}, '0.0.1', { requires: ['model']});
Remember in index.html in the YUI.use() call where we specified personModel and personView, this is how we made those classes accessible. By calling YUI.add() we add our class into the YUI namespace, so you can use YUI.use() to included them when needed, like we did in index.html.
Next we create our new class, by deriving from Y.Model using Y.Base.create(), you can find more details here. We declare a single function getName(), then a series of three attributes, name, height and age. We set our version level to ‘0.0.1’ chosen completely at random. When inside a YUI.add() call, we specify our YUI libraries as a array named requires instead of in the YUI.use call. Otherwise, it works the same as a .use() call, creating a customized Y object consisting of just the classes you need.
Now lets take a look at the view,']});
Like person.js, we use YUI.add() to add personView to YUI for availability elsewhere. Again we used Y.Base.create(), this time to extend a Y.View. The rest that follows is all pretty horrifically hacky, but sadly I couldn’t find a better way to do things that way I want. The first horrible hack is that:this, which is simply taking a copy of PersonView’s this pointer, as later during the callback, this will actually represent something completely different. The next hack was dealing with including Handlebar templates, something no sites that I could findon the web illustrate, because they are using a single HTML file (which makes the task of including a template trivial).
The problem is, I wanted to load in a Handlebars template( we will see it in a moment ) in the client and there are a few existing options, none of which I wanted to deal with. One option is to create your template programmatically using JavaScript, which seemed even more hacky ( and IMHO, beats the entire point of templating in the first place! ). You can also precompile your templates, which I will probably do later, but during development this just seemed like an annoyance. The photosnear.me site includes them on the server side using Node, something I wanted to avoid ( it’s a more complex process over all, and doesn’t lend itself well to a tutorial ). So in the end, I loaded them using Y.io. Y.io allows you to make asynchronous networking requests, which we use to read in our template file person.Template. Y.io provides a series of callbacks, of which we implement the complete function, read the results as our template, “compile” it using Y.Handlebars, we then “run” the template using template(), passing it the data it will populate itself with. In our case, our name, age and height attributes from our personModel. template() after executing contains our fully populated html, which we set to our views container using the setHTML() method.
Finally, lets take a look at person.Template, our simple Handlebars template:
<div align=right>
<img src="" alt="GameFromScratch HTML5 RPG logo" />
</div>
<p><hr /></p>
<div>
<h2>About {{name}}:</h2>
<ul>
<li>{{name}} is {{height}} feet tall and {{age}} years of age.</li>
</ul>
</div>
As you can see, Handlebar templates are pretty much just straight HTML files, with small variations to support templating. As you can see, the values {{name}}, {{height}} and {{age}} are the values that are populated with data. They will look at the data passed in during the template() call and attempt to find matching values. This is a very basic example of what Handlebars can do, you can find more details here.
Now, if you haven’t done so, run your server using the command node server.js, if you have set node in your PATH.
Then, open a web browser and navigate to, and if all went well you should see:
Granted, not very exciting application, but what you are seeing here is a fully working client/server application with a model, view and templating . There is one thing that I should point out at this point… in the traditional sense, this isn’t really an MVC application, there is no C(ontroller), or to a certain extent, you could look at the template as the view, and the view as the controller! But don’t do that, it’s really quite confusing! Just know, we have accomplished the same goals, our data layer is reusable and testable, our view is disconnected from the logic and data. Don’t worry, the benefits of all of this work will become clear as we progress, and certainly, once we start adding more complexity.
In the near future, we will turn it into a bit more of an application.
You can download the project source code here.
Programming
YUI, Tutorial, JavaScript, Node, Pipeline, HTML
|
http://www.gamefromscratch.com/post/2012/06/22/Creating-a-simple-YUI-Application-Framework-and-Node-app.aspx
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
GameFromScratch.com
When it comes to programming languages, I literally use dozens, but when it comes down to an all other things being equal decision my go to language of choice tends to be C#. One of the big plus sides of C# is the wonderful LINQ ( Language Integrated Query ). LINQ makes heavy use of lambda (closures) a feature lacking until recently in C++. Now with lambda expressions part of the C++ language LINQ for C++ is now a possibility. It exists as a single hpp file you add to your project.
If you aren’t already familiar with LINQ, here is a simple example in C#. It’s a simple scoreboard that sorts the results by name, then by score, then totals and averages all of the scores. As you can see, it’s a very compact and clean way to access data.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Entry
{
public Entry(string name, int score)
{
this.name = name;
this.score = score;
}
public string name { get; set; }
public int score { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Entry> scoreEntries = new List<Entry>();
scoreEntries.Add(new Entry("mike", 42));
scoreEntries.Add(new Entry("bob", 99));
scoreEntries.Add(new Entry("doug", 99));
scoreEntries.Add(new Entry("steve", 12));
var sortedByName = scoreEntries.OrderBy(item => item.name).ToList();
Console.WriteLine("Sorted by score");
sortedByName.ForEach(item => { Console.WriteLine(item.name + " " + item.score); });
Console.WriteLine("\nSorted by name");
var sortedByScore = scoreEntries.OrderBy(item => item.score).ToList();
sortedByScore.ForEach(item => { Console.WriteLine(item.name + " " + item.score); });
var totalOfScores = scoreEntries.Where(item => item.score > 0)
.Sum(item => item.score);
var averageScore = scoreEntries.Average(item => item.score);
Console.WriteLine("\nTotal of scores == " + totalOfScores + " Average Score == " + averageScore);
}
}
}
Now let's take a look at the C++ version using cpplinq:
#include <string>
#include <list>
#include "cpplinq.hpp"
#include <iostream>
class Entry{
public:
Entry::Entry(std::string name, int score){
this->name = name;
this->score = score;
}
std::string name;
int score;
};
int main(int argc, char **argv)
{
std::list<Entry> scoreEntries;
scoreEntries.push_back(Entry("mike", 42));
scoreEntries.push_back(Entry("bob", 99));
scoreEntries.push_back(Entry("doug", 99));
scoreEntries.push_back(Entry("steve", 12));
using namespace cpplinq;
auto sortedByName = from(scoreEntries)
>> orderby_ascending([](const Entry & entry){ return entry.name; })
>> to_vector();
auto sortedByScore = from(scoreEntries)
>> orderby_descending([](const Entry & entry){ return entry.score; })
>> to_vector();
std::cout << "Sorted by name" << std::endl;
from(sortedByName)
>> for_each([](const Entry & entry){ std::cout << entry.name << " " << entry.score << std::endl; });
std::cout << std::endl << "Sorted by score" << std::endl;
from(sortedByScore)
>> for_each([](const Entry & entry){ std::cout << entry.name << " " << entry.score << std::endl; });
auto totalOfScores = from(scoreEntries)
>> select([](const Entry & entry){ return entry.score; })
>> sum();
auto averageScore = from(scoreEntries)
>> select([](const Entry & entry){ return entry.score; })
>> avg();
std::cout << std::endl << "Total of scores == " << totalOfScores << " average score == " << averageScore << std::endl;
return 0;
}
A few obvious differences. Cpplinq statements start with the from methods defining the type of data source to perform on. In this case I used the default from() which takes a standard C++ STL type. There are also from__array() and from_range() for working with arrays and iterators respectively. Next the . (dot) operator has been replaced with the >> operator. Of course the lambda syntax is different as well ( C++’s is much uglier ), otherwise at the end of the day, it is very similar to LINQ in both look and execution.
If you are new to C++ and are struggling to wrap your head around the uses for lambdas, give cpplinq a shot and you will quickly see their value!
Programming
CPP
|
http://www.gamefromscratch.com/post/2014/04/04/LINQ-for-CPP-with-cpplinq.aspx
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
So I'm currently trying to unpack a struct that has the following format, written in C:
{
volatile bool
volatile float
bool
}
Udp.write(((byte*)&pm), sizeof(struct PressureMonitor));
import socket
import time
import struct
UDP_IP = '192.168.1.222'
UDP_PORT = 8742
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024)
print(len(data))
print(struct.unpack('cfc',data))
time.sleep(.01)
You need to tell
struct.unpack that your data isn't padded.
The format string
'cfc' doesn't contain a byte order / alignment character, which is equivalent to specifying
'@' as the byte order / alignment character, so you get native byte ordering and native alignment. Float data is 4 bytes wide and should be aligned on a 4 byte boundary, but since you have a one byte bool before your float 3 padding bytes get added after that first bool to ensure the float is correctly aligned.
You can specify native byte ordering with no padding with a
'=cfc' format string. But it would be better to explicitly indicate the correct byte ordering. If the data is being sent from an Intel machine, that would be
'<cfc'. Please see Byte Order, Size, and Alignment in the
struct module docs for details.
|
https://codedump.io/share/EhYegBHxKtqf/1/unpacking-a-struct-containing-a-boolean-in-python
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
These notes are for developing a C++ application. If you are a developing a .NET/C# application please see our .NET Wiki instead.
Checklist
Before we begin, you’ll need the following:
Install the SDK
- After downloading the SDK, extract it to a folder in your home directory.
- Open the Terminal.
- Change directories to the SDK files you just extracted.
- Run
sudo make allto install the library to your machine.
Run the Samples
You should now be able to run the samples. Change directories to the
./bin folder and run some samples:
The Hello World example loads up Google and renders it to a JPG on disk:
./awesomium_sample_hello
The WebFlow sample depends on SDL 1.2 and OpenGL, demonstrates a simple 3D browser:
./awesomium_sample_webflow
Using Awesomium
To use most of the Awesomium API in your C++ code, just include the following:
#include <Awesomium/WebCore.h>
To link against Awesomium 1.7.4 in your applications, just add “-lawesomium-1-7”
g++ main.cpp -lawesomium-1-7
|
http://wiki.awesomium.com/getting-started/setting-up-on-linux.html
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
This document is the Software Development Plan for the GHOSTS project.
This document includes the following chapters :
GHOSTS is a software application intended to help genealogists in their activities. Those activities are the following :
More than a computer tool, GHOSTS aims to be a genealogical helper : its services shall be adapted to the Genealogist behavior, and answer to realist use-cases.
On a technical point of view, GHOSTS shall rely on the state-of-the-art technologies ; it shall intensively include effective open-source standards, in order to provide efficiency in its development (do not re-invent the wheel) and long-time reliability and maintainability (conformity to open-source standards should provide those benefits). To improve long-time reliability, GHOSTS shall depend only on free software components.
The GHOSTS development standards shall comply with the GNU standards (ref. TBD).
The instantiation of those standards on this project is provided in the following paragraph, highlighting particular issues and deviations.
Requirements are developed at three levels:
Traceability shall be established between application requirements and software high level requirements
Each requirement shall have an unique identifier base on the format REQ_[GHOSTS|LIBGEDCOMPARSER|GEDCOMVIEWER]_X where X is a sequence number (1 or more digits).
Graphical representation of software design shall be performed using UML diagrams.
Naming:
Mixity with other coding rules may occur since some external libraries complies with other rules (for instance in Gtk-- all the methods use low case and underscore to separate words, so derived class of Gtk-- class can have inconsistency in its public interface).
Documentation:
Each namespace shall be documented, presenting the following information:
Each class shall be documented, presenting the following information :
Each public method shall be documented, presenting the following information:
Such documentation shall be written as comments in a style allowing the formatting of those comments in a more displayable way (useable by doxygen of doc++ for instance).
The software life cycle is an Y life cycle : the development of GHOSTS is motivated by the overall goal expressed in the Vision, and constrained by the architecture chosen according to state-of-the-art and reliability / maintainability objectives. The Vision and Architecture are described in this SDP.
From those information (Vision and Architecture) starts the requirement analysis activity. This activity consists in writing down use-cases and man-machine interface specifications. The use-cases describe activities of the genealogist, without considering software as a means to realize or to help with this activity. The man-machine interface specifications introduces software aspects to realize use-cases with the assistance of a computer. Use-cases and man-machine interface are described in non deliverable documents. As a summary of those use-cases and man-machine interface, a list of application requirements is written in the requirement analysis document.
After the requirement analysis starts the design activity. This activity consists in two phases :
After the design activity starts the coding activity. This activity is the implementation of the design in the target programming language, mainly C++ in this software.
The overall verification process is the following :
The verification process results are not stored. Defects reports are submitted when their correction is not immediately performed.
The overall software life cycle is iterative : the vision is developed incrementally. Each increment engages the following activities.
Objecteering, Linux Mandrake 8.1, gcc 3.2, savannah, cvs, Mozilla, autotools, flex / bison, doc++
|
http://www.nongnu.org/ghosts/developers/contributing/plans/sdp.html
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How to encrypt a field before to record it?
I would like record a field (wich is a password) encrypted in my database. I have to encrypt it directly inside my module not in my PostgreSQL database. I did the following :
import md5 import os from openerp.osv import osv, fields ###### Encrypton of passwords ###### CRYPT64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' def make_salt(): sbytes = os.urandom(8) return ''.join([CRYPT64[ord(b) & 0x3f] for b in sbytes]) def md5crypt(password, salt, magic='$1$'): if salt is None: salt = make_salt() m = md5.new() m.update(password + magic + salt) mixin = md5.new(password + salt + password).digest() for i in range(0, len(password)): m.update(mixin[i % 16]) # Then something really weird... # Also really broken, as far as I can tell. -m i = len(password) while i: if i & 1: m.update('\x00') else: m.update(password[0]) i >>= 1 final = m.digest() return final md5crypt(pass_pid) ###### Creation of password table ###### class password(osv.osv): _inherit = 'res.partner' _columns = { 'passwords': fields.one2many('password.table','name_pid','user_pid') } password() class password_table(osv.osv): _name="password.table" _columns = { 'name_pid':fields.many2one('res.partner', 'name', required=True), 'user_pid':fields.char("UserName", size=128, required=True), 'host_pid':fields.char("IP/HostName", size=128, required=True), 'pass_pid':fields.function(md5crypt, type="text", string="password", size=128, required=True), 'com_pid':fields.text("Comment") } password_table()
The error is about my parameters but I don't know at all how to modify that!
This is a python programming question, not an openerp issue/ error/ question. I will try to point you in the right direction, but you are going to have to get someone that knows how to program python to do this programming for you, this forum is for openERP questions.
First you should move the encryption function into
class password_table(osv.osv):
Second, you want to use this function to encode and store the password, so you have to create a function that will encode when saving the field and another for viewing it.
read how to use functions here:
'pass_pid':fields.function( _view_function, fnct_inv=_store_function, type="text", string="password", size=128, required=True),
Third you cannot just cut and paste code from other sources, you have to massage it into openERP so you will have to rewrite the function accordingly. Your functions will have to start something like this:
def _store_function(self, cr, uid, id, name, value, args=None, context=None):
If you need help beyond this you should contact an openERP partner to write the module for you. Custom coding is a service they are happy to post the error you are getting? That would help give you a better answer.
I'm getting this error: "File "/home/integration/oe7_1/addons/password_module/password.py", line 59, in <module> md5crypt(pass_pid) NameError: name 'pass_pid' is not defined"
|
https://www.odoo.com/forum/help-1/question/how-to-encrypt-a-field-before-to-record-it-24653
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
That feels like an AvroMode-related exception; which version of Crunch are
you using?
J
On Thu, Aug 21, 2014 at 12:45 PM, Danny Morgan <unluckyboy@hotmail.com>
wrote:
> Hi Guys,
>
> Love crunch but having some trouble recently using Avro records. I think
> someone needs to write a Crunch book.
>
> I'm trying to aggregate hourly visits to a page by each user. I do one
> pass to parse the records and then I try to "group by" unique users and
> hour and count the number of times they visited as well as their first
> visit time in the hour. Here's the Avro schema
>
> {"namespace": "com.test",
> "type": "record",
> "name": "Visit",
> "fields": [
> {"name": "dateid", "type": "int"}, // Year Month Day Hour
> in PST as an integer e.g. 2014081103
> {"name": "userid", "type": "string"},
> {"name": "vcount", "type": ["long", "null"]},
> {"name": "firsttimestamp", "type": ["long", "null"]} // Unixtime
> stamp of first visit
> ]
> }
>
> Here I do the parsing, at first vcount and firstvisit aren't set.
>
> PTable<Visit, Pair<Long, Long>> visits =
> parsed.parallelDo("visits-parsing", new VisitsExtractor(),
> Avros.tableOf(Avros.specifics(Visit.class),
> Avros.pairs(Avros.longs(), Avros.longs())));
>
> The relevant line from VisitsExtractor:
> emitter.emit(Pair.of(visit, Pair.of(1L, log.timestamp())));
>
> Everything up to this point works fine, now I want to count up the unique
> visitors and the minimum timestamp.
>
> PTable<Visit, Pair<Long, Long>> agg =
> visits.groupByKey().combineValues(Aggregators.pairAggregator(Aggregators.SUM_LONGS(),
> Aggregators.MIN_LONGS()));
>
> The above seems to work fine too, now I want to create new Visit classes
> and fill in the count and minimum timestamp fields.
>
> PCollection<Visit> count_visits = agg.parallelDo("visits-count",
> new DoFn<Pair<Visit, Pair<Long, Long>>, Visit>() {
> @Override
> public void process(Pair<Visit, Pair<Long, Long>> p,
> Emitter<Visit> emitter) {
> Visit v = Visit.newBuilder(p.first()).build();
> v.setVcount(p.second().first());
> v.setFirsttimestamp(p.second().second());
> emitter.emit(v);
> }
> }, Avros.specifics(Visit.class));
> }
>
> count_visits.write(To.textFile(outputPath), WriteMode.OVERWRITE);
>
> Here's the error:
> 2014-08-21 15:09:26,245 ERROR run.CrunchReducer
> (CrunchReducer.java:reduce(54)) - Reducer exception
> java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record
> cannot be cast to com.test.Visit
> at com.test.Logs$1.process(Logs.java:49)
> at com.test.Logs$1.process(Logs.java:1)
> at org.apache.crunch.impl.mr.run.RTNode.process(RTNode.java:98)
> at
> org.apache.crunch.impl.mr.emit.IntermediateEmitter.emit(IntermediateEmitter.java:56)
>
> So I'm pretty sure the problem is this line:
>
> Visit v = Visit.newBuilder(p.first()).build();
>
> specifically p.first() should be a Visit type but I guess it isn't. I
> assume the output of the groupBy operation in the reducers is serializing
> the key but not using the correct Avro type to do it?
>
> Also I don't think I understand when I should be using Avros.records()
> versus Avros.specifics() when I have a generated avro file.
>
> Thanks!
>
> Danny
>
|
http://mail-archives.apache.org/mod_mbox/crunch-user/201408.mbox/%3CCANb5z2JwerKUq19F1k3c+YF_c+3QWoUbqYJ0n+W_1vC53-qM6g@mail.gmail.com%3E
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
Wow ! IronPython goes open source, and Jim Hugunin joins the CLR team at MS.
Wow ! IronPython goes open source, and Jim Hugunin joins the CLR team at MS.
Hardware acceleration: my first reaction to hearing about XML hardware acceleration was disbelief. Just another symptom of inappropriate application of XML, and code bloat in general, I thought. After all, XML seems to be the default formatting choice for any messaging job these days, irrespective of performance, interoperability or code ownership requirements. And so much enterprise coding reduces to shuffling data between UI layer, database and messaging format.
But then I thought again. Remember the 8087 ? CPUs didn't always have onboard FPUs. If you needed to do a lot of number crunching, you added the floating point capability. Likewise with graphics. CPUs used to do the bit blitting. As the demand for graphics applications increased, dedicated cards came onto the market that relieved the CPU of the graphics processing. Could we be seeing a similar trend for text ? After all, the string processing workload for the typical PC has been ever rising for the last ten years, with ever increasing volumes of email, HTML, XML etc. Maybe CPUs need specialised Text Processing Units alongside their FPUs and GPUs.
SSL &...
Insane.
Generators:.
Plan to throw six away: more levitt hacking last night. Really happy with the way the codebase is coming along at the moment. I've been working on this system since 2001. I've restructured and refactored so many times. For server infrastructure I started off with a plain medusa front end, and ZODB at the back. Then I switched to a Zope product approach, to leverage Zope's UI. Then I switched to a browser plug in implementation. Now I'm doing a standalone impl, that will probably use Twisted in a personal server deployment. And there were minor refactorings within those larger implementation decisions. I know Fred Brooks enjoined us to "plan to throw one away", but maybe I'm going too far. However, the upside is the implementation feels smaller and cleaner and far better factored.
clarkbw: my fave Skynyrd tune !
Generators: Python has them, and C# is proposing to add them. What are they ?
def GeneratorFunc( n): for i in range( n): yield i
for i in GeneratorFunc( 3): print "i=%d" % i
The call to GeneratorFunc does not execute any of the code inside the GeneratorFunc. Instead it returns an iterator object that we can use in the for loop at the bottom. The for loop implicitly calls the iterator's next() method, which in turn executes the code inside GeneratorFunc. Every time this happens, the yield keyword supplies the value to be returned by the iterator's next() method. The important thing to remember is that all the local variables, and stack state, inside the GeneratorFunc body are preserved between invocations of the iterator's next() method. All this may be a little clearer if we invoke the iterator directly rather than relying on for to do it...
def GeneratorFunc( n): for i in range( n): yield i
iter = GeneratorFunc( 3) while 1: print "i=%d" % iter.next()
All well and good, you may say. But where can I apply this idiom ? I can see tremendous leverage in two common coding areas: recursive tree walks and blocking IO handler code. More later...
Financial technology blogging: I ply my trade as a software developer in the City of London, working for wholesale banks. So do many of the developers I know. Since wholesale banks tend to be secretive and paranoid, most of us who develop trading systems don't talk about it much in public forums. I don't talk about my professional work at all on line. But a few people are starting to put their heads above the parapet...
A highly talented colleague Quant dev in S!
|
http://www.advogato.org/person/osullivj/diary.html?start=58
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
As per mocha documentation the use of arrow functions are discouraged.
Is this the same for Jasmine? I couldn't find any pointers on the topic in Jasmine documentation.
There is a really very interesting article you should not miss:
And this is a cite:
The new, better way
For every test (and their beforeEach/afterEach hooks), jasmine sets the receiver of each function to an initially empty object. This object, which is called userContext within Jasmine's source code, can have properties assigned to it, and gets blown away at the end of each test. In an attempt to address the issues we were having, we recently switched over to assigning variables to this object, rather than declaring them within describe and then assigning them. So our original code above now looked something like this:
describe('views.Card', function() { 'use strict'; beforeEach(function() { this.model = {}; this.view = new CardView(this.model); }); describe('.render', function() { beforeEach(function() { this.model.title = 'An Article'; this.view.render(); }); it('creates a "cardTitle" h3 element set to the model\'s title', function() { expect(this.view.$el.find('.cardTitle')).toContainText(this.model.title); });
So, what does that all mean? Should we use arrow function with jasmine?
And the answer should be - keep arrow functions in your code, except of this combination
// could be arrow describe("ListModel -", () => { // local context description interface IMyTestContext { items?: Heroe[]; ... } // could be arrow describe("Test items ", () => { // NOT AN ARROW - profit from Jasmine context passed as 'this' beforeEach(function() { var ctx: IMyTestContext = this.TestContext = {}; // TODO do some defaults with context ... }); // NOT AN ARROW - profit from Jasmine context passed as 'this' it("should ...", function() { var ctx: IMyTestContext = this.TestContext; // TODO ... test expecations ...
So,
beforeEach() and
it() do NOT use arrow - to profit from Jasmine context represented by
this
we can also introduce a global call
beforeEach
import * as something from "..."; beforeEach(function() { this.TestContext = {}; });
and now context is always there for us so we do not have to re-create it:
describe("Track Changed items ", () => { // NOT AN ARROW - profit from Jasmine context passed as 'this' beforeEach(function() { // created by global beforeEach above var ctx: IMyTestContext = this.TestContext;// = {};
Yes, that is really so amazing, that if a test runner will find some global
beforeEach... it will also run it before each test... awesome, is not it?
|
https://codedump.io/share/8TD3tHZGJu21/1/are-arrow-functions-recommended-in-jasmine-test-cases
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
Interface Block (GLSL)
GLSL shader input, output, uniform, and storage buffer variables can be grouped into Interface Blocks. These blocks have special syntax and semantics that can be applied to them.
Contents
Syntax
Interface blocks have different semantics in different contexts, but they have the same syntax regardless of how they are used. Uniform blocks are defined as follows:
interface_qualifier block_name { <define members here> } instance_name;
This looks like a struct definition, but it is not.
interface:
uniform MatrixBlock { mat4 projection; mat4 modelview; };
You could simply use projection to refer to it. So the interface name acts as a namespace qualifier.
The instance name can also.
Linking between shader stages allows multiple shaders to use the same block. Interface blocks match with each other based on the block name and the member field definitions. So the same block in different shader stages can have different instance names.
Input and output
Input and output blocks are designed to compliment each other. Their primary utility is with geometry or tessellation shaders, as these shaders often work with arrays of inputs/outputs.
Data passed between shader stages can be grouped into blocks. If the input is in a block, then the output must also be within a block that uses the same block name and members (but not necessarily the same instance name)..
Buffer backed
Uniform blocks and shader storage blocks work in very similar ways, so this section will explain the features they have in common. Collectively, these are called "buffer-backed blocks.").
shared is the default. This layout means that individual members cannot be optimized out. The name comes from the fact that if you provide the exact same definition (including array counts and the like) to two different programs, OpenGL guarantees that they will have the exact same member variable layouts. Thus, you can query layout information for one, and use it in another.
packed gives the implementation the maximum freedom. It can optimize out definitions, rearrange their orders, etc. The layout for a packed block must be queried regardless of how it is defined.
std140 and std430 are layouts that are explicitly defined by the OpenGL standard. Thus, not only are the layouts guaranteed between programs, they are guaranteed across implementations. This is useful for being able to build C or C++ structs that contain exactly the values in the proper order that GLSL's blocks will take.
std430 can only be used on shader storage blocks; it offers greater packing and smaller alignment guarantees than std140..
If GL 4.2 or ARB_shading_language_420pack is defined, then140.
Shader storage blocks.
|
https://www.opengl.org/wiki_132/index.php?title=Interface_Block_(GLSL)&oldid=6694
|
CC-MAIN-2017-04
|
en
|
refinedweb
|
.comment.event;32 33 import org.blojsom.blog.Comment;34 import org.blojsom.blog.Blog;35 36 import java.util.Date ;37 38 /**39 * Comment unmarked spam event40 *41 * @author David Czarnecki42 * @since blojsom 3.043 * @version $Id: CommentUnmarkedSpamEvent.java,v 1.1 2006/04/18 17:11:21 czarneckid Exp $44 */45 public class CommentUnmarkedSpamEvent extends CommentEvent {46 47 /**48 * Create a new event indicating a {@link Comment} was unmarked as spam in the system.49 *50 * @param source Source of the event51 * @param timestamp Event timestamp52 * @param comment {@link Comment}53 * @param blog {@link Blog}54 */55 public CommentUnmarkedSpamEvent(Object source, Date timestamp, Comment comment, Blog blog) {56 super(source, timestamp, comment, blog);57 }58 }
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
|
http://kickjava.com/src/org/blojsom/plugin/comment/event/CommentUnmarkedSpamEvent.java.htm
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
Opened 6 years ago
Closed 6 years ago
#16934 closed Uncategorized (invalid)
Tutorial 3: error in html editing
Description
In the section of tutorial 3 where we edit a new html file with:
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
I kept getting an error saying that the {% else %} statement was an invalid block.
I believe that it is supposed to be (% else %) as opposed to {% else %}
Change History (2)
comment:1 Changed 6 years ago by
comment:2 Changed 6 years ago by
The tutorial appears to be correct. Perhaps you have a typo or something missing in your own code. In any case, please do not use Trac for posting support questions -- instead use the django-users mailing list:
Please do reopen this ticket if it appears that there is an actual error in the tutorial.
If someone could please respond to this as soon as possible it would be greatly appreciated
|
https://code.djangoproject.com/ticket/16934
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
Opened 5 years ago
Last modified 10 months ago
#18392 new New feature
Use utf8mb4 encoding with MySQL 5.5 (40)
comment:1 Changed 5 years ago by
comment:2 Changed 5 years ago by
I don't know enough about MySQL and the ORM to answer your questions, I hope someone else does.
comment:3 Changed:
))"
From:
comment:4 Changed 5 years ago by?
comment:9 Changed 5 years ago by
As a workaround, you can make python understand 'utf8mb4' as an alias for 'utf8':
import codecs codecs.register(lambda name: codecs.lookup('utf8') if name == 'utf8mb4' else None)
comment:11 Changed 5 years ago by
comment:12 Changed 5 years ago by
The fix mentioned above has been merged to master () and released ()
comment:14 Changed 4 years ago by
comment:15 Changed 4 years ago by
comment:16 Changed 4 years ago by
comment:18 Changed 4 years ago by
comment:19 follow-up: 20 Changed 3 years ago by
comment:23 Changed 2 years ago by
One solution would be to reduce the INDEX size to 191 for mysql, like the example above:
col1 VARCHAR(500) CHARACTER SET utf8mb4, INDEX (col1(191))"
comment:24 follow-up: 25 Changed 2 21 months 21 months.)
Ohh and it _is_ possible to have indexes longer than 191, it just requires changing your db configuration, so Django should allow longer than 191 if it's told that it's ok.
comment:27 Changed 20 months ago by
Will that setting work nicely with migrations though? I think we need to know the index names for some operations like
AlterField. It seems problematic if we have a way that users can vary the index names without updating existing names.
comment:28 Changed 20 months ago by
I was thinking it wouldn't actually change the name of the index, but I haven't actually looked at the code. :)
comment:29 Changed 20 months 20 months ago by
I'm not thinking of limiting the _name_ of the index. The issue is "the maximum number of characters that can be indexed".
comment:31 Changed 20 months ago by
Thanks Collin, in that case your proposal makes more sense to me. It could be nice to get a consensus from more MySQL users though.
comment:32 Changed 19 months ago by
comment:33 Changed 19 months ago by
comment:34 Changed 19 months ago by
comment:35 Changed 19 months 18 months 17 months ago by
Yes, I based my proposal off of what WordPress did. WordPress limited the length of the index without limiting the length of the field itself. Django currently doesn't have that option.
comment:38 Changed 14 months ago by
comment:39 Changed 13 months ago by
comment:40 Changed 10 months.
|
https://code.djangoproject.com/ticket/18392
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
Java ArrayList is perhaps the simplest and one of the most used data structure implementation classes of the Java API Library. It is a part of the Java Collection Framework under the java.util package. On one hand, it behaves like a normal array, providing all the benefits of it and, on the other, it is a generic re-sizable collection implementation of the List interface. Java ArrayList is especially used for managing a large number of objects. This article attempts to provide some information of this utility class with a brief overview of its structure.
Java ArrayList Class Hierarchy
In short, Java ArrayList is a subclass of AbstractList and implements the List interface, and List is an extension of the Collection interface. As a result, we can declare an ArrayList object as any of the ways that follow:
- Collection<String> collection=new ArrayList<>();
- List<String> list=new ArrayList<>();
- ArrayList<String> alist=new ArrayList<>();
Figure 1: An ArrayList chart
Refer to the Java API Documentation for more details on the classification.
Java ArrayList Overview
While dealing with data structures in any programming language, we resort to low-level manipulation of data. Creating each element of the data structure dynamically and modifying them by directly manipulating references to it can be erroneous and also daunting at times. Direct manipulation may be necessary on occasion, yet when productivity is concerned, support from the API library comes in quite handy. Java Collection Framework contains many such prepackaged data structures, interfaces, and algorithms. Java ArrayList is one of them and can be used like the low-level arrays with some special connotation.
Java ArrayList uses an array as the internal programming construct to store elements. An array is nothing but a sequential collection same type of elements, accessed by their index values. Naturally, Java ArrayList also behaves in a similar manner. Here, the behavior is defined by the ready-made methods of the ArrayList class. Common operations are add/remove elements in various ways, determine if the list is empty, obtain the size of the list indicated by number of elements present currently, and so forth.
Constructors
Java ArrayList class contains three constructors, such as:
- ArrayList(): Constructs an empty list with an initial storage capacity of ten elements.
- ArrayList(Collection<? Extends E> c): Constructs a list containing elements in a pre-specified collection.
- ArrayList(int initialCapacity): Constructs an empty list, but we can override the default initial capacity.
Methods
There are various methods. A few of the commonly used are as follows:
- boolean add(E obj): Inserts an element at the end of the list.
- void add(int index, E obj): Inserts an element at the specified index. The elements at that location and subsequent locations are shifted to the right.
- void clear(): Makes the list completely empty by removing all elements.
- E remove(int index): Removes an element at the specified index and shifts any subsequent elements to the left.
- E get(int index): Returns an element at the index position.
- int indexOf(Object obj): Returns the index of the first occurrence of the element in the list, or returns -1 to indicate that the list does not contain the specified element.
- boolean contains(Object obj): Returns true if list contains the specified element; otherwise, returns false.
- boolean isEmpty(): Returns true is there is no element in the list; otherwise, returns false.
- int size(): Returns the count of elements in the list.
A Quick Example
package org.mano.example; import java.util.ArrayList; import java.util.Random; public class ArrayListDemo1 { public static void main(String[] args) { ArrayList<String> planets = new ArrayList<>(); planets.add("Mercury"); planets.add("Earth"); planets.add("Jupiter"); planets.add("Saturn"); System.out.println(planets); int index = planets.indexOf("Earth"); planets.remove(index); planets.add(1, "Venus"); System.out.println("Size = " + planets.size()); for (index = 0; index < planets.size(); index++) { System.out.println(planets.get(index)); } } }
Generic ArrayList
Java ArrayList is built to support generic types. That is the reason that the class refers to having elements of type E, such as ArrayList<E>. The E is replaced by the type of element such as String, Employee, and so on. There is a subtle difference between a normal array and Java ArrayList: Here we do not create an ArrayList of objects, rather we create an ArrayList object that stores a particular object type. For example, if we want to create an ArrayList of String object type, we may write:
ArrayList<String> strList=new ArrayList<>();
Similarly, for Employee object, we may write:
ArrayList<Employee> empList=new ArrayList<>();
We also may create an ArrayList without specifying a type, such as:
ArrayList <?> unknownList=new ArrayList<>();
This, however, is not always a good practice because we should let the compiler know the type of data element prior to adding it to the list. The ? denotes a wild card. Let us illustrate a case to get a clear idea about the uses of the generic ArrayList, including wildcards.
Suppose we want to implement a list of numbers and a generic sumTotal() method to get a total sum of the number of elements in the collection. By definition, generic classes can be used only with class or interface types. As a result, the numbers should be auto-boxed as objects of a wrapper class, such as an int value would be auto-boxed as Integer or a double value would be auto-boxed as a Double wrapper class. Our sumTotal() function should be able to calculate the total of the numbers in the ArrayList regardless of type variation. Therefore, we'll declare the ArrayList as ArrayList<Number>. The type argument Number is a super class of both wrapper classes Integer and Double. As a result, the reference variable can hold the reference of both the types. The following code should clarify the point further.
package org.mano.example; import java.util.ArrayList; public class Main { public static void main(String[] args) { Number[] nos = { 10, 20.683, 89, 0.74876 }; ArrayList<Number> nosList = new ArrayList<>(); for (Number no : nos) nosList.add(no); System.out.println(nosList); System.out.println("Sum = " + sumTotal(nosList)); } public static double sumTotal(ArrayList<Number> list) { double sum = 0; for (Number number : list) sum += number.doubleValue(); return sum; } }
So far, so good. The sumTotal() method takes a parameter as ArrayList<Number>; now, what if we want to send an ArrayList<Integer> or say ArrayList<Double> as an argument to the sumTotal() method call? We might expect that the method would work under this circumstance as well. After all, Number is a super class of Integer or Double, right? Unfortunately, it will not work! And, it would issue an error message at compile time. Try this modified code; it will not work.
public class Main { public static void main(String[] args) { Integer[] nos = { 10, 20, 89, 22 }; ArrayList<Integer> nosList = new ArrayList<>(); for (Integer no : nos) nosList.add(no); // ...same as above } public static double sumTotal(ArrayList<Number> list) { // ...same as above } }
The compiler does not consider the parameterized type ArrayList<Number> to be a super type of ArrayList<Integer>, because if ArrayList<Number> is considered a super type, we might add a Double object to an ArrayList<Number>. After all, Double is also a number as well. But, the point is we cannot add a Double object to an ArrayList<Integer> Because Double is not an Integer. This creates a erroneous super-subtype relationship.
Under these circumstances, can we create a sumTotal() method that is flexible enough to work with any subclass of Number? The answer is, we can, but by using wild card type arguments.
Let's modify the preceding example to suit our needs.
package org.mano.example; import java.util.ArrayList; public class Main { public static void main(String[] args) { Integer[] nos = { 10, 20, 89, 22 }; ArrayList<Integer> nosList = new ArrayList<>(); for (Integer no : nos) nosList.add(no); // ...same as above } public static double sumTotal(ArrayList<? extends Number> list) { // ...same as above } }
Conclusion
This article tried to put up some specific points in using the Java ArrayList class. In simple terms, ArrayList is an implementation of the concept of dynamic arrays. Normal arrays are of a static length; they cannot grow or shrink. That means we must specify their capacity prior to using them. Java ArrayList, in essence, is a variable-length array of object references that can dynamically increase or decrease its capacity. It is created with an initial size but, if this size is exceeds, the collection is automatically enlarged. Conversely, when objects are removed, the array is also shrunk.
|
http://mobile.developer.com/java/data/what-is-a-java-arraylist.html
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
1. Enjoying coding: Pressing letter keys, not arrow keysThere is often a need to introduce a new variable inside a foreach loop. For example, given:
foreach x $list { puts $x }in order to count the list's items during the loop I may do:
set c -1 foreach x $list { incr c puts "$c. $x" }While not so bad I still prefer not introducing new variables because
- Having to go backwards to set new variables doesn't feel very pleasant. Coding feels good when it flows forward, especially inside loops. By coding I mean typing the code.
- If there is a need for more than one variable, it begins to feel messy.
- It makes me feel like coding in C... from tcl I would expect something else.
res = [2*x for x in lis]but this is an algorithm:
res = [] for x in lis: res += [2*x]and it remains an algorithm even if it is written like this
set res {}; foreach x $lis {lappend res $x}This is better
proc mult2 x {expr $x*2} set res [struct::list map $res mult2]but not as good as this one
set res [struct::list map $res {apply {x {expr $x*2}}}LV Better in what sense? I look at this last item and have no idea what its purpose is, while if I look at the first tcl foreach example I have a clear idea of what it is doing... except that it isn't doing what the rest of the items is doing (there's nothing about multiplying anything by 2 in the foreach example...).iu2 Oops,I should have written the first example like this
set res2 {}; foreach x $res {lappend res2 [expr {2*$x}]}This form has three disadvantages:
- One has to read until the end of the line to get the idea of what this line is doing
- The list variable itself res cannot be reused, so res2 must be introduced
- I feel that stacking up two commands in one line is a less favorable coding pattern...
- On can tell what's happening in one glimpse at the beginning of the line - a list is formed out of another list. In order to understand exactly how it is formed - the 'apply' part is right there at the end.
- The list variable itself can be reused, as shown in the example.
- One command in the line
proc with {vars body} { foreach v $vars { foreach {name default} $v { break } uplevel 1 [list set $name $default] } uplevel 1 $body foreach v $vars { foreach {name default} $v { break } uplevel 1 [list unset -nocomplain $name] } }Your example above, using with:
with {{c -1} x} { foreach x $list { incr c puts "$c. $x" } }2. Introducing a counter inside a foreachWe start straight from eliminating set c -1
set list {a b c d e f g} foreach x $list c [struct::list iota [llength $list]] { puts "$c. $x" }With a little help from
proc counters list { for {set c 0} {$c < [llength $list]} {incr c} { lappend res $c } return $res }we can go
foreach x $list c [counters $list] { puts "$c. $x" }This is the Python way
proc enumerate list { set c 0 foreach x $list { lappend res $c $x incr c } return $res } foreach {c x} [enumerate $list] { puts "$c. $x" }but I prefer the previous one, which is more foreach-y.3. First iteration commandsThis code
foreach x $list first 1 { if {$first == 1} {set c 0} else {incr c} puts "$c. $x" }introduces the variable first, which is set to 1 in the first iteration and then becomes "" for all the rest. Since first is in foreach's arguments list, it doesn't realy seem like going back and setting a new variable.This code sums up a list
set numbers {1 2 3 4 5 6 7 8 9 10} foreach x $numbers first 1 { if {$first == 1} {set sum $x} else {incr sum $x} } puts $sumResult:
55and this one finds the maximum
set numbers2 {-2 -4 -1 -3 0 10 3} foreach x $numbers2 first 1 { if {$first == 1 || $x > $max} {set max $x} } puts $maxResult:
104. Little functions giving a Common Lisp flavourInstead of first, let's call that variable enablecl, standing for Enable Common Lisp.
proc incrementing {var} { uplevel 1 [list if {$enablecl == 1} [list set $var 0] else [list incr $var]] } # test foreach x $list enablecl 1 { incrementing c1 puts "$c1. $x" }Let's add more functions like that
proc summing {exp into var} { uplevel 1 [list if {$enablecl == 1} [list set $var $exp] else [list incr $var $exp]] } proc counting {cond into var} { uplevel 1 [list if {$enablecl == 1} [list set $var 0]] uplevel 1 [list if $cond [list incr $var]] }and give them a try
set numbers {1 2 3 4 5 6 7 8 9 10 11} # test foreach x $numbers enablecl 1 { summing $x into sum1 summing [expr 2*$x] into sum2 counting 1 into count counting {int($x)/2*2 == $x} into even counting "int($x)/2*2 != $x" into odd } puts "$sum1, $sum2, $count steps, $even evens, $odd odds"Result:
66, 132, 11 steps, 5 evens, 6 oddsNice.Maximum and minimum took me a while to figure out...
proc maximizing {exp into var} { uplevel 1 [list if {$enablecl == 1} [list set $var $exp]] uplevel [list if [concat $exp > $$var] [list set $var $exp]] } proc minimizing {exp into var} { uplevel 1 [list if {$enablecl == 1} [list set $var $exp]] uplevel [list if [concat $exp < $$var] [list set $var $exp]] } set numbers2 {-2 -4 -1 -3 0 10 3} # test foreach x $numbers2 enablecl 1 { maximizing $x into max minimizing $x into min puts $x,$max,$min } puts $max,$minWe advance towards list comprehension by introducing appending
proc appending {exp into var} { uplevel 1 [list if {$enablecl == 1} [list set $var [list $exp]] else [list lappend $var $exp]] } # test foreach x $numbers enablecl 1 { appending $x into nums appending "Number $x" into strings if {$x > 5} {appending [expr 2*$x] into twice} ;# a list comprehension... if {[set res [expr $x+1]] > 5} {appending $res into plus1} ;# and an improvement } puts [join $nums ,] puts [join $strings \n] puts [join $twice ", "] puts [join $plus1 ", "]Adding a bit more syntax to appending makes it more interesting
proc appending {exp into var {if if} {cond 1}} { uplevel 1 [list if {$enablecl == 1} [list set $var {}]] set res [uplevel 1 [list subst $exp]] uplevel 1 [regsub -all -- {%\yr\y} [list if $cond [list lappend $var $res]] $res] } # test foreach x {1 2 3 4} y {5 6 7 8} enablecl 1 { appending [expr $x+$y] into sums2 if {%r > 8} } puts [join $sums2]More stuff
proc toggling {into var} { uplevel 1 [list if {$enablecl == 1} [list set $var 0]] uplevel 1 [list if {$enablecl != 1} [list set $var [uplevel 1 [list expr 1-$$var]]]] } # test foreach x {1 2 3 4} enablecl 1 { toggling into togl puts "$x - $togl" }This is a general form of updating a variable each iteration
proc updating {init exp into var} { uplevel 1 [list if {$enablecl == 1} [list set $var $init]] uplevel 1 [list set $var [uplevel 1 $exp]] } # test foreach x {1 2 3 4 5} enablecl 1 { updating 0 {expr $count+1} into count updating 0 {expr $sum2+$x} into sum2 updating 1 {expr $mult*$x} into mult updating {} {lappend mult2 [expr 2*$x]} into mult2 } # print result foreach x {count sum2 mult mult2} {puts "$x: [set $x]"}Result:
count: 5 sum2: 15 mult: 120 mult2: 2 4 6 8 10
# another test foreach x {1 2 3 4 5 6 7 8 9 10 11 12} enablecl 1 { updating -1 {expr ($cyc+1)%3} into cyc puts "x: $x, cyc: $cyc" }The last test leads to another idea
proc cycling {exp into var} { uplevel 1 [list if {$enablecl == 1} [list set $var -1]] uplevel 1 [list set $var [uplevel 1 [list expr ($$var+1)%$exp]]] } # test foreach x {1 2 3 4 5 6 7 8 9 10 11 12} enablecl 1 { cycling 3 into cyc puts "x: $x, cyc: $cyc" }I often write lists as rows, each row having col_count items, so
foreach number $list enablecl 1 { puts -nonewline "$number " cycling $col_count into cyc if {$cyc == $col_count-1} {puts ""} }because of that last example, I just can't resist extending cycling a little bit...
proc cycling {exp into var args} { uplevel 1 [list if {$enablecl == 1} [list set $var -1]] uplevel 1 [list set $var [uplevel 1 [list expr ($$var+1)%$exp]]] set condcount 0 foreach {on list what} $args { # if {[uplevel 1 [list set $var]] in $list} tcl 8.5 if {[lsearch $list [uplevel 1 [list set $var]]] > -1} {uplevel 1 $what; incr condcount} else { if {$on eq "else" && $condcount == 0} {uplevel 1 $list} } } } # test foreach x {1 2 3 4 5 6 7 8 9 10 11 12} enablecl 1 { puts -nonewline "$x " cycling 3 into cyc on 2 {puts ""} } # or even this foreach x {1 2 3 4 5 6 7 8 9 10 11 12} enablecl 1 { puts -nonewline "$x" cycling 3 into cyc on 2 {puts ""} else {puts -nonewline " "} } # another test foreach x {1 2 3 4 5 6 7 8 9 10 11 12} enablecl 1 { cycling 4 into cyc on 0 {puts "start: cyc=$cyc"} on 3 {puts "last: cyc=$cyc"} on {1 2} {puts "middle: cyc=$cyc"} puts $cyc }5. Helper functions with a helper variableThe following example uses another variable besides var
proc cyclelist {hlpvar list into var} { uplevel 1 [list if {$enablecl == 1} [list set $hlpvar -1]] set len [llength $list] set index [uplevel 1 [list set $hlpvar]] set index [expr ($index+1)%$len] uplevel 1 [list set $hlpvar $index] uplevel 1 [list set $var [lindex $list $index]] } # test foreach x {1 2 3 4 5 6 7 8 9 10 11 12 13 14} enablecl 1 { cyclelist cyc1 {one two three four} into cyc2 puts "$x $cyc2 ($cyc1)" }6. Summary
- With these little helpers foreach-ing can be more readable, more fun and more press letter keys, not arrow keys ;-)
- I'm sure more functions of this type can be introduced
- There still may be bugs in them, so bug fixes are welcome
- I'm not sure the uplevel 1 [list if... way I use is the best. Shorter or more readable formats will be appreciated.
LES on same day:
set res [struct::list map $res {apply {x {expr $x*2}}}You call that "readable"?
iu2 well, yes, beacuse I recognize a structure: map-list-apply.
RS Due to the path structure, the first part is a bit cluttered. If you seriously use map, it might help to
interp alias {} map {} struct::list mapand then code (remember to brace your expr-essions :^)
set res [map $res {apply {x {expr {$x*2}}}}]NEM: And adding a constructor for lambdas helps a lot:
proc func {params body} { list ::apply [list $params [list expr $body] ::] } map $res [func x {$x*2}]Unfortunately, the tcllib versions of map, filter and fold take arguments in an inconvenient order for interp alias, so e.g. we have to do:
proc ldouble xs { map $xs [func x {$x*2}] }rather than simply:
def ldouble = map [func x {$x*2}]aspect -- frankly, I find the use of [list map] and apply awkward in the above example. Using lmap it simplifies (without the need for lambda) to:
set res [lmap i $res {expr {$i*2}}].. or, using the version (which I prefer for succinctness, even if it is a little less flexible) from list map and list grep you get:
set res [lmap $res {expr {$_*2}}]NEM I'm not sure which uses you find awkward? The func constructor I provide is a simple single-line proc, and the resultant map is just as tiny as lmap:
proc map {f xs} { set ys [list] foreach x $xs { lappend ys [{*}$f $x] } return $ys } map [func i {$i*2}] $resIt can also be used directly with existing commands. For instance, if we want to convert all words in a list to upper-case, we can simply do:
map {string toupper} {this is a list of words}This is just one of the benefits of properly factoring out the construction of a callback from the control construct that uses it. Others are that we can use multiple different constructors in different situations: e.g. a plain lambda, a version that uses expr, a version that captures a closure, etc. Not to mention the benefits of byte-compilation that come from having the lambda as a single argument.
FM : sometimes I like to use this proc
proc except cond { uplevel [list if $cond {return -code continue}] } set L [list 0 1 2 3 4 5 6 7 8 9] foreach e $L { except {$e%2==1 || $e==0} lappend Res $e } set Res ; # 2 4 6 8
|
http://wiki.tcl.tk/17444
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
This C Program computes the sum of two one-dimensional arrays using malloc. The program allocates 2 one-dimentional arrays using malloc() call and then does the addition and stores the result into 3rd array. The 3rd array is also defined using malloc() call.
Here is source code of the C program to compute the sum of two one-dimensional arrays using malloc. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to find the sum of two one-dimensional arrays using
* Dynamic Memory Allocation
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main()
{
int i, n;
int *a, *b, *c;
printf("How many Elements in each array...\n");
scanf("%d", &n);
a = (int *)malloc(n * sizeof(int));
b = (int *)malloc(n * sizeof(int));
c = (int *)malloc(n * sizeof(int));
printf("Enter Elements of First List\n");
for (i = 0; i < n; i++)
{
scanf("%d", a + i);
}
printf("Enter Elements of Second List\n");
for (i = 0; i < n; i++)
{
scanf("%d", b + i);
}
for (i = 0; i < n; i++)
{
*(c + i) = *(a + i) + *(b + i);
}
printf("Resultant List is\n");
for (i = 0; i < n; i++)
{
printf("%d\n", *(c + i));
}
}
$ cc pgm90.c $ a.out How many Elements in each array... 5 Enter Elements of First List 23 45 67 12 90 Enter Elements of Second List 87 56 90 45 10 Resultant List is 110 101 157 57 100.
|
http://www.sanfoundry.com/c-program-compute-sum-two-one-dimensional-arrays-using-malloc/
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
wicd-curses crashes for an IndexError exception
Bug Description
Distribution: Arch
Package version: 1.7.3
I get this stack trace using wicd-curses in an environment with multiple wifi connection available:
ERROR:dbus.
Traceback (most recent call last):
File "/usr/lib/
self.
File "/usr/share/
return func(*args, **kargs)
File "/usr/share/
self.
File "/usr/share/
wired.
File "/usr/share/
return self.theList[loc]
IndexError: list index out of range
This error is triggered at exit (i.e. when I press 'q'):
1) when I first run wicd-curses right after boot
2) If a when I first disable wifi (hardware switch), then I reenable it again and rerun wicd-curses
It seems the profiles list is not update correctly in some case, or there is some inconsistency with get_focus().
I hit this bug every time i use wicd-curses, regardless of connection state.
This seems like a trivial fix, can we get someone to merge this patch or look into the issue?
Hello! My name is Alex and I'm maintainer few packages on AUR.
Since I've been looked for minimalistic way to management connection to wifi points, I am looked in direction of wicd.
Seems easy to use for me but because few bugs in curses inteface, I'd to collect few patches from different sources that solve them and put into a single package.
I'll apprechiate if you'll test it out https:/
Also, thanks for the great tool, seems helpful to me.
And patches that developers made to fix users issues!!
Have a lucky day.
@alextalker
Working perfectly for me. Thanks for your work.
I can finally use wicd-curses again, instead of wicd-gtk. Yay!
@alextalker: I default to 0 instead of -1 as proposed in the patch posted at https:/
Reason is that your patch defaults to "Add new profile" which is confusing. Choosing the first item instead of the last one makes more sense to me.
I can't really test this any time soon but for me it only seemed to be a selection highlighted. Perhaps the bug is different to what I first thought. If 0 works for you then what does it affect later in the code?
Hi,
I was able to fix this on my machine by simply including a try/except handler in the get_selected_
<code>
def get_selected_
"""Get the selected wired profile"""
try:
loc = self.get_focus()[1]
return self.theList[loc]
except:
return ""
</code>
- Armin
Oh, forgot to add this: Line 535 in wicd-curses.py that was, on my machine.
- Armin
This patch fixes the index out of bounds error by returning the last item in the list when variable loc is not a valid index.
|
https://bugs.launchpad.net/wicd/+bug/1421918
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
In my recent post about safely applying monkey patches in Python, I mentioned how one of the issues that arises is when a monkey patch is applied. Specifically, if the module you need to monkey patch has already been imported and was being used by other code, that it could have created a local reference to a target function you wish to wrap, in its own namespace. So although your monkey patch would work fine where the original function was used direct from the module, you would not cover where it was used via a local reference.
Coincidentally, Ned Batchelder recently posted about using monkey patching to debug an issue where temporary directories were not being cleaned up properly. Ned described this exact issue in relation to wanting to monkey patch the 'mkdtemp()' function from the 'tempfile' module. In that case he was able to find an alternate place within the private implementation for the module to patch so as to avoid the problem. Using some internal function like this may not always be possible however.
What I want to start discussing with this post is mechanisms one can use from wrapt to deal with this issue of ordering. A major part of the solution is what are called post import hooks. This is a mechanism which was described in PEP 369 and although it never made it into the Python core, it is still possible to graft this ability into Python using existing APIs. From this we can then add additional capabilities for discovering monkey patching code and automatically apply it when modules are imported, before other modules get the module and so before they can create a reference to a function in their own namespace.
Post import hook mechanism
In PEP 369, a primary use case presented was illustrated by the example:
import imp
@imp.when_imported('decimal')
def register(decimal):
Inexact.register(decimal.Decimal)
The basic idea is that when this code was seen it would cause a callback to be registered within the Python import system such that when the 'decimal' module was imported, that the 'register()' function which the decorator had been applied to, would be called. The argument to the 'register()' function would be the reference to the module the registration had been against. The function could then perform some action against the module before it was returned to whatever code originally requested the import.
Instead of using the decorator '@imp.when_imported' decorator, one could also explicitly use the 'imp.register_post_import_hook()' function to register a post import hook.
import imp
def register(decimal):
Inexact.register(decimal.Decimal)
imp.register_post_import_hook(register, 'decimal')
Although PEP 369 was never incorporated into Python, the wrapt module provides implementations for both the decorator and the function, but within the 'wrapt' module rather than 'imp'.
Now what neither the decorator or the function really solved alone was the ordering issue. That is, you still had the problem that these could be triggered after the target module had already been imported. In this case the post import hook function would still be called, albeit for our case too late to get in before the reference to the function we want to monkey patch had been created in a different namespace.
The simplest solution to this problem is to modify the main Python script for your application and setup all the post import hook registrations you need as the absolute very first thing that is done. That is, before any other modules are imported from your application or even modules from the standard library used to parse any command line arguments.
Even if you are able to do this, because though the registration functions require an actual callable, it does mean you are preloading the code to perform all the monkey patches. This could be a problem if they in turn had to import further modules as the state of your application may not yet have been setup such that those imports would succeed.
They say though that one level of indirection can solve all problems and this is an example of where that principle can be applied. That is, rather than import the monkey patching code, you can setup a registration which would only lazily load the monkey patching code itself if the module to be patched was imported, and then execute it.
import sysfrom wrapt import register_post_import_hookdef load_and_execute(name):
def _load_and_execute(target_module):
__import__(name)
patch_module = sys.modules[name]
getattr(patch_module, 'apply_patch')(target_module)
return _load_and_executeregister_post_import_hook(load_and_execute('patch_tempfile'), 'tempfile')
In the module file 'patch_tempfile.py' we would now have:
from wrapt import wrap_function_wrapperdef _mkdtemp_wrapper(wrapped, instance, args, kwargs):
print 'calling', wrapped.__name__
return wrapped(*args, **kwargs)def apply_patch(module):
print 'patching', module.__name__
wrap_function_wrapper(module, 'mkdtemp', _mkdtemp_wrapper)
Running the first script with the interactive interpreter so as to leave us in the interpreter, we can then show what happens when we import the 'tempfile' module and execute the 'mkdtemp()' function.
$ python -i lazyloader.py
>>> import tempfile
patching tempfile
>>> tempfile.mkdtemp()
calling mkdtemp
'/var/folders/0p/4vcv19pj5d72m_bx0h40sw340000gp/T/tmpfB8r20'
In other words, unlike how most monkey patching is done, we aren't forcibly importing a module in order to apply the monkey patches on the basis it might be used. Instead the monkey patching code stays dormant and unused until the target module is later imported. If the target module is never imported, the monkey patch code for that module is itself not even imported.
Discovery of post import hooks
Post import hooks as described provide a slightly better way of setting up monkey patches so they are applied. This is because they are only activated if the target module containing the function to be patched is even imported. This avoids unnecessarily importing modules you may not even use, and which otherwise would increase memory usage of your application.
Ordering is still important and as a result it is important to ensure that any post import hook registrations are setup before any other modules are imported. You also need to modify your application code every time you want to change what monkey patches are applied. This latter point could be inconvenient if only wanting to add monkey patches infrequently for the purposes of debugging issues.
A solution to the latter issue is to separate out monkey patches into separately installed modules and use a registration mechanism to announce their availability. Python applications could then have common boiler plate code executed at the very start which discovers based on supplied configuration what monkey patches should be applied. The registration mechanism would then allow the monkey patch modules to be discovered at runtime.
One particular registration mechanism which can be used here is 'setuptools' entry points. Using this we can package up monkey patches so they could be separately installed ready for use. The structure of such a package would be:
setup.py
src/__init__.py
src/tempfile_debugging.py
The 'setup.py' file for this package will be:
from setuptools import setupNAME = 'wrapt_patches.tempfile_debugging'def patch_module(module, function=None):
function = function or 'patch_%s' % module.replace('.', '_')
return '%s = %s:%s' % (module, NAME, function)ENTRY_POINTS = [
patch_module('tempfile'),
]setup_kwargs = dict(
name = NAME,
version = '0.1',
packages = ['wrapt_patches'],
package_dir = {'wrapt_patches': 'src'},
entry_points = { NAME: ENTRY_POINTS },
)setup(**setup_kwargs)
As a convention so that our monkey patch modules are easily identifiable we use a namespace package. The parent package in this case will be 'wrapt_patches' since we are working with wrapt specifically.
The name for this specific package will be 'wrapt_patches.tempfile_debugging' as the theoretical intent is that we are going to create some monkey patches to help us debug use of the 'tempfile' module, along the lines of what Ned described in his blog post.
The key part of the 'setup.py' file is the definition of the 'entry_points'. This will be set to a dictionary mapping the package name to a list of definitions listing what Python modules this package contains monkey patches for.
The 'src/__init__.py' file will then contain:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
as is required when creating a namespace package.
Finally, the monkey patches will actually be contained in 'src/tempfile_debugging.py' and for now is much like what we had before.
from wrapt import wrap_function_wrapperdef _mkdtemp_wrapper(wrapped, instance, args, kwargs):
print 'calling', wrapped.__name__
return wrapped(*args, **kwargs)def patch_tempfile(module):
print 'patching', module.__name__
wrap_function_wrapper(module, 'mkdtemp', _mkdtemp_wrapper)
With the package defined we would install it into the Python installation or virtual environment being used.
In place now of the explicit registrations which we previously added at the very start of the Python application main script file, we would instead add:
import osfrom wrapt import discover_post_import_hookspatches = os.environ.get('WRAPT_PATCHES')if patches:
for name in patches.split(','):
name = name.strip()
if name:
print 'discover', name
discover_post_import_hooks(name)
If we were to run the application with no specific configuration to enable the monkey patches then nothing would happen. If however they were enabled, then they would be automatically discovered and applied as necessary.
$ WRAPT_PATCHES=wrapt_patches.tempfile_debugging python -i entrypoints.py
discover wrapt_patches.tempfile_debugging
>>> import tempfile
patching tempfile
What would be ideal is if PEP 369 ever did make it into the core of Python that a similar bootstrapping mechanism be incorporated into Python itself so that it was possible to force registration of monkey patches very early during interpreter initialisation. Having this in place we would have a guaranteed way of addressing the ordering issue when doing monkey patching.
As that doesn't exist right now, what we did in this case was modify our Python application to add the bootstrap code ourselves. This is fine where you control the Python application you want to be able to potentially apply monkey patches to, but what if you wanted to monkey patch a third party application and you didn't want to have to modify its code. What are the options in that case?
As it turns out there are some tricks that can be used in that case. I will discuss such options for monkey patching a Python application you can't actually modify in my next blog post on this topic of monkey patching.
|
http://blog.dscpl.com.au/2015/03/ordering-issues-when-monkey-patching-in.html
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
XForms uses XPath to address instance data nodes in binding expressions, to express constraints, and to specify calculations.]. Elements and attributes in the instance data may
have namespace information associated with them, as defined in the XPath Data
Model. Unless otherwise specified, all instance data elements and attributes
are unqualified. In addition, XForms processors must provide
DOM access to this instance data via the interface defined below.
interface XFormsModelElement : org.w3c.dom.Element
The method getInstanceDocument returns a DOM Document that corresponds to the instance data associated with this XForms Model.
Return value: org.w3c.dom.Document
raises (DOMException); if there is no model with the specified model-id. binding expressions in XForms:
The context node for outermost form
control elements is the XPath root (
/). A " form control element" is any
element other than
bind that is explicitly
allowed to have a binding expression attribute. A form control element is
"outermost" when the node-set returned by the XPath
expression
ancestor::* includes no form control element nodes.
The context node for non-outermost form
control elements is the first node of the
binding expression of the immediately enclosing element. An element is
"immediately enclosing" when it is the first form
control element node in the node-set returned by the XPath expression
ancestor::*. This is also referred to as "scoped resolution".
The context node for the
ref attribute on
bind is the XPath root. The context node for other attributes of
bind is the first node of the node-set returned from the binding
expression in the sibling
ref attribute.
The context size and position are both exactly 1.
No variable bindings are in place.
The available function library is defined below.
Any namespace declarations in scope for the attribute that defines the expression are applied to the expression.
<group ref="level1/level2/level3"> <selectOne ref="elem" ... /> <selectOne ref="@attr" ... /> </group>
In this example, the
group has a binding expression of
level1/level2/level3. According to the rules above, this outermost element would have a
context node of
/, which is the root of the instance data, or the parent to the
elem element. Both of the
selectOnes then inherit a context node from their parent, the context node being
/level1/level2/level3. Based on this, the
selectOne binding expressions evaluate respectively to
/level1/level2/level3/elem and
/level1/level2/level3/@attr. Matching instance data follows:
<level1> <level2> <level3 attr="xyz"> <elem>xyz</elem> </level3> </level2> </level1>
The XForms Core Function Library includes the entire [XPath 1.0] Core Function Library, including operations on node-sets, strings, numbers, and booleans.
This section defines a set of required functions for use within XForms.
boolean boolean-from-string(string)
Function
boolean-from-string returns
true if the required parameter
string is "true", or
false if parameter
string is "false". This is useful when referencing a Schema
xsd:boolean datatype in an XPath expression. If the parameter
string matches neither "true" nor "false", according to a case-insensitive
comparison, processing stops with a fatal error.
Note:
The XPath number datatype and associated methods and operators use IEEE specified representations. XForms Basic Processors are not required to use IEEE, and thus might yield slightly different results. cursor( string )
Function
cursor takes a string
argument that is the
idref of a
repeat and returns the current position of the repeat
cursor for the identified
repeat—see 10.3 Repeating Structures
for details on
repeat and its associated repeat cursor. If the
specified argument does not identify a
repeat, this function throws an
error.
<xforms:button> <xforms:caption>Add to Shopping Cart</xforms:caption> <xforms:insert ev: </xforms:button>
property()>
|
http://www.w3.org/TR/2001/WD-xforms-20011207/slice7.html
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
in reply to Re: parsing XML fragments (xml log files) with XML::Parserin thread parsing XML fragments (xml log files) with XML::Parser.
It parses numerical entities. Decoding them wasn't required and would only require one regex be added. It handles namespace prefixes exactly as I wanted it to (they're included in the tag name). It is trivial to make it handle them differently (which is the point). I won't go into "validation" here, it being a subject worthy of a lengthy write-up.
A pre/post processor could fix this...
Wow. You are really stuck in thinking in terms of an XML-parsing module. There is no need to do anything in a pre-/post-processor -- which is part of the whole point of the exercise.
For example, supporting comments is 2 minutes' work and easily fits into the existing structure. The few items that rise to the level of being interesting to implement are the things that I've never actually seen used in any XML. So it shouldn't be surprising that I didn't bother to implement them in the code that implemented just what I needed for one project.?
my $data= '(?: [^<>&]+ | &\#?\w+; )+';
[download]
my $data= '(?: [^<&]+ | &\#?\w+; )+';
[download]
XML allows for unescaped ">".
|
http://www.perlmonks.org/?node_id=893908
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
iMovieRecorder Struct ReferenceUsing this interface you can communicate with the MovieRecorder plugin. More...
#include <ivaria/movierecorder.h>
Inheritance diagram for iMovieRecorder:
Detailed DescriptionUsing this interface you can communicate with the MovieRecorder plugin.
This allows changing or disabling the hotkey bindings, changing the video parameters, and programmatically starting and stopping the recorder.
- Remarks:
- The plugin is GPL, not LGPL.
Definition at line 41 of file movierecorder.h.
Member Function Documentation
Is the recording paused?
Are we recording?
Pause an in-progress recording.
Start recording using the settings in the configuration system.
Stop recording if a recording is in progress.
Resume an in-progress recording.
The documentation for this struct was generated from the following file:
- ivaria/movierecorder.h
Generated for Crystal Space 1.0.2 by doxygen 1.4.7
|
http://www.crystalspace3d.org/docs/online/api-1.0/structiMovieRecorder.html
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
Contemporary Perl's release schedule is approximately one major release per year. The 5.14 release came out on May 14, 2011, so it is not too soon to be thinking about 5.16. That release is indeed stabilizing with a number of new features. A key aspect of this release is a familiar story: as with most other languages, Perl developers are trying to improve their support for Unicode in all situations. Many developers have participated in this work, but Tom Christiansen has arguably been the most visible. His recent work includes the preparation of an extensive Perl Unicode cookbook demonstrating Perl's Unicode-related features which, he has suggested, are now second to none.
As this cookbook was being discussed, Karl Williamson pointed out that some of the examples where Perl is put into full-time UTF8 mode (a very useful mode for contemporary programs) are unsafe because the language does not properly handle malformed strings. At best, such problems could lead to the corrupted strings seen in so many settings where character encodings are not properly handled. But, as Christian Hansen suggested, things can be worse than that:
What followed was a classic missive from Tom trying to get to the bottom of the problem. He listed nine different ways to tell Perl to operate with UTF8 and asked how many of them were truly vulnerable to undetected encoding problems. If Perl's UTF8 handling is unsafe by default, he said, it needs to be fixed:
And, he said, this situation really needs to be treated as a blocker for the 5.16 release; to do otherwise would be to delay the fix excessively and cause the world to be filled with bad workaround code.
In many projects, the prospect of open security-related problems would at least cause people to think about delaying a release. On the Perl list, though, Tom found little support. Aristotle Pagaltzis responded:
And, with those words, the public email discussion faded away. At this point, there is little clarity on which Unicode features are safe to use, what might be required to fix the rest, how many of those fixes might be ready in time for the 5.16 release, or whether programs using UTF8 in Perl 5.16 (and earlier releases) suffer from known-exploitable security problems. Tom, who probably understands these issues better than just about anybody else, said:
The response he got claimed another train would be coming along in a year and the fixes could catch a ride on that one.
Releasing software with known bugs is a common practice; even a project like Debian cannot make the claim that there are no known problems with its releases. To do otherwise would make software releases into rare events indeed. It is also true that time-based releases have value; users know that they will get useful new code in a bounded period of time. Anybody who has watched release dates slip indefinitely knows how frustrating that can be for both users and developers; the 2.4.0 or 2.6.0 kernel releases are a classic example - as is Perl 5.10. So the Perl developers who say that the show must go on are doing so in accordance with many years of free software development experience.
That said, releasing software with known, security-related issues in something as fundamental as UTF8 support risks tarnishing the image of the project for a long time. There is not enough information publicly available to say whether Perl's UTF8 problems are severe enough to incur this risk. But it is probably safe to assume that, as a result of this conversation, crackers are looking at Perl's UTF8 handling rather more closely than they were before. Perl may have had some of these problems for years without massive ill effect, but they may not remain undiscovered and undisclosed for much longer. If the problem is real and exploitable, people are going to figure it out and take advantage of it.
One would assume that, behind the public positioning, the relevant developers understand what's at stake and are taking the time to understand the scope of the problem. They may not want to stop the release train, but seeing it derailed by a known security problem after release would not be much fun either. A release delay now may prove less painful than a security-update fire drill later.
Mozilla announced
a deal with
Latin American mobile carrier Telefónica Digital on February 27
to start shipping HTML5-driven smartphones by the end of 2012. Although
the press release dubs the new platform "Open Web Device," many Mozilla
watchers know it better as Boot To
Gecko (B2G), a lightweight Linux-based system that uses Gecko as its
primary (if not sole) application framework. B2G has been in development
since July 2011, but it has advanced significantly since we last examined it in mid-August.
Initially, the project debated several options for the underlying operating system on which to perch the Gecko runtime — including Android (which served as the basis for the earliest experimental builds), MeeGo, and webOS. The team has since settled on an architecture of its own, which takes some components from Android, but constructs its own stack, called Gonk.
Gonk is a stripped-down Linux distribution, using the kernel and some standard userspace libraries for hardware access (e.g., libusb and Bluez). It also borrows hardware abstraction layer code from Android — the architecture document on the Mozilla wiki lists camera and GPS devices in particular. The architecture document also makes references to both the Android kernel and to modified kernels supplied by hardware vendors; evidently B2G is designed to tolerate minor variations.
Gonk also includes an Android-derived init program, D-Bus, wpa_supplicant, and Network Manager. The media playback functionality also comes from Android: there is a mediaserver player for the audio and video formats that Gecko can decode natively, and libstagefright to access binary-only codecs and hardware decoding chips.
Mozilla's B2G team could not be reached for comment, but several of the Android components in the Gonk stack appear to have been chosen for the practical task of bootstrapping the OS on available smartphone hardware (such as the Samsung Galaxy S II, which is the testbed device at Mozilla) rather than on technical grounds. For instance, the setup currently uses Android's Bionic library, but there has been some discussion of replacing it with a more general libc implementation.
Apart from those components and the cellular modem layer, however, Gecko is the only runtime process started. In B2G, there is a master "Gecko server" process named b2g that spawns lower-privileged child processes for each web application run. Only the b2g process can directly access hardware devices; it mediates access requested by the child processes. b2g and the application processes can pass messages to each other using what Mozilla calls "IPC (Interprocess communication) Protocol Definition Language" or IPDL, which originates from the Electrolysis project. Electrolysis is Mozilla's effort to refactor Firefox as a multi-process application; it is still in development, but it provides both synchronous and asynchronous communication, and isolates child processes from each other.
Ultimately, Gonk is different enough from both Android and typical desktop Linux systems to warrant its own build target for Gecko. Among other distinctions, it implements a lightweight input event system, and draws directly to OpenGL ES rather than the X Window system. But in order to provide the full smartphone application framework, the Gecko engine must also have direct access to low-level functionality that is normally handled by other processes — such as the telephony stack.
B2G's telephony stack is called the Radio Interface Layer (RIL), and is derived from the corresponding code in Android. RIL caters to device vendors by providing a rilproxy mechanism to manage connections between the b2g process and the cellular modem driver. The driver, called rild, can be proprietary (in fact, the RIL design assumes it is proprietary) and thus link to binary-only firmware blobs without triggering the license inheritance conditions from other parts of the stack.
RIL implements voice and 3G data calls, network status, text and MMS messaging, and SIM card commands (such as storing and retrieving contacts, or entering and validating unlock codes). These commands are exposed to HTML5 applications through the WebTelephony and WebSMS JavaScript APIs, which are still in development.
In fact, much of the B2G-specific functionality requires the definition of new APIs that "traditional" Gecko applications do not expect. Mozilla has already invested in the drafting of OS-independent web APIs for other reasons, including its Web App Store project. Mozilla is also participating in the standardization effort being managed by the W3C, primarily the Device APIs Working Group. At the moment, not every API created by Mozilla has a corresponding W3C specification, although Mozilla says standardizing all of them is the ultimate goal. Mozilla's list includes a mixture of high-level interfaces (such as the Contacts or Camera APIs) and low-level interfaces (such as the Bluetooth and near field communication (NFC) stack APIs).
The most far-reaching APIs in the library are Open Web Apps, which specifies a manifest file format and packaging guidelines for "installable" web applications, and WebRTC, which provides a real-time communication framework used for streaming media as well as network-centric features like peer-to-peer networking. Some of the less familiar specifications under development are APIs for detecting screen orientation, processing notifications when the device is idle, and locking hardware resources (such as preventing screen-dimming).
The plan is for every application in a B2G device to be written in HTML5, CSS, and JavaScript, and naturally the list begins with the generic phone applications: a "home" screen, phone dialer, camera, contact list, calendar, and so on. While phone vendors may prefer to write their own code in-house, Mozilla is at least in the planning and mock-up stage of creating some demo B2G applications.
The demo application suite is code-named Gaia. The wiki page has placeholders for a dozen or so basic applications, including more detailed mock-ups for the web browser, image gallery, and camera application. There are also mock-up images on the Demo page for a home screen, lock screen, and dialer.
More interesting than static mock-ups are the in-development demos found at B2G developer Andreas Gal's GitHub site (screen shots of some are shown here). A recent version of Firefox will open the HTML files from the repository; the homescreen.html file shows the home screen and lock screen, and several other applications are accessible through home screen launchers (the Mozilla wiki's Demo page also links to a "live" demo, but that appears to be out-of-order at the moment). The UI responds to mouse clicks and "slide" gestures, although the applications vary widely in completion, of course — some are just static images. Still, the home screen and generic applications are in place along with basic navigation and UI elements.
The B2G roadmap is ambitious; it predicts a product-ready milestone by the end of the second quarter of 2012. Considering that not all of the fourth quarter 2011 goals have been met yet, that may not be attainable without an infusion of developer time from a hardware partner, but the project did bring a B2G demonstration to Mobile World Congress alongside the February 27 announcement.
Perhaps notably, the Bluetooth, NFC, and USB tracking bugs appear to be behind schedule at the moment, while most of the higher-level work for sensor support and user applications appear to be on track. Arguably the biggest piece of the puzzle yet to get underway is WebRTC support. WebRTC itself is still undergoing rapid development, of course, but without it, the goal of supporting real-time audio and video on a web-runtime smartphone is difficult to imagine.
Resources for potential Open Web Device application developers are also in short supply at the moment. Although Mozilla curates a collection of HTML5 resources at its Mozilla Developer Network (MDN) site, so far only the Open WebApps APIs are covered. Mozilla formally opened its Open Web App "Marketplace" on February 28, in an announcement that referenced the in-progress Web API effort in addition to the traditional desktop platform. That is probably a sign that the Web APIs will make their way to MDN in short order as well.
In its own press release, Telefónica Digital says only that its first Open Web Device-powered phone (which has not been detailed in hardware specification or price) will ship in 2012. That leaves considerable time to complete the project on schedule, although from Mozilla's perspective getting the new JavaScript APIs through the not-known-for-its-rapidity W3C standardization process may be a tight fit.
One of the "advantages" of running a Rawhide system is that one gets to try out the new toys ahead of the crowd. Said toys also have a certain tendency to arrive at random and inopportune times. In the case of the /usr move, most Rawhide users got little or no warning before updates simply failed to work. The Rawhide repository, it seems, had suddenly been populated with packages requiring a system where the /usr move had already been done. Actually causing this move to happen was left as an exercise for the system administrator.
As it happens, this is one of the more controversial aspects of the /usr move in the Fedora community. Fedora policy has always said that using the yum tool to update an installation to a newer release of the distribution is not supported; one is supposed to use a CD or the preupgrade tool for that purpose. But, in reality, just using yum tends to work; the prospect of it not working to get to Fedora 17 has caused some grumpiness in the Fedora user community. If this limitation remains in the Fedora 17 release, expect to hear some complaints; users don't like to have their ponies taken away, even if nobody had ever said they could have a pony in the first place.
For Rawhide users, it is possible to move past the usrmove flag day by following this set of instructions. The process involves editing the grub configuration files, installing a special initramfs image, then rebooting with a special option that causes the actual thrashing of the system to be done from the initramfs before the real root is mounted. Your editor, setting out along this path with a well backed-up system, was reminded of doing the manual transition from the a.out to the ELF executable format on a Slackware system many years ago. In both cases, one had the sense of toying with fundamental forces with no guarantee of a non-catastrophic outcome.
In both cases, as it happens, things worked out just fine. Directories like /bin, /lib, /lib64, and /sbin are now symbolic links into /usr, and the system works just like it always did. No programs or scripts needed to be changed, custom kernels work as they always did, and so on. That will almost certainly be most users' experience of this transition - they will not even notice that it has happened. This is not a particularly surprising result; the practice of moving files and leaving a symbolic link in their place has a long history. Of course, somebody has probably patented it anyway.
Of course, an equally successful result for all systems depends on the Fedora developers creating a bombproof automatic mechanism for carrying out this transition prior to the Fedora 17 release. Hopefully something will have been learned from the GRUB 2 mess, where the Fedora 16 upgrade left a lot of bricked systems in its wake. If Fedora 17 creates similar messes on systems that, perhaps, are not set up quite as the Fedora developers expect, a lot of unhappiness will ensue.
As an aside, it is interesting to compare how Fedora is managing this transition with Debian's multiarch transition. Fedora has forced a flag day requiring the entire thing to happen at once; Debian, instead, has carefully avoided flag days in favor of a carefully-planned step-by-step change. One could argue that the Debian approach is better: it lets the transition "just happen" through normal package updates without the need for any special actions on the part of administrators or users. On the other hand, the multiarch transition has been a multi-year process and is still not complete; Fedora, instead, has pushed this change through in a small number of months.
Now that Fedora has made this jump and seems to be past the turning-back point, will other distributions follow suit? Some investigation suggests that Fedora will not be alone in this change:
Of course, Debian has some time to think about the problem. Nobody has suggested that usrmove could be added to the list of goals for the upcoming "wheezy" release, so any transition, even in the unstable tree, is likely to be at least a year away.
In short, it looks like, over time, the move toward keeping all binaries and libraries in /usr will spread through most Linux distributions.
Given that most users will likely not even notice the change, it is natural to wonder why the change is so controversial. Undoubtedly, some people dislike significant changes to how traditional Linux systems have been laid out. Possibly, some creatively-organized systems will not handle the transition well, leading to problems that must be fixed. Conceivably, the change strikes some people as useless churn with no real benefits - at least for them. And, almost certainly, it is a bikeshed-type issue that is easy to have an opinion on and complain about.
The truth of the matter is that it appears to be a reasonably well-thought-out change driven by some plausible rationales. Filesystem hierarchies are not set in stone; there are times when it makes sense to clean things up. The usrmove operation yields a filesystem that is easier to understand, easier to manage, and more consistent in its organization. Having been through the transition, your editor thinks it is probably worth the trouble.
Page editor: Jonathan Corbet
Security
Fedora is exploring a new security feature in the upcoming Fedora 17 release that is intended to make firewall configuration simpler for the average user. Based on features found in the new, D-Bus-enabled firewall tool, the Network Zones feature will automatically activate different sets of firewall rules based on the network location, and provide sensible defaults for different classes of network — from trusted connections at home to potentially dangerous open WiFi networks in public.
At the heart of Network Zones is the notion that each network has an associated trust level — fully trusted, mostly trusted, mostly untrusted, or fully untrusted. To serve the needs of users that regularly move between network locations, the firewall should ratchet up the netfilter rules to a stricter level when in an untrusted location such as a restaurant or public park, but ratchet them back down when reconnecting to the home or office network. Exactly which rules are applied at each trust level is up to the user or administrator.
Existing firewall tools, however, fall short in two ways. First, they know only about network interfaces, not about the networks themselves (trust information in particular). Second, they require stopping and restarting the firewall in order to change any settings. Red Hat's Thomas Woerner developed a solution tackling both issues based on GNOME's NetworkManager, and a new firewall application named Firewalld.
NetworkManager, which was designed to keep track of WiFi networks and opportunistically switch between them when roaming, already implemented some of the required functionality. It maintains a history of networks visited, and allows users to associate preferences with each saved network connection. Adding a trust level to each network connection would allow NetworkManager to instruct the firewall to change to a different rule set.
Firewalld solves the restarting problem by running as a D-Bus enabled daemon, listening for state change commands, and emitting information on the current status of the firewall. NetworkManager also uses D-Bus, so it can simply send a message to Firewalld telling it to raise or lower specific firewall rules as the situation dictates. To keep the firewall state consistent, though, Firewalld must be the only application modifying the settings (thus requiring that other firewall management packages be disabled), and for security reasons, all rule change requests accepted by Firewalld must be authenticated with PolicyKit.
In order for Firewalld to expose a straightforward set of configuration options to users (and other applications) over D-Bus, the firewall rule set had to be refactored into a clean set of distinct chains that correspond to individual features and services. Thus, adding or removing a rule in one chain will not interfere with the others. Firewalld implements chains for feature sets like virtualization, masquerading (NAT), port forwarding, and open ports, plus predefined chains for individual services like Samba or FTP.
The official Network Zones proposal on the Fedora wiki defines nine initial network trust levels: trusted (meaning fully trusted, with all incoming traffic permitted), home, work, and internal (all three of which are for mostly trusted networks), dmz, public, and external (which are mostly untrusted), and block and drop (which are both fully untrusted).
Firewalld provides an initial configuration for each zone in an XML file. By default, the mostly-trusted zones open only a select set of ports (SSH, mDNS, Samba, and Internet Printing Protocol (IPP) for the home and internal zones, and SSH and IPP for work). The mostly-untrusted zones are more restricted, with SSH being the only allowed protocol for public and dmz, but SSH allowed and IP Masquerading enabled for external — though it's not exactly clear what the benefit of the latter is. The block zone rejects all incoming connections, while the drop zone drops them silently.
Of course, the intent is for users or system administrators to customize each of the zones' configuration as desired, allowing some differentiation between the otherwise-identical offerings. There are GUI and command-line utilities (named firewall-config and firewall-cmd, respectively) for examining and altering the configuration options; however as of today not all of the Firewalld rules are supported in either tool.
There does not appear to be a DTD or XML Schema for the zone configuration or firewall rules yet, but the syntax is straightforward. Individual services are enabled with a <service name=servicename> element; the other available firewall options are enabled by adding an element specific to the feature, such as <masquerade enabled="True"/>.
Network Zone integration is available in the NetworkManager 0.9.4 release, which will be part of Fedora 17, allowing users to assign a trust level to each of their saved networks, as well as a default zone to apply to unknown network connections. A system tray applet will display the current firewall state in GNOME Shell. The project has discussed adding the same functionality to KDE's network manager as well.
Firewalld was first made available in Fedora 15, but with the completion of the Network Zones support, it is slated to become the default firewall configuration tool in Fedora 17 (scheduled for release in early May 2012). Network zone support is not the only benefit of the daemon-like firewall approach — D-Bus controls open the door for other dynamic features in the future, like triggering temporary firewall rules without manual intervention, and desktop notifications triggered by firewall events.
The Firewalld project is not resting on its laurels, however. The future plans include support for granting or limiting access to the configuration tools on a per-user basis, and more abstract firewall rules based on metadata — such as "allow external access to music sharing applications." Network Zones is of clear benefit to laptop users, who both expose their systems to the greatest risk while roaming, and have had the hardest time finding a balanced firewall policy. But the possibilities enabled by a dynamically controlled firewall extend further; only time will tell what roles it can fill that a static configuration hasn't.
Brief items
8. We are serious about all of the above. So don't go trying to sue us later with some nonsense like "I thought that was all satire." All your privacy are belong to us. We mean it..
New vulnerabilities
Page editor: Jake Edge
Kernel development
Brief items
Stable updates: 3.2.8 was released on February 27. 3.0.23 and 3.2.9 updates were released on February 29; they each contain just over 70 important fixes.
For a while, this made it really hard for us maintainers to tell which incoming patches we should actually read! Fortunately, the Anti-whitespace crusaders have come full circle: we can now tell newbie coders by the fact that they obey checkpatch.pl.
You remove UIO at the risk of pissing off those robots, the choice is yours, I know I'm not going to do it...
With Ingo Molnar's encouragement, Jason Baron recently posted a patch set changing the jump label mechanism to look like this:
if (very_unlikely(&jump_label_key)) { /* Rarely-used code appears here */ }
A number of reviewers complained, saying that very_unlikely() looks like just a stronger form of the unlikely() macro, which works in a different way. Ingo responded that the resemblance was not coincidental and made sense, but he made few converts. After arguing the point for a while, Ingo gave in to the inevitable and stopped pushing for the very_unlikely() name.
Instead, we have yet another format for jump labels, as described in this document. A
jump label
static key is defined with one of:
struct static_key key = STATIC_KEY_INIT_FALSE; struct static_key key = STATIC_KEY_INIT_TRUE;
The initial value should match the normal operational setting - the one that should be fast. Testing of static keys is done with:
if (static_key_false(&key)) { /* Unlikely code here */ }
Note that static_key_false() can only be used with a key initialized with STATIC_KEY_INIT_FALSE; for default-true keys, static_key_true() must be used instead. To make a key true, pass it to static_key_slow_inc(); removing a reference to a key (and possibly making it false) is done with static_key_slow_dec().
This version of the change was rather less controversial and, presumably, will find its way in through the 3.4 merge window. After that, one assumes, this mechanism will not be reworked again for at least a development cycle or two.
Kernel development news
The control group mechanism is really just a way for a system administrator to partition processes into one or more hierarchies of groups. There can be multiple hierarchies, and a given process can be placed into more than one of them at any given time. Associated with control groups is the concept of "controllers," which apply some sort of policy to a specific control group hierarchy. The group scheduling controller allows control groups to contend against each other for CPU time, limiting the extent to which one group can deprive another of time in the processor. The memory controller places limits on how much memory and swap can be consumed by any given group. The network priority controller, merged for 3.3, allows an administrator to give different groups better or worse access to network interfaces. And so on.
Tejun Heo started the discussion with a lengthy message describing his complaints with the control group mechanism and some thoughts on how things could be fixed. According to Tejun, allowing the existence of multiple process hierarchies was a mistake. The idea behind multiple hierarchies is that they allow different policies to be applied using different criteria. The documentation added with control groups at the beginning gives an example with two distinct hierarchies that could be implemented on a university system:
On their face, multiple hierarchies provide a useful level of flexibility for administrators to define all kinds of policies. In practice, though, they complicate the code and create some interesting issues. As Tejun points out, controllers can only be assigned to one hierarchy. For controllers implementing resource allocation policies, this restriction makes some sense; otherwise, processes would likely be subjected to conflicting policies when placed in multiple hierarchies. But there are controllers that exist for other purposes; the "freezer" controller simply freezes the processes found in a control group, allowing them to be checkpointed or otherwise operated upon. There is no reason why this kind of feature could not be available in any hierarchy, but making that possible would complicate the control group implementation significantly.
The real complaint with multiple hierarchies, though, is that few developers seem to see the feature as being useful in actual, deployed systems. It is not clear that it is being used. Tejun suggests that this feature could be phased out, perhaps with a painfully long deprecation period. In the end, Tejun said, the control group hierarchy could disappear as an independent structure, and control groups could just be overlaid onto the existing process hierarchy. Some others disagree, though; Peter Zijlstra said "I rather like being able to assign tasks to cgroups of my making without having to mirror that in the process hierarchy." So the ability to have a control group hierarchy that differs from the process hierarchy may not go away, even if the multiple-hierarchy feature does eventually become deprecated.
A related problem that Tejun raised is that different controllers treat the control group hierarchy differently. In particular, a number of controllers seem to have gone through an evolutionary path where the initial implementation does not recognize nested control groups but, instead, simply flattens the hierarchy. Later updates may add full hierarchical support. The block I/O controller, for example, only finished the job with hierarchical support last year; others still have not done it. Making the system work properly, Tejun said, requires getting all of the controllers to treat the hierarchy in the same way.
In general, the controllers have been the source of a lot of grumbling over the years. They tend to be implemented in a way that minimizes their intrusiveness on systems where they are not used - for good reason - but that leads to poor integration overall. The memory controller, for example, created its own shadow page tracking system, leading to a resource-intensive mess that was only cleaned up for the 3.3 release. The hugetlb controller is not integrated with the memory controller, and, as of 3.3, we have two independent network controllers. As the number of small controllers continues to grow (there is, for example, a proposed timer slack controller out there), things can only get more chaotic.
Fixing the controllers requires, probably more than anything else, a person to take on the role as the overall control group maintainer. Tejun and Li Zefan are credited with that role in the MAINTAINERS file, but it is still true that, for the most part, control groups have nobody watching over the whole system, so changes tend to be made by way of a number of different subsystems. It is an administrative problem in the end; it should be amenable to solution.
Fixing control groups overall could be harder, especially if the elimination of the multiple-hierarchy feature is to be contemplated. That, of course, is a user-space ABI change; making it happen would take years, if it is possible at all. Tejun suggests "herding people to use a unified hierarchy," along with a determined effort to make all of the controllers handle nesting properly. At some point, the kernel could start to emit a warning when multiple hierarchies are used. Eventually, if nobody complains, the feature could go away.
Of course, if nobody is actually using multiple hierarchies, things could happen a lot more quickly. Nobody entered the discussion to say that they needed multiple hierarchies, but, then, it was a discussion among kernel developers and not end users. If there are people out there using the multiple hierarchy feature, it might not be a bad idea to make their use case known. Any such use cases could shape the future evolution of the control group mechanism; a perceived lack of such use cases could have a very different effect.
A face-to-face meeting of the Android mainlining interest group, which is a community interested in upstreaming the Android patch set into the Linux kernel, was organized by Tim Bird (Sony/CEWG) and hosted by Linaro Connect on February 10th. Also in attendance were representatives from Linaro, TI, ST-Ericsson, NVIDIA, Google's Android and ChromeOS teams, among others.
The meeting was held to give better visibility into the various upstreaming efforts going on, making sure any potential collaboration between interested parties was able to happen. It covered a lot of ground, mostly discussing Android features that recently were re-added to the staging directory and how these features might be reworked so that they can be moved into mainline officially. But a number of features that are still out of tree were also covered.
Kicking off the meeting, participants introduced themselves and their interests in the group. Also some basic goals were covered just to make sure everyone was on the same page. Tim summarized his goals for the project as: to let android run on a vanilla mainline kernel, and everyone agreed to this as a desired outcome.
Tim also articulated an important concern in achieving this goal is the need to avoid regressions. As Android is actively shipping on a huge number of devices, we need to take care that getting things upstream at the cost of short term stability to users isn't an acceptable trade-off. To this point, Brian Swetland (Google) clarified that the Google Android developers are quite open to changes in interfaces. Since Android releases both userland and kernel bundled together, there is less of a strict need for backward API compatibility. Thus it's not the specific interfaces they rely on, but the expected behavior of the functionality provided.
This is a key point, as there is little value in upstreaming the Android patches if the resulting code isn't actually usable by Android. A major source of difficulty here is that the expected behavior of features added in the Android patch set isn't always obvious, and there is little in the way of design documentation. Zach Pfeffer (Linaro) suggested that one way to both improve community understanding of the expected behavior, as well as helping to avoid regressions, would be to provide unit tests. Currently Android is for the most part tested at a system level, and there are very few unit tests for the kernel features added. Thus creating a collection of unit tests would be beneficial, and Zach volunteered to start that effort.
At this point, the discussion was handed over to Magnus Damm to talk about power domain support as well as the wakelock implementation that the power management maintainer Rafael Wysocki had recently posted to the Linux kernel mailing list. The Android team said they were reviewing Rafael's patches to establish if they were sufficient and would be commenting on them soon.
Magnus asked if full suspend was still necessary now that run-time power-management has improved; Brian clarified that this isn't an either/or sort of situation. Android has long used dynamic power management techniques at run time, and they are very excited about using the run-time power-management framework to further to save power, but they also want to use suspend to further reduce power usage. They really would like to see deep idle for minutes to hours in length, but, even with CONFIG_NOHZ, there are still a number of periodic timers that keep them from reaching that goal. Using the wakelocks infrastructure to suspend allows them to achieve those goals.
Magnus asked if Android developers could provide some data on how effective run-time power-management was compared to suspend using wakelocks, and to let him know if there are any particular issues that can be addressed. The Android developers said they would look into it, and the discussion continued on to Tim and his work with the logger.
Back in December, Tim posted the logger patches to the linux-kernel list and got feedback for changes that he wanted to run by the Android team to make sure there were no objections. The first of these, which the Android developers supported, is to convert static buffer allocation to dynamic allocation at run-time.
Tim also shared some thoughts on changing the log dispatching mechanism. Currently logger provides a separation between application logs and system logs, preventing a noisy application from causing system messages to be lost. In addition, one potential security issue the Android team has been thinking about is a poorly-written (or deliberately malicious) application dumping private information into the log; that information could then be read by any other application on the system. A proposal to work around this problem is per-application log buffers; however, with users able to add hundreds of applications, per-application or per-group partitioning would consume a large amount of memory. The alternative - pushing the logs out to the filesystem - concerns the Android team as it complicates post-crash recovery and also creates more I/O contention, which can cause very poor performance on flash devices.
Additionally, the benefits from doing the logging in the kernel rather than in user space are low overhead, accurate tagging, and no scheduler thrashing. The Android developers are also very hesitant to add more long-lived daemons to the system, as while phones have gained quite a lot of memory and cpu capacity, there is still pressure to use Android on less-capable devices.
Another concern with some of the existing community logging efforts going on is that Android developers don't really want strongly structured logging, or binary logging, because it further complicates accessing the data when the system has crashed. With plain text logging, there is no need for special tools or versioning issues should the structure change between newer and older devices. In difficult situations, with plain text logging, a raw memory dump of the device can still provide very useful information. Tim discussed a proposed filesystem interface to the logger to which the Android team re-iterated their interface agnosticism, as long as access control is present and writing to the log is cheap. Tim promised to benchmark his prototypes to ensure performance doesn't degrade.
From here, the discussion moved to ION with Hiroshi Doyu (NVIDIA) leading the discussion. There had been an earlier meeting at Linaro Connect focusing on graphics that some of the ION developers attended, so Jesse Barker (Linaro) summarized that discussion. The basic goal there is to make sure the Contiguous Memory Allocator (CMA), dma-buf, and other buffer sharing approaches are compatible with both general Linux and Android Linux.
Dima Zavin (Google) clarified that ION is focused on standardizing the user-space interface, allowing different approaches required by different hardware to work, while avoiding the need to re-implement the same logic over and over for each device. The really hard part of buffer sharing is sorting out how to allocate buffers that satisfy all the constraints of the different hardware that will need to access those buffers. For Android, the constraints are constant per-device, so they can be statically decided, but for more generic Linux systems there may need to be some run-time detection of what devices a buffer might be shared with, possibly converting buffer types when a incompatible buffer interacts with a constrained bit of hardware for the first time. There are some conflicting needs here as Android is very focused on constant performance, and per-device optimizations allow that, whereas the more general proposed solution might have occasional performance costs, requiring buffers to be occasionally copied.
The ION work is still under development, and hasn't yet been submitted to the kernel mailing list, but Hiroshi pointed out that a number of folks are actively working on integrating the dma-buf and CMA work with ION, thus there is a need for a point where discussion and collaboration can be done. As it seems the ION work won't move upstream or into staging immediately, it's likely the linaro-mm-sig mailing list will be the central collaboration point.
The next topic, was ashmem, which John Stultz (Linaro/IBM) has been working on. He helped get the ashmem patches reworked and merged into staging, and is now working on pulling the pinning/unpinning feature from ashmem out of the driver and pushing it a little more deeply into the VM subsystem via the fadvise volatile interface. The effort is still under development, but there have been a number of positive comments on the general idea of the feature.
The current discussion with the code on linux-kernel is around how to best store the volatile ranges efficiently, and some of the behavior around coalescing neighboring volatile ranges. In addition there have been requests by Andrew Morton to find a way to reuse the range storage structure with the POSIX file locking code, which has similar requirements. This effort wouldn't totally replace the ashmem driver, as the ashmem driver also provides a way to get unlinked tmpfs file descriptors without having tmpfs mounted, but it would greatly shrink the ashmem code, making it more of a thin "Android compatibility driver", which would hopefully be more palatable upstream.
John then covered the Android Alarm Driver feature, which he had worked on partially upstreaming with the virtualized RTC and POSIX alarm_timers work last year. John has refactored the Android Alarm driver and has submitted it for staging in 3.4; he also has a patch queue ready which carves out chunks of the Android Alarm driver and converts it to using the upstreamed alarm_timers. To be sure regressions are not introduced, this conversion will likely be done slowly, so that any minor behavioral differences between the Android alarm infrastructure and the upstreamed infrastructure can be detected and corrected as needed. Further, the upstream POSIX alarm user interfaces are not completely sufficient to replace the Android Alarm driver, due to how it interacts with wakelocks, but this patch set will greatly reduce the alarm driver, and from there we can see if it would either be appropriate to preserve this smaller Android specific interface, or try to integrate the functionality into the timerfd code.
As Anton Vorontsov (Linaro) could not attend, John covered Anton's work on improving the low memory killer in the staging tree as well as his plans to re-implement the low memory killer in user space using a low-memory notifier interface to signal the Android Activity Manager. There is wider interest in the community in a low-memory notifier interface, and a number of different approaches have been proposed, using both control groups (with the memory controller) or simpler character device drivers.
The Android developers expressed concern that if the killing logic is pushed out to the Activity Manager, it would have to be locked into memory and the killing path would have to be very careful not to cause any memory allocations, which is difficult with Dalvik applications. Without this care, if memory is very tight, the killing logic itself could be blocked waiting for memory, causing the situation to only get worse. Pushing the killing logic into its own memory-locked task which was then carefully written not to trigger memory allocations would be needed, and the Android developers weren't excited about adding another long-lived daemon to the system. John acknowledged those concerns, but, as Anton is fairly passionate about this approach, he will likely continue his prototyping in order to get hard numbers to show any extra costs or benefits to the user-space approach.
Anton had also recently pushed out the Android "interactive cpufreq governor" to linux-kernel for discussion. Due to a general desire in the community not to add any more cpufreq code, it seems the patches won't be going in as-is. Instead it was suggested that the P-state policy should be in the scheduler itself, using the soon-to-land average load tracking code, so Anton will be doing further research there. There was also a question raised whether the ondemand cpufreq governor would not now be sufficient, as a number of bugs relating to the sampling period had been resolved in the last year. The Android developers did not have any recent data on ondemand, but suggested Anton get in touch with Todd Poyner at Google as he is the current owner of the code on their side.
Having covered most of the active work, folks discussed which items might be too hard to ever get upstream.
The paranoid network interface, which hard-fixes device permissions to specific group IDs, is clearly not generic enough to be able to go upstream. Arnd Bergmann (Linaro/IBM) however commented that network namespaces could be used to provide very similar functionality. The Android developers were very interested in this, but Arnd warned that the existing documentation is narrowly scoped and will likely be lacking to help them do exactly what they want. The Android developers said they would look into it.
The binder driver also was brought up as a difficult bit of code to get included into mainline officially. The Android developers expressed their sympathy as it is a large chunk of code with a long history, and they themselves have tried unsuccessfully to implement alternatives. However, the specific behavior and performance characteristics of binder are very useful for their systems. Arnd made the good point that there is something of a parallel to SysV IPC. The Linux community would never design something like SysV IPC, and generally has a poor opinion of it, but it does support SysV IPC to allow applications that need it to function. Something like this sort of a rationale might be persuasive to get binder merged officially, once the code has been further cleaned up.
At this point, after 4 hours of discussion, the focus started to fray. John showed a demo of the benefit of the Android drivers landing in staging, with an AOSP build of Android 4.0 running on a vanilla 3.3-rc3 kernel with only few lines of change. Dima then showed off a very cool debugging tool for their latest devices. With a headphone plug on one end and USB on the other, he showed off how the headphone jack on the phone can do double duty as a serial port allowing for debug access. With this, excited side conversations erupted. Tim finally thanked everyone for attending and suggested we do this again sometime soon, personal and development schedules allowing.
Many thanks to the meeting participants for an interesting discussion, Tim Bird for organizing, and to Paul McKenney, Deepak Saxena, and Dave Hansen for their edits and thoughts on this summary.
Shibata-san again presented about LTSI at ELC 2012, giving more details about how the project would be run, and how to get involved. The full slides for the presentation [PDF] are available online.
The LTSI project has grown out of the needs of a large number of consumer electronic companies that use Linux in their products. They need a new kernel every year to support newer devices, but they end up cobbling together a wide range of patches and backports to meet their needs. At LinuxCon in Europe, the results of a survey of a large number of kernel releases in different products showed that there are a set of common features that different companies need, yet they were implemented in different ways, pulling from different upstream kernel or project versions, and combining them in different kernel versions with different bug fixes, some done in opposite ways. The results of this survey are now available for the curious.
This is usually done because of the short development cycle that consumer electronic companies are under in order to get a product released. Once a product is released, the development cycle starts up again, and old work is usually forgotten, except to the extent that it is copied into the new project. This cycle is hard to break out of, but that needs to happen in order to be able to successfully take advantage of the Linux kernel community's releases.
The LTSI project's goals were summarized as:
Let's look at these goals individually, to find out how they are going to be addressed.
A few months ago, after discussing this project and the needs of the embedded industry, I announced that I will be maintaining a longterm Linux kernel for bugfixes and security updates for two years after it was originally released by Linus. This kernel version will be picked every year, enabling two different longterm kernels to be supported at the same time. The rules of these kernels are the same as the normal stable kernel releases, and can be found in the in-kernel file Documentation/stable_kernel_rules.txt.
The 3.0 kernel was selected last August as the first of these longterm kernels to be supported in this manner. The previous longterm kernel, 2.6.32, which was selected with the different enterprise Linux distributions' needs in mind, will still be maintained for a while longer as they rely on this kernel version for their users.
As the 3.0 kernel was selected last August, it looks like the next longterm kernel will be selected sometime around August, 2012. I've been discussing this decision with a number of different companies about which version would work well for them, and if anyone has any input into this, please let me know.
As shown at LinuxCon Europe, basing a product kernel on just a community-released kernel does not usually work. Almost all consumer electronics releases depend on a range of out-of-tree patches for some of their features. These patches include the Android kernel patch set, LTTng, some real-time patches, different architecture and system-on-a-chip support, and various small bugfixes. These patches, even if they are accepted upstream into the kernel.org releases, usually do not fit the requirements that the community stable kernel releases require. Because of that, the LTSI kernel has been created.
This kernel release will be based on the current longterm community-based kernel, with a number of these common patchsets applied. Applying them in a single place enables developers from different companies to be assured that the patches are correct, they have the latest versions, and, if any fixes are needed, they can be done in a common way for all users of the code. This LTSI kernel tree is now public, and can be browsed at. [Editor's note: this site, like the LTSI page linked below, fails badly if HTTPS is used; "HTTPS Everywhere" users will have difficulty accessing these pages.] It currently contains a backport of the Android kernel patches, as well as the latest LTTng codebase. Other patches are pending review to be accepted into this tree in the next few weeks.
This tree is set up much like most distribution kernel trees are: a set of quilt-based patches that apply on top of an existing kernel.org release. This organization allows the patches to be easily reworked, and even removed if needed; patches can also be forward-ported to new kernel releases without the problems of rebasing a whole expanded kernel git tree. There are scripts in the tree to generate the patches in quilt, git, or just tarball formats, meeting the needs of all device manufacturers.
During the hallway track at ELC 2012, I discussed the LTSI kernel with a number of different embedded companies, embedded distributions, and community distributions. All of these groups were eager to start using the LTSI kernel as a base for their releases, as no one likes to do the same work all the time. By working off of a common base, they can then focus on the real value they offer their different communities.
Despite the continued growth of the number of developers and companies that are contributing to the Linux kernel, some companies still have a difficult time of figuring out how to get involved. Because of this, a specific effort to get embedded engineers working upstream is part of the LTSI project.
The LTSI kernel will accept patches from companies even if they contain code that does not meet the normal acceptance criteria set by Linux kernel developers due to technical reasons. These patches will be cleaned up in the LTSI kernel tree and helped to be merged upstream by either submission to the various kernel subsystem groups, or through the staging subsystem if the code will need more work than a simple cleanup. This feedback loop into the community is to help these embedded engineers learn how to work with the community, and in the end, be part of the community directly, so for the next product they have to create, they will not need to use the LTSI kernel as a "launching pad".
The end goal of LTSI is to put itself out of business. With companies learning how to work directly with mainstream, their patches will not need the help of the LTSI developers to be accepted. And if those patches are accepted, their authors will not have to maintain them on their own for their product's lifetime; instead, they can just rely on the community longterm kernel support schedule for the needed bugfixes and security updates. However, until those far-reaching goals are met, there will be a need for the LTSI project and developers for some time.
If you work for a company interested in working with the LTSI kernel as either a base for your devices, or to help get your code upstream, please see the LTSI web site for information on how to get involved.
Patches and updates
Kernel trees
Architecture-specific
Core kernel code
Development tools
Device drivers
Documentation
Filesystems and block I/O
Memory management
Networking
Security-related
Virtualization and containers
Benchmarks and bugs
Miscellaneous
Page editor: Jonathan Corbet
Distributions
In Hinduism and Buddhism, a chakra is one of several centers of energy in the body. In free software, The Chakra Project is a fork of Arch Linux. The name is appropriate, because, like its mystical namesake, Chakra concentrates on several centers of development within the general body of Linux, including a design that is simple yet aimed at intermediate users, the creation of a system that consists of only KDE/Qt applications, and an original selection of default software. Some of these concentrations are well-advanced, while others are still in early development.
According to project leader Phil Miller, Chakra began as a sub-project in Arch Linux to develop a version of KDE called KDEMod. It differs from other KDE versions in that it split and reordered packages and added a few minor usability enhancements, such as extra options in the Dolphin file manager's context menu. The same sub-project also started developing a Live CD and a graphical installer. However, he said:
Developer Jan Mette wrote scripts to create packages from the Arch Linux repositories, and eventually created a new repository called core, which was working toward a fork. Then, abruptly, he disappeared from IRC and forums. When news came that Mette had died, Miller said, those in the sub-project "decided to go on with his dream and started the fork. We honor Jan with the Chakra distribution.".
Technically, Chakra differs from Arch Linux in several ways. Boersma explained that, for one thing, Chakra is developing a package manager that, instead of using text files like Arch Linux, uses a true database, and supports a graphical interface rather than a text-based installer. In addition, Chakra developers are dedicated to creating a distribution consisting entirely of KDE/Qt applications, without any GTK2 build dependencies or libraries. This policy affects many aspects of Chakra, including its development priorities and application selection.
However, Boersma said, the major difference from Arch is philosophical:
In other ways, Chakra continues to resemble Arch Linux, sharing an emphasis on speed, minimalism, and hands-on administration. The main differences are opinions on how to attain those goals and user-friendliness. If Arch Linux can be characterized as intended for experienced users, then Chakra could be described as aimed at intermediate users. Or, as the online help for the Live CD suggests, Chakra is aimed at "KISS-minded users who aren't afraid to get their hands dirty."
Boersma described the relationship today between Arch Linux and Chakra as "mostly mutual respect, where a few Arch developers communicate regularly with Chakra developers, giving advice, and exchanging ideas about found bugs, and how to correct those issues found."
Today, Chakra is developed by about ten regular contributors and enjoys a moderate popularity. Its first release series was downloaded nearly 115,000 times, while the 2012.02 release (codenamed "Archimedes") was downloaded 40,000 times in its first week, according to Boersma. At Distrowatch, Chakra is currently in thirteenth position for page views, which, if nothing else, indicates a strong curiosity in the free software community about the young distribution.
True to its basic policy, Chakra is developing its own Qt4-based installer, called Tribe. Tribe is currently in Alpha release, and its interface is sometimes illogical — for instance, at the partitioning stage, users must click the "Advanced" button rather than the "Format" button. Functionally, it is about equivalent to the Ubuntu installer, offering much less user control than Arch's installer, although more control of the installation process is planned for later releases.
Tribe is different enough from other installers that users should read Chakra's comprehensive Beginner's Guide before plunging into an installation, as well as consult the Welcome widget, a small Plasma application that opens when you boot the Live CD's desktop to display release notes.
For instance, since you are never asked to set a root password, you might assume that Chakra uses sudo without a root password, the way that Ubuntu does. In fact, sudo is set up, but Tribe also automatically assigns the root user the same password as the user account you create during installation — a practice that saves a step, but which security-minded users might want to change immediately after their first login.
Even more importantly, just before you install, you confront a button inviting you to "Download Popular Bundles". Contrary to what you might first think, "bundles" are not Chakra's jargon for packages. Rather, they are Chakra's way of permitting the use of GTK2 applications without actually adding their libraries and dependencies to the system. While Qt-based applications are installed via normal packages, GTK2-based ones are made available as loop-mounted squashfs/lzma filesystem images that also contain their dependencies.
This approach may seem like an overly complicated way to ensure a pure KDE/QT system. However, what it means in practice is that if you want applications like Audacity, Chrome, Firefox, Inkscape, GIMP, or Thunderbird, you should select the button during installation, even though nothing in Tribe itself indicates why you might want to. Otherwise, you face installing GTK2 apps afterward with a bundle manager that is currently little more than a list placed in a window.
But even without such idiosyncrasies, Tribe leaves something to be desired. For one thing, it has no provision for selecting individual packages and bundles within the installer, which is unlikely to to please Chakra's target audience.
For another, Tribe does not work consistently on some hardware. In my experience, it seems especially prone to display corruption at the partitioning stage. A workable but annoying solution is to repeat efforts to install three or four times until they succeed. Overall, Tribe is an interesting preview, but unfinished enough that perhaps it should not be included in the current release.
With GTK2 applications banished to Bundles, Chakra has a KDE orientation whose thoroughness is unusual among current distributions. Boersma told me that Chakra's founders decided that having too many desktop environments would only create a "splitting of resources," so that the distribution would end up "not doing any desktop environment the way it could be done, if it had the full and only attention." The founders chose KDE, Miller said, because "we want to showcase KDE as it should be."
For this reason, Chakra offers what appears to be a largely unmodified version of KDE 4.8, using the standard Oxygen widgets and icons with the main menu in its usual position on the bottom left along with the basic selection of Activities. Branding is confined chiefly to the Chakra Project wallpaper.
The main difference in KDE on Chakra is that — subjectively, at least — it is much faster than most installations. Boersma attributed the apparent speed to the removal all traces of GTK2 from core packages. "Because Chakra has stripped all of its base packages of any GTK libs, it does start showing a difference in lightness," Boersma insisted. "Strip it from one or two applications you run, you won't notice so much, but keep multiplying it by so many base packages that carry everything to run on both GTK2 and QT/KDE based systems, and the end results start adding up. ."
Where possible, Chakra's software is free-licensed, although it does include the common proprietary drivers and proprietary-dependent free tools like Q4wine, a Qt interface for WINE. Much of the software, too, will be familiar to KDE users, such as Marble, KDE's answer to Google Earth and Maps, or KNetAttach, the wizard for integrating network resources for the desktop.
However, much of Chakra's software will be strange even to many KDE users. The default browser is Rekonq, and the lightweight music player Bangarang. Chakra also borrows SUSE Studio Imagewriter for creating bootable USB drives, and Ubuntu's System Cleaner for removing unwanted files. Other menu items, such as miniBackup, are merely shell scripts to automate a process. Taken as a whole, they make an intriguing change from the standard applications in most distributions, and are enough by themselves to make an afternoon's exploration of Chakra worthwhile.
In the current release, Chakra uses Arch's Pacman for package installation, and CInstall, a rough and ready interface which the project site calls a "temporary GUI" for bundles. This division is inconvenient — especially if you cannot recall or have no idea whether a particular application uses Qt or GTK2. However, Pacman is scheduled to be replaced in the near future with a new package manager called Akabei. Eventually, too, package and bundle installation will be combined into a single utility, possibly based on Arch Linux's Shaman, a front end for Pacman.
Chakra's latest release may inspire mixed reactions. On the one hand, the incompleteness of the installer and the mixed system of packages and bundles is irritating. Granted, the development team makes no secret that Chakra is incomplete, yet could the release not wait until these things were more polished? Or does the project not consider initial setup and application installation part of the core that needs to be reliable?
On the other hand, these shortcomings offer few difficulties that Chakra's target users should not be able to overcome. Moreover, Chakra's traditional virtues — speed, efficiency, and do-it-yourself maintenance — are likely to have a deep appeal to its target users. At a time when many major distributions hide complexity for the sake of helping newcomers, Chakra aims for simplicity with a hands-on approach. Add an original selection of applications, and many users might be able to forgive the distribution's uneven edges.
Others might prefer to wait until Chakra is out of rapid development before using it as a main desktop. However, no matter what the immediate verdict, Chakra is among the most innovative of newer distributions. What it accomplishes in the next release or two should be worth watching.
Brief items
IME, people are pleasantly surprised when they drop a patch on [LaunchPad] and that results in a package getting fixed; I've never heard of someone being disappointed they didn't have to go through another round of review.
Full Story (comments: 21)
Full Story (comments: none)
Full Story (comments: none)
Distribution News
Fedora
Full Story (comments: none)
Newsletters and articles of interest
Page editor: Rebecca Sobol
Development
The D-Bus interprocess communication (IPC) mechanism is used extensively by Linux desktop environments and applications, but it suffers from less-than-optimal performance. While that problem may not be so noticeable on desktop-class systems, it can be a real issue for smaller and embedded devices. Over the years there have been a number of attempts to add functionality to the kernel to increase D-Bus performance, but none have passed muster. A recent proposal to add multicast functionality to Unix sockets is another attempt at solving that problem.
D-Bus currently relies on a daemon process to authenticate processes and deliver messages that it receives over Unix sockets. Part of the performance problem is caused by the user-space daemon, which means that messages need two trips through the kernel on their way to the destination (once on the way to the daemon and another on the way to the receiver). It also requires waking up the daemon and an "extra" transition to and from kernel mode. Putting D-Bus message handling directly into the kernel would eliminate the need to involve the daemon at all. That would eliminate one of the transitions and one of the copies, which would improve performance.
If all of the D-Bus messages were simply between pairs of processes, Unix sockets could potentially be used directly between them. But there is more to D-Bus than that. Processes can register for certain kinds of events they wish to receive (things like USB devices being attached, a new song playing, or battery status changes for example), so a single message may need to be multicast to multiple receivers. That is part of what the daemon mediates.
Earlier efforts to add an AF_DBUS socket type (and associated kdbus module) to handle D-Bus messages in the kernel weren't successful because kernel hackers were not willing to add the complexity of D-Bus routing. The most recent proposal was posted by Javier Martinez Canillas based on work from Alban Créquy, who also proposed the AF_DBUS feature. It adds multicasting support to Unix (i.e. AF_UNIX) sockets, instead, while using packet filters so that receivers only get the messages they are interested in. That way, the routing is strictly handled via multicast plus existing kernel infrastructure.
As described in Rodrigo Moya's blog posting, there are a number of reasons that a D-Bus optimization can't use the existing mechanisms in the kernel. Netlink sockets would seem to be one plausible alternative, and there is support for multicasting, but D-Bus requires fully reliable delivery even if the receiver's queue is full. In that case, netlink sockets just drop packets, while D-Bus needs the sender to block until the receiver processes some of its messages. In addition, netlink sockets do not guarantee the ordering of multicast messages that D-Bus requires.
Another option would be to use UDP multicast, but Moya (and Canillas) seem skeptical that it will perform as well as Unix socket multicast. There is also a problem for devices that do not have a network card, because the lo loopback network device does not support multicast. Moya also notes that a UDP-based solution suffers from the same packet loss and ordering guarantee problems that come with netlink sockets.
So, that left Créquy and others at Collabora (including Moya, Canillas, and others) to try a different approach. Créquy outlines the multicast approach on his blog. Essentially, both SOCK_DGRAM and SOCK_SEQPACKET socket types can create and join multicast groups which will then forward all traffic to each member of the group. Datagram multicast allows any process that knows the group address to join, while seqpacket multicast (which is connection-oriented like a SOCK_STREAM but enforces message boundaries) allows the group creator to decide whether to allow a particular group member at accept() time.
As Moya described, a client would still connect to the D-Bus daemon for authentication, and would then be added to the seqpacket multicast group for the bus. The daemon would also attach a packet filter that would eliminate any of the messages that the client should not receive. One of the patches in the set implements the ability for the daemon to attach a filter to the remote endpoint, so that it would be in control of which messages a client can see.
The idea is interesting, but so far comments on the netdev mailing list have been light. Kernel network maintainer David Miller is skeptical that the proposal is better than having the daemon just use UDP:
I can't see how this is better than doing multicast over ipv4 using UDP or something like that, code which we have already and has been tested for decades.
Cannilas responded by listing some of the reasons that UDP multicast would not serve their purposes, but admitted that no performance numbers had yet been gathered. Miller said that he will await those numbers before reviewing the proposal further, noting: "In many cases TCP/UDP over loopback is actually faster than AF_UNIX.".
Even if UDP has the needed performance, some solution would need to be found for the packet loss and ordering issues. Blocking senders due to inattentive receivers may be a hard sell, however, as it seems like it could lead to denial of service problems, no matter which socket type is used. But it is clear that there is a lot of interest in better D-Bus performance. In fact, it goes well beyond just D-Bus as "fast" IPC mechanisms are regularly proposed for the kernel. It's unclear whether multicasting for Unix sockets is suitable for that, but finding a way to speed up D-Bus (and perhaps other IPC-using programs) is definitely on some folks' radar.
Brief items
Full Story (comments: none)
Newsletters and articles
Page editor: Jonathan Corbet
Announcements
Brief items
Full Story (comments: none)
Full Story (comments: none)
Full Story (comments: 15)
Full Story (comments: none)
Full Story (comments: none)
Articles of interest
New Books
Full Story (comments: none)
Full Story (comments: none)
Calls for Presentations
Full Story (comments: none)
Upcoming Events
If your event does not appear here, please tell us about it.
Page editor: Rebecca Sobol
Linux is a registered trademark of Linus Torvalds
|
https://lwn.net/Articles/483442/bigpage
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
(switching lists to python-ideas, dropping python-dev and python-checkins) Context for anyone not following python-checkins: I recently moved PEP 3150 (statement local namespaces) to Withdrawn, rewrote PEP 403 with a different syntax proposal, retitled it to "Statement local class and function definitions" and moved it to Deferred. On Fri, Feb 24, 2012 at 2:37 AM, Jim Jewett <jimjjewett at gmail.com> wrote: > I understand that adding a colon and indent has its own problems, but > ... I'm not certain this is better, and I am certain that the desire > for indentation is strong enough to at least justify discussion in the > PEP. Fair point. The reason for the flat structure is that allowing a full suite screws with the scoping rules and gets us into the land of insane complexity that was PEP 3150. A decorator-inspired syntax makes it very clear (both to the reader and to the compiler) that there's only *one* name being forward referenced, rather than potentially hiding declarations of forward references an arbitrary distance from the statement that uses them. This doesn't actually lose any flexibility, since you can just make a forward reference to a class instead and use that as your local namespace (with ordinary attribute access semantics), rather than the brain-bender that was the proposed scoping rules for PEP 3150's given clause. The only other alternative syntax would be to use a custom suite definition that allowed only a single class or function definition statement, but I think having something that looks like a suite, but isn't one would be significantly worse than the current proposed syntax that merely allows a function (or class) definition's implied local name binding to be overridden with a custom statement. To (almost*) recreate the effect of an ordinary function definition with the in statement, you could write: in f = f def f(): pass And a decorated definition like: @deco1 @deco2 @deco3 def f(): pass Could (almost*) be expressed as: in f = deco1(deco2(deco3(f))) def f(): pass * The reason for the "almost" caveat is that, given the current PEP 403 semantics, recursive references to f() will resolve differently for the "in" statement cases - for the in statement, they will resolve directly to the innermost function definition, while for ordinary definitions they will be resolved according to the scoping rules for any name lookup. This could be an argument in favour of allowing *decorated* function and class definitions, rather than requiring that they be undecorated - if decorators are allowed, then recursive references would resolve directly to the post-decorated version. Alternatively, people could adopt a convention of prepending an underscore to the actual function name in cases where it mattered, meaning they would have easy access to *both* forms of the function (decorated and undecorated): in f = deco1(deco2(deco3(_f))) def _f(): return f, _f # decorated, undecorated In either case, whereas an ordinary recursive function definition can get confused by reassignments in the outer scope, an in-statement based definition would be truly recursive (via a cell reference) and hence ignore any subsequent changes in the outer namespace. Something else the PEP should mention explicitly is that, like __class__, a class object obviously won't be available while the class body is being executed. Only methods will be able to refer to the class by name, just as only methods can use __class__. Updates to PEP 403 are going to be pretty sporadic until some time after 3.3 release though - it's still very much in "this is a problem I am thinking about" territory rather than "this is a language addition I am proposing" (the latest round of updates were just to make sure I recorded my latest idea before I forgot about the details). Cheers, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
|
https://mail.python.org/pipermail/python-ideas/2012-February/014182.html
|
CC-MAIN-2017-30
|
en
|
refinedweb
|
I:
namespace awl { class kernel_mutex { public: kernel_mutex() { hMutex = ::CreateMutex(NULL, FALSE, NULL); AWL_ASSERT(hMutex != INVALID_HANDLE_VALUE); } ~kernel_mutex() { AWL_VERIFY(::CloseHandle(hMutex) != FALSE); } void lock() { AWL_VERIFY(::WaitForSingleObject(hMutex, INFINITE) == 0); } void unlock() { AWL_VERIFY(::ReleaseMutex(hMutex) != FALSE); } private: HANDLE hMutex; }; template <class T> class lock_guard { public: lock_guard(T & m) : Mutex(m) { Mutex.lock(); } ~lock_guard() { Mutex.unlock(); } private: T & Mutex; }; }; //namespace awl typedef awl::kernel_mutex mutex; typedef awl::lock_guard<mutex> lock_guard;
Also I turned off ZI and Cm compiler options that are not compatible with CLI (/crl) and linked MFC and runtime dynamically.
The only small thing that I have not solved yet is that some MFC DLL triggered fore asserts at startup probably related to thread local storage and MFC module state so I press “Ignore” button fourfold each time I start my application.
The alternate way to add WPF content to existing MFC application is to show entire WPF window with the following code:
MyWpfWindow ^ window = gcnew MyWpfWindow(); System::Windows::Interop::WindowInteropHelper ^ helper = gcnew System::Windows::Interop::WindowInteropHelper(window); helper->Owner = IntPtr(m_hWnd); window->Show();
|
https://developernote.com/2014/04/using-a-wpf-control-in-a-mfc-application/
|
CC-MAIN-2018-30
|
en
|
refinedweb
|
Grails 2.3 has been released recently. This time, it is a release with a lot of new features.
IMHO, The most outstanding features are the REST improvements (including scaffolding of REST controllers) and the new support for an asynchronous programming model using promises.
Server-Side REST Improvements
Mapping to REST resources
You can now easily create RESTful URL mappings that map onto controllers. In the UrlMappings.groovy file, you can define which URL should be mapped to which restful controller.
"/api/books"(resources:'book')
This will map the HTTP operations to controller actions, e.g. GET on the URL /books will map to the index action, POST on this URL will map to the save action etc.
Scaffolding of REST controllers
This is a big one. All controllers scaffolded by Grails are REST controllers, so you can not only see the HTML representation of your data in the browser, but you can also retrieve the data in the form of XML or JSON.
What does that mean? You could instantly start to write, e.g., a mobile client for your app, you could connect your application to other applications or you could build a single page application that communicates with your controllers via JSON.
To achieve this, the respond() and withFormat() methods are used. respond() attempts to return the most appropriate type for the requested content type. A caller can specify the requested content type by either using a format=… request parameter, or by using a file extension (e.g. /book/show/1.json) or by using an accept header (which is the most natural way IMHO).
You have to explicitly enable content negotiation with accept headers in Config.groovy:
grails.mime.use.accept.header = true
The withFormat() method lets you decide what to render based on the requested content type.
Here is an example of two scaffolded controller actions:
def show(Book bookInstance) { respond bookInstance } @Transactional def update(Book bookInstance) { // ... if (bookInstance.hasErrors()) { respond bookInstance.errors, view:'edit' return } bookInstance.save flush:true request.withFormat { form { flash.message = message(code: 'default.updated.message', args: [message(code: 'Book.label', default: 'Book'), bookInstance.id]) redirect bookInstance } '*'{ respond bookInstance, [status: OK] } } }
Async support
Grails 2.3 supports a new asynchronous programming API based on promises.
import static grails.async.Promises.* def p1 = task { 2 * 2 } def p2 = task { 4 * 4 } def p3 = task { 8 * 8 } onComplete([p1,p2,p3]) { List results -> assert [4,16,64] == results } def promiseList = tasks { 2 * 2 }, { 4 * 4}, { 8 * 8 } assert [4,16,64] == promiseList.get()
GORM also supports async features, so you can execute database queries in parallel:
import static grails.async.Promises.* // ... def index() { tasks books: Book.async.list(), totalBooks: Book.async.count() }
Controller Exception Handling and namespaced controllers
Prior Grails versions allowed to define a central Exception handler. Grails 2.3 allows to specify exception handling logic on a per controller level:
class DemoController { // ... def handleSQLException(SQLException e) { render 'An SQLException occurred' } def handleBatchUpdateException(BatchUpdateException e) { redirect controller: 'logging', action: 'batchProblem' } }
The new version also allows multiple controllers with the same name (in different packages) by specifying a static namespace field in the controller class.
You can then define a corresponding URL mapping:
class UrlMappings { static mappings = { '/userAdmin' { controller = 'admin' namespace = 'users' } '/reportAdmin' { controller = 'admin' namespace = 'reports' } } }
Default dependency resolution engine switched to Aether
Grails 2.3 tries to solve a lot of dependency management problems (which a lot of Grails users experienced) by adding support for the dependency manager Aether. Prior Grails 2.3, Grails used Ivy which seems to be responsible for a lot of trouble (e.g. problematic snapshot handling). Aether is the dependency manager used by Maven and should solve most issues users experienced when using Ivy.
Improved Data Binding
The new Grails version improves data binding by allowing finer grained control of the binding.
In Grails 2.3, you can customize the binding logic on a per class or per field level using the BindUsing annotation. Alternatively, you can implement your own ValueConverters. Date conversions can be customized with the BindingFormat annotation.
Improvements to Command Objects
You can now use domain classes as command objects.
If an id parameter is included in the request, the corresponding database record will be retrieved automatically.
def update(Book bookInstance) { // ... }
You can now bind the request body to command objects. Grails will automatically parse the body of incoming requests. E.g. when it contains JSON or XML data, it will be automatically parsed and bound to a command object.
For more information, see the What’s new in Grails 2.3? section in the user guide.
|
https://blog.oio.de/2013/09/13/grails-2-3-with-asynchronous-apis-and-server-side-rest-improvements/
|
CC-MAIN-2018-30
|
en
|
refinedweb
|
A too.
In the above image, since 1 was kept in the queue before 2, it was the first to be removed from the queue as well. It follows the FIFO rule.
In programming terms, putting an item in the queue is called an "enqueue" and removing an item from the queue is called "dequeue".
We can implement queue in any programming language like C, C++, Java, Python or C#, but the specification is pretty much the same.
A queue is an object or more specifically an abstract data structure(ADT) that allows the following operations:
Queue operations work as follows:
The most common queue implementation is using arrays, but it can also be implemented using lists.
#include<stdio.h> #define SIZE 5 void enQueue(int); void deQueue(); void display(); int items[SIZE], front = -1, rear = -1; int main() { //deQueue is not possible on empty queue deQueue(); //enQueue 5 elements enQueue(1); enQueue(2); enQueue(3); enQueue(4); enQueue(5); //6th element can't be added to queue because queue is full enQueue(6); display(); //deQueue removes element entered first i.e. 1 deQueue(); //Now we have just 4 elements display(); return 0; } void enQueue(int value){ if(rear == SIZE-1) printf("\nQueue is Full!!"); else { if(front == -1) front = 0; rear++; items[rear] = value; printf("\nInserted -> %d", value); } } void deQueue(){ if(front == -1) printf("\nQueue is Empty!!"); else{ printf("\nDeleted : %d", items[front]); front++; if(front > rear) front = rear = -1; } } void display(){ if(rear == -1) printf("\nQueue is Empty!!!"); else{ int i; printf("\nQueue elements are:\n"); for(i=front; i<=rear; i++) printf("%d\t",items[i]); } }
When you run this program, you get the output
Queue is Empty!! Inserted -> 1 Inserted -> 2 Inserted -> 3 Inserted -> 4 Inserted -> 5 Queue is Full!! Queue elements are: 1 2 3 4 5 Deleted : 1 Queue elements are: 2 3 4 5
#include <iostream> #define SIZE 5 using namespace std; class Queue { private: int items[SIZE], front, rear; public: Queue(){ front = -1; rear = -1; } bool isFull(){ if(front == 0 && rear == SIZE - 1){ return true; } return false; } bool isEmpty(){ if(front == -1) return true; else return false; } void enQueue(int element){ if(isFull()){ cout << "Queue is full"; } else { if(front == -1) front = 0; rear++; items[rear] = element; cout << endl << "Inserted " << element << endl; } } int deQueue(){ int element; if(isEmpty()){ cout << "Queue is empty" << endl; return(-1); } else { element = items[front]; if(front >= rear){ front = -1; rear = -1; } /* Q has only one element, so we reset the queue after deleting it. */ else { front++; } cout << endl << "Deleted -> " << element << endl; return(element); } } void display() { /* Function to display elements of Queue */ int i; if(isEmpty()) { cout << endl << "Empty Queue" << endl; } else { cout << endl << "Front -> " << front; cout << endl << "Items -> "; for(i=front; i<=rear; i++) cout << items[i] << ""\t"; cout << endl << "Rear -> " << rear << endl; } } }; int main() { Queue q; //deQueue is not possible on empty queue q.deQueue(); //enQueue 5 elements q.enQueue(1); q.enQueue(2); q.enQueue(3); q.enQueue(4); q.enQueue(5); //6th element can't be added to queue because queue is full q.enQueue(6); q.display(); //deQueue removes element entered first i.e. 1 q.deQueue(); //Now we have just 4 elements q.display(); return 0; }
When you run this program, the output will be
Queue is empty Inserted 1 Inserted 2 Inserted 3 Inserted 4 Inserted 5 Queue is full Front -> 0 Items -> 1 2 3 4 5 Rear -> 4 Deleted -> 1 Front -> 1 Items -> 2 3 4 5 Rear -> 4
As you can see in the image below, after a bit of enqueueing and dequeueing, the size of the queue has been reduced.
The indexes 0 and 1 can only be used after the queue is reset when all the elements have been dequeued.
By tweaking the code for queue, we can use the space by implementing a modified queue called circular queue.
|
https://www.programiz.com/dsa/queue
|
CC-MAIN-2018-30
|
en
|
refinedweb
|
2015-12-22 04:42 AM
Hi,
Does anyone have experience with the exchange of certificates on Cognos Server ?
We like to import our own Certificates.
I try this as described in the Cognos documentation ,
create signrequest / encryptrequest....
create cert in our CA
import cert
config cognos to Use third party CA,
but the Report Server show always the selfsigned Cert from the Basic Installation.
Thanks Michael
Solved! SEE THE SOLUTION
2015-12-22 05:17 AM
Michael,
The following previously answered thread may help you.
The jboss we ship is SSL enabled with a self signed cert out of the box. On OCI 7.0.x, we no longer ship Apache, and instead use Jboss to front-end the Cognos components. Theoretically, this procedure should work to replace the self signed SSL certs on each OCI operational server as well as DWH.
The Jboss certs/keys are stored in the java keystore. The password is changeit.
..\SANscreen\jboss\server\onaro\cert
Contains the keystore – backup this file, and at any point, you can safely revert to your original keystore by reverting to your backup, and restarting the “SANscreen Server” service, along with all acquisition units.
Oracle ships a keytool with Java. It should be in your ..\java\bin folder
##############
First, understand what is in the keystore by doing a verbose list
keytool -list -v -keystore "c:\Program Files\SANscreen\jboss\server\onaro\cert\server.keystore"
Alias name: ABC
We may need to purge certain keys:
keytool -delete -alias localhost -keystore "c:\Program Files\SANscreen\jboss\server\onaro\cert\server.keystore"
Then, generate new key
keytool -genkey -alias localhost -keyalg RSA -keysize 2048 -keystore "c:\Program Files\SANscreen\jboss\server\onaro\cert\server.keystore"
What is key is that when you are asked for "What is your first and last name?" you respond with the FQDN you expect to use
After a variety of questions about organization and structure, you will be prompted:
Is CN=localhost, OU=Waltham, O=NetApp, L=Waltham, ST=MA, C=US correct?
[no]
Only type in yes when the Common Name (CN) value is accurately displaying the FQDN
Enter key password for <localhost>
(RETURN if same as keystore password):
keytool -certreq -alias localhost -keystore "c:\Program Files\SANscreen\jboss\server\onaro\cert\server.keystore" -file c:\localhost.csr
The c:\localhost.csr file is the certificate request. Submit it to your CA. Once it is approved, you want the cert returned to you in DER format. This may may or may not be a .der extension. Microsoft CA services defaults to a .cer extension.
keytool -importcert -alias localhost -file c:\localhost2.cer -keystore "c:\Program Files\SANscreen\jboss\server\onaro\cert\server.keystore"
You will be prompted for the keystore password, and you should receive:
Certificate reply was installed in keystore
At this point, if you restart the “SANscreen Server” service, you should find that it is using the CA signed certs. Your web browser should no longer throw certificate errors because the signer of the certs is not trusted
|
https://community.netapp.com/t5/OnCommand-Storage-Management-Software-Discussions/OCI-DWH-and-Cognos-Reporting/td-p/114035
|
CC-MAIN-2018-30
|
en
|
refinedweb
|
I have this working code but my teacher wants really specific things. codes always have to be OOP, and this needs to to have no more then 2 cout. i have 3 but cant seem to find away to take one out. my friend told me i should do this in arrays, but honestly im not really good at this so im really confused about what to do. again sorry if im posting this in the wrong place or posting it in a bad way. thanx u in advance. here is the code,
// DiamondLoop.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string> #include<iostream> using namespace std; class Diamond { private: public: Diamond(){ int i=0, j=0, NUM=3; for(i=-NUM; i<=NUM; i++) { for(j=-NUM; j<=NUM; j++) { if( abs(i)+abs(j)<=NUM) { cout<<"*"; } else { cout<<" ";} } cout <<endl; } } }; int _tmain(int argc, _TCHAR* argv[]) { Diamond shape; return 0; }
|
https://www.daniweb.com/programming/software-development/threads/375520/c-oop-diamond-loop-2-cout-count
|
CC-MAIN-2018-30
|
en
|
refinedweb
|
Akka Notes: Actor Supervision
Akka Notes: Actor Supervision
Join the DZone community and get the full member experience.Join For Free
Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal! top most method in your stack throws an Exception. What could be done by the methods down the stack?
- The exception could be caught and handled in order to recover
- The exception could be caught, may be logged and kept quiet.
- The methods down the stack could also choose to duck the exception completely (or may be caught and rethrown)
Imagine if all the methods until the main method doesn't handle the exception. In that case, the program exits after writing an essay for an exception to the console.
You could also compare the same scenario with spawning Threads. If a child thread throws an exception and if the
run or the
call method doesn't handle it, then the exception is expected to be handled by the parent thread or the main thread, whatever be the case. If the main thread doesn't handle it, then the system exits.
Let's do it one more time - if the Child Actor which was created using the
context.actorOf fails with an Exception, the parent actor (aka supervisor) could prefer to handle any failures of the child actor. If it does, it could prefer to handle it and recover (
Restart/
Resume). Else, duck the exception (
Escalate) to it's parent. Alternatively, it could just
Stop the child actor - that's the end of story for that child. Why did I say parent (aka supervisor)? Simply because Akka's approach towards supervision is Parental supervision - which means that only the creators of the Actors could supervise over them.
That's it !! We have pretty much covered all the supervision
Directives (what could be done about the failures).
STRATEGIES
Ah, I forgot to mention this one : You already know that an Akka Actor could create children and that they could create as many children as they want.
Now, consider two scenarios :
1. OneForOneStrategy
Your Actor spawns multiple child actors and each one of these child actors connect to different datasources. Say you are running an app which translates an english word into multiple languages.
Suppose, one child actor fails and you are fine to skip that result in the final list, what would you want to do? Shut down the service? Nope, you might want to just restart/stop only that child actor. Isn't it? Now that's called
OneForOneStrategy in Akka supervision strategy terms - If one actor goes down, just handle one alone.
Depending on your business exceptions, you would want to react differently (
Stop,
Restart,
Escalate,
Resume) to different exceptions. To configure your own strategy, you just override the
supervisorStrategy in your Actor class.
An example declaration of
OneForOneStrategy would be
import akka.actor.Actor import akka.actor.ActorLogging import akka.actor.OneForOneStrategy import akka.actor.SupervisorStrategy.Stop class TeacherActorOneForOne extends Actor with ActorLogging { ... ... override val supervisorStrategy=OneForOneStrategy() { case _: MinorRecoverableException => Restart case _: Exception => Stop } ... ...
2. AllForOneStrategy
Assume that you are doing an External Sort (One more example to prove that my creativity sucks!!), and each of your chunk is handled by a different Actor. Suddenly, one Actor fails throwing an exception. It doesn't make any sense to continue processing the rest of the chunks because the final result wouldn't be correct. So, it is logical to
Stop ~ALL~ the actors.
Why did I say
Stop instead of
Restart in the previous line? Because
Restarting would also not make any sense for this use-case considering the mailbox for each of these Actors would not be cleared on Restart. So, if we restart, the rest of the chunks would still be processed. That's not what we want. Recreating the Actors with shiny new mailboxes would be the right approach here.
Again, just like the
OneForOneStrategy, you just override the
supervisorStrategy with an implementation of
AllForOneStrategy
And example would be
import akka.actor.{Actor, ActorLogging} import akka.actor.AllForOneStrategy import akka.actor.SupervisorStrategy.Escalate import akka.actor.SupervisorStrategy.Stop class TeacherActorAllForOne extends Actor with ActorLogging { ... override val supervisorStrategy = AllForOneStrategy() { case _: MajorUnRecoverableException => Stop case _: Exception => Escalate } ... ...
DIRECTIVES
The constructor of both
AllForOneStrategy and the
OneForOneStrategy accepts a
PartialFunction[Throwable,Directive] called
Deciderwhich maps a
Throwable to a
Directive as you may see here :
case _: MajorUnRecoverableException => Stop
There are simply just four kinds of directives -
Stop,
Resume,
Escalate and
Restart
Stop
The child actor is stopped in case of exception and any messages to the stopped actor would obviously go to the deadLetters queue.
Resume
The child actor just ignores the message that threw the exception and proceeds with processing the rest of the messages in the queue.
Restart
The child actor is stopped and a brand new actor is initialized. Processing of the rest of the messages in the mailbox continue. The rest of the world is unaware that this happened since the same ActorRef is attached to the new Actor.
Escalate The supervisor ducks the failure and lets its supervisor handle the exception.
DEFAULT STRATEGY
What if our Actor doesn't specify any Strategy but has created child Actors. How are they handled? There is a default strategy declared in the
Actor trait which (if condensed) looks like below :
override val supervisorStrategy=OneForOneStrategy() { case _: ActorInitializationException=> Stop case _: ActorKilledException => Stop case _: DeathPactException => Stop case _: Exception => Restart }
So, in essence, the default strategy handles four cases :
1. ACTORINITIALIZATIONEXCEPTION => STOP
When the Actor could not be initialized, it would throw an
ActorInitializationException. The Actor would be stopped then. Let's simulate it by throwing an exception in the
preStart callback :
package me.rerun.akkanotes.supervision import akka.actor.{ActorSystem, Props} import me.rerun.akkanotes.protocols.TeacherProtocol.QuoteRequest import akka.actor.Actor import akka.actor.ActorLogging object ActorInitializationExceptionApp extends App{ val actorSystem=ActorSystem("ActorInitializationException") val actor=actorSystem.actorOf(Props[ActorInitializationExceptionActor], "initializationExceptionActor") actor!"someMessageThatWillGoToDeadLetter" } class ActorInitializationExceptionActor extends Actor with ActorLogging{ override def preStart={ throw new Exception("Some random exception") } def receive={ case _=> } }
Running the
ActorInitializationExceptionApp would generate a
ActorInitializationException (duh!!) and then move all the messages into the message queue of the
deadLetters Actor:
Log
[ERROR] [11/10/2014 16:08:46.569] [ActorInitializationException-akka.actor.default-dispatcher-2] [akka://ActorInitializationException/user/initializationExceptionActor] Some random exception akka.actor.ActorInitializationException: exception during creation at akka.actor.ActorInitializationException$.apply(Actor.scala:164) ... ... Caused by: java.lang.Exception: Some random exception at me.rerun.akkanotes.supervision.ActorInitializationExceptionActor.preStart(ActorInitializationExceptionApp.scala:17) ... ... [INFO] [11/10/2014 16:08:46.581] [ActorInitializationException-akka.actor.default-dispatcher-4] [akka://ActorInitializationException/user/initializationExceptionActor] Message [java.lang.String] from Actor[akka://ActorInitializationException/deadLetters] to Actor[akka://ActorInitializationException/user/initializationExceptionActor#-1290470495] was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
2. ACTORKILLEDEXCEPTION => STOP
When the Actor was killed using the
Kill message, then it would throw an
ActorKilledException. The default strategy would stop the child Actor if it throws the exception. At first, it seems that there's no point in stopping an already killed Actor. However, consider this :
ActorKilledExceptionwould just be propagated to the supervisor. What about the lifecycle watchers or deathwatchers of this Actor that we saw during DeathWatch. The watchers won't know anything until the Actor is
Stopped.
Sending a
Killon an Actor would just affect that particular actor which the supervisor knows. However, handling that with
Stopwould suspend the mailbox of that Actor, suspends the mailboxes of child actors, stops the child actors, sends a
Terminatedto all the child actor watchers, send a
Terminatedto all the immediate failed Actor's watchers and finally stop the Actor itself. (Wow, that's pretty awesome !!)
package me.rerun.akkanotes.supervision import akka.actor.{ActorSystem, Props} import me.rerun.akkanotes.protocols.TeacherProtocol.QuoteRequest import akka.actor.Actor import akka.actor.ActorLogging import akka.actor.Kill object ActorKilledExceptionApp extends App{ val actorSystem=ActorSystem("ActorKilledExceptionSystem") val actor=actorSystem.actorOf(Props[ActorKilledExceptionActor]) actor!"something" actor!Kill actor!"something else that falls into dead letter queue" } class ActorKilledExceptionActor extends Actor with ActorLogging{ def receive={ case message:String=> log.info (message) } }
Log
The logs just say that once the
ActorKilledException comes in, the supervisor stops that actor and then the messages go into the queue of
deadLetters
INFO m.r.a.s.ActorKilledExceptionActor - something ERROR akka.actor.OneForOneStrategy - Kill akka.actor.ActorKilledException: Kill INFO akka.actor.RepointableActorRef - Message [java.lang.String] from Actor[akka://ActorKilledExceptionSystem/deadLetters] to Actor[akka://ActorKilledExceptionSystem/user/$a#-1569063462] was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
3. DEATHPACTEXCEPTION => STOP
From DeathWatch, you know that when an Actor watches over a child Actor, it is expected to handle the
Terminated message in its
receive. What if it doesn't? You get the
DeathPactException
The code shows that the Supervisor
watches the child actor after creation but doesn't handle the
Terminated message from the child.
package me.rerun.akkanotes.supervision import akka.actor.{ActorSystem, Props} import me.rerun.akkanotes.protocols.TeacherProtocol.QuoteRequest import akka.actor.Actor import akka.actor.ActorLogging import akka.actor.Kill import akka.actor.PoisonPill import akka.actor.Terminated object DeathPactExceptionApp extends App{ val actorSystem=ActorSystem("DeathPactExceptionSystem") val actor=actorSystem.actorOf(Props[DeathPactExceptionParentActor]) actor!"create_child" //Throws DeathPactException Thread.sleep(2000) //Wait until Stopped actor!"someMessage" //Message goes to DeadLetters } class DeathPactExceptionParentActor extends Actor with ActorLogging{ def receive={ case "create_child"=> { log.info ("creating child") val child=context.actorOf(Props[DeathPactExceptionChildActor]) context.watch(child) //Watches but doesnt handle terminated message. Throwing DeathPactException here. child!"stop" } case "someMessage" => log.info ("some message") //Doesnt handle terminated message //case Terminated(_) => } } class DeathPactExceptionChildActor extends Actor with ActorLogging{ def receive={ case "stop"=> { log.info ("Actor going to stop and announce that it's terminated") self!PoisonPill } } }
Log
The logs tell us that the
DeathPactException comes in, the supervisor stops that actor and then the messages go into the queue of
deadLetters
INFO m.r.a.s.DeathPactExceptionParentActor - creating child INFO m.r.a.s.DeathPactExceptionChildActor - Actor going to stop and announce that it's terminated ERROR akka.actor.OneForOneStrategy - Monitored actor [Actor[akka://DeathPactExceptionSystem/user/$a/$a#-695506341]] terminated akka.actor.DeathPactException: Monitored actor [Actor[akka://DeathPactExceptionSystem/user/$a/$a#-695506341]] terminated INFO akka.actor.RepointableActorRef - Message [java.lang.String] from Actor[akka://DeathPactExceptionSystem/deadLetters] to Actor[akka://DeathPactExceptionSystem/user/$a#-1452955980] was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.
4. EXCEPTION => RESTART
For all other Exceptions, the default
Directive is to
Restart the Actor. Check the following app. Just to prove that the Actor is restarted,
OtherExceptionParentActor makes the child throw an exception and immediately sends a message. The message reaches the mailbox and when the the child actor restarts, the message gets processed. Nice !!
package me.rerun.akkanotes.supervision import akka.actor.Actor import akka.actor.ActorLogging import akka.actor.ActorSystem import akka.actor.OneForOneStrategy import akka.actor.Props import akka.actor.SupervisorStrategy.Stop object OtherExceptionApp extends App{ val actorSystem=ActorSystem("OtherExceptionSystem") val actor=actorSystem.actorOf(Props[OtherExceptionParentActor]) actor!"create_child" } class OtherExceptionParentActor extends Actor with ActorLogging{ def receive={ case "create_child"=> { log.info ("creating child") val child=context.actorOf(Props[OtherExceptionChildActor]) child!"throwSomeException" child!"someMessage" } } } class OtherExceptionChildActor extends akka.actor.Actor with ActorLogging{ override def preStart={ log.info ("Starting Child Actor") } def receive={ case "throwSomeException"=> { throw new Exception ("I'm getting thrown for no reason") } case "someMessage" => log.info ("Restarted and printing some Message") } override def postStop={ log.info ("Stopping Child Actor") } }
Log
The logs of this program is pretty neat.
- The exception gets thrown. We see the trace
- The child restarts - Stop and Start gets called (we'll see about the
preRestartand
postRestartcallbacks soon)
- The message that was send to the Child actor before restart is processed.
INFO m.r.a.s.OtherExceptionParentActor - creating child INFO m.r.a.s.OtherExceptionChildActor - Starting Child Actor ERROR akka.actor.OneForOneStrategy - I'm getting thrown for no reason java.lang.Exception: I'm getting thrown for no reason at me.rerun.akkanotes.supervision.OtherExceptionChildActor$anonfun$receive$2.applyOrElse(OtherExceptionApp.scala:39) ~[classes/:na] at akka.actor.Actor$class.aroundReceive(Actor.scala:465) ~[akka-actor_2.11-2.3.4.jar:na] ... ... INFO m.r.a.s.OtherExceptionChildActor - Stopping Child Actor INFO m.r.a.s.OtherExceptionChildActor - Starting Child Actor INFO m.r.a.s.OtherExceptionChildActor - Restarted and printing some Message
ESCALATE AND RESUME
We saw examples of
Stop and
Restart via the
defaultStrategy. Now, let's have a quick look at the
Escalate.
Resume just ignores the exception and proceeds processing the next message in the mailbox. It's more like catching the exception and doing nothing about it. Awesome stuff but not a lot to talk about there.
Escalating generally means that the exception is something critical and the immediate supervisor would not be able to handle it. So, it asks help from it's supervisor. Let's take an example.
Consider three Actors -
EscalateExceptionTopLevelActor,
EscalateExceptionParentActor and
EscalateExceptionChildActor. If the child actor throws an exception and if the parent level actor could not handle it, it could
Escalate it to the Top level Actor. The Top level actor could choose to react with any of the Directives. In our example, we just
Stop.
Stop would stop the immediate child (which is the
EscalateExceptionParentActor). As you know, when a
Stop is executed on an Actor, all its children would also be stopped before the Actor itself is stopped.
package me.rerun.akkanotes.supervision import akka.actor.Actor import akka.actor.ActorLogging import akka.actor.ActorSystem import akka.actor.OneForOneStrategy import akka.actor.Props import akka.actor.SupervisorStrategy.Escalate import akka.actor.SupervisorStrategy.Stop import akka.actor.actorRef2Scala object EscalateExceptionApp extends App { val actorSystem = ActorSystem("EscalateExceptionSystem") val actor = actorSystem.actorOf(Props[EscalateExceptionTopLevelActor], "topLevelActor") actor ! "create_parent" } class EscalateExceptionTopLevelActor extends Actor with ActorLogging { override val supervisorStrategy = OneForOneStrategy() { case _: Exception => { log.info("The exception from the Child is now handled by the Top level Actor. Stopping Parent Actor and its children.") Stop //Stop will stop the Actor that threw this Exception and all its children } } def receive = { case "create_parent" => { log.info("creating parent") val parent = context.actorOf(Props[EscalateExceptionParentActor], "parentActor") parent ! "create_child" //Sending message to next level } } } class EscalateExceptionParentActor extends Actor with ActorLogging { override def preStart={ log.info ("Parent Actor started") } override val supervisorStrategy = OneForOneStrategy() { case _: Exception => { log.info("The exception is ducked by the Parent Actor. Escalating to TopLevel Actor") Escalate } } def receive = { case "create_child" => { log.info("creating child") val child = context.actorOf(Props[EscalateExceptionChildActor], "childActor") child ! "throwSomeException" } } override def postStop = { log.info("Stopping parent Actor") } } class EscalateExceptionChildActor extends akka.actor.Actor with ActorLogging { override def preStart={ log.info ("Child Actor started") } def receive = { case "throwSomeException" => { throw new Exception("I'm getting thrown for no reason.") } } override def postStop = { log.info("Stopping child Actor") } }
Log
As you could see from the logs,
- The child actor throws exception.
- The immediate supervisor (
EscalateExceptionParentActor) escalates that exception to its supervisor (
EscalateExceptionTopLevelActor)
- The resultant directive from
EscalateExceptionTopLevelActoris to Stop the Actor. As a sequence, the child actors gets stopped first.
- The parent actor gets stopped next (only after the watchers have been notified)
INFO m.r.a.s.EscalateExceptionTopLevelActor - creating parent INFO m.r.a.s.EscalateExceptionParentActor - Parent Actor started INFO m.r.a.s.EscalateExceptionParentActor - creating child INFO m.r.a.s.EscalateExceptionChildActor - Child Actor started INFO m.r.a.s.EscalateExceptionParentActor - The exception is ducked by the Parent Actor. Escalating to TopLevel Actor INFO m.r.a.s.EscalateExceptionTopLevelActor - The exception from the Child is now handled by the Top level Actor. Stopping Parent Actor and its children. ERROR akka.actor.OneForOneStrategy - I'm getting thrown for no reason. java.lang.Exception: I'm getting thrown for no reason. at me.rerun.akkanotes.supervision.EscalateExceptionChildActor$$anonfun$receive$3.applyOrElse(EscalateExceptionApp.scala:71) ~[classes/:na] ... ... INFO m.r.a.s.EscalateExceptionChildActor - Stopping child Actor INFO m.r.a.s.EscalateExceptionParentActor - Stopping parent Actor
Please note that whatever directive that was issued would only apply to the immediate child that escalated. Say, if a
Restart is issued at the TopLevel, only the Parent would be restarted and anything in its constructor/
preStart would be executed. If the children of the Parent actor was created in the constructor, they would also be created. However, children that were created through messages to the Parent Actor would still be in the
Terminated state.
TRIVIA
Actually, you could control whether the
preStart gets called at all. We'll see about this in the next minor write-up. If you are curious, just have a look at the
postRestart method of the Actor
def postRestart(reason: Throwable): Unit = { preStart() }
CODE
As always, code is on github
(my
.gitignore wasn't setup right for this project. will fix it today. sorry) }}
|
https://dzone.com/articles/akka-notes-actor-supervision
|
CC-MAIN-2018-30
|
en
|
refinedweb
|
The theory
When you say:
from foo.bar import baz
Python will start by looking for a module named foo, and then inside that a module named bar, and then inside that for an object named baz (which may be a regular python object, or another module)
A module is defined as:
either a Python file
- ie a file on disk that ends in .py and contains valid Python (syntax errors, for example, will stop you from being able to import a file)
or a folder which contains Python files.
- for a folder to become a module, it must contain a special file called
__init__.py
When a module is actually a folder, the things you can import from it are:
- any other modules that are inside the folder (ie, more .py files and folders)
- any objects defined or imported inside the
__init__.pyof the folder
Finally, where does Python look for modules? It looks in each directory specified in the special "sys.path" variable. Typically (but not always), sys.path contains some default folders, including the current working directory, and the standard "packages" directory for that system, usually called site-packages, which is where pip installs stuff to.
So
from foo.bar import baz could work in a few different ways:
. `-- foo/ |-- __init__.py `-- bar.py <-- contains a variable called "baz"
Or
. `-- foo/ |-- __init__.py `-- bar/ |-- __init__.py `-- baz.py
Or:
. `-- foo/ |-- __init__.py `-- bar/ `-- __init__.py <-- contains a variable called "baz"
What this means is that you need to get a few things right for an import to work:
- The dot-notation has to work: from foo.bar import baz means foo has to be a module folder, and bar can either be a folder or a file, as long as it somehow contains a thing called baz. Spelling mistakes, including capitalization, matter
- The top-level "foo" must be inside a folder that's on your sys.path.
- If you have multiple modules called "foo" on your sys.path, that will probably lead to confusion. Python will just pick the first one.
Debugging sys.path issues in web apps
can you run the wsgi file itself?
$ python3.6 -i /var/www/www_my_domain_com_wsgi.py
Or, if you're using python 2:
$ python2.7 -i /var/www/www_my_domain_com_wsgi.py
Or, if you're using a virtualenv, activate it first:
$ workon my-virtualenv (my-virtualenv)$ python -i /var/www/www_my_domain_com_wsgi.py
If this shows any errors and won't even load python (eg syntax errors), you'll need to fix them.
If it loads OK, it will drop you into a Python shell. Try doing the import manually at the command line. Then, check whether they really are coming from where you think they are:
from foo.bar import baz import foo print(foo) # this should show the path to the module. Is it what you expect? import sys print('\n'.join(sys.path)) # does this show the files and folders you need?
Django-specific issues.
eg:
path = "/home/myusername/myproject" if path not in sys.path: sys.path.append(path) os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings"
What this implies is that you have a directory tree that looks like this:
/home/myusername `-- myproject/ |-- __init__.py `-- myproject/ |-- __init__.py `-- settings.py
NB - this is the typical django project structure for django versions greater than 1.4. You will probably need to use a virtualenv to get this to work, see VirtualenvForNewerDjango
If in doubt, try the
python -i /var/www/www_my_domain_com_wsgi.py >>> import myproject.settings # this should work. if this doesn't, figure out why. print sys.path, etc.
Other tips
Can you run the files it's trying to import?
eg, if your wsgi file does
from myapp import settings, can you run:
python /path/to/myapp/settings.py
?
Shadowing
Could there be any sort of "shadowing" going on? do any of your modules have the same name as system modules? eg, if you're trying to do
from package import thing
What happens if you open up a console and type
import package print(package)
does it give you the path to your package, or to a system package? if the latter, it's best to rename your own module to avoid the conflict.
Check virtualenv Python versions
If you're using a virtualenv, just double-check that the Python version of your virtualenv is the same as the one on the web tab.
- you can check the virtualenv version with
python --version(remember to activate your virtualenv fist with
workon my-virtualenv-namefirst)
- you can check the webapp python version on the Web tab, it's indicated near the top.
|
https://help.pythonanywhere.com/pages/DebuggingImportError
|
CC-MAIN-2018-30
|
en
|
refinedweb
|
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
This seems like something I should be able to supplement within the configuration of Script Runner's clone issue template. I'm sure if I had the correct code to execute as an additional issue function, I could implement it. I'm just not knowledgable to come up with it myself, yet. Any help from those smarter than myself is greatly appreciated!
Have a look at. You would iterate the comments on the source issue, and create corresponding comments on the target issue.
Jamie,
I tried this approach with the following script in the post function:
import com.atlassian.jira.issue.comments.CommentManager
import com.atlassian.jira.issue.comments.Comment
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.component.ComponentAccessor
CommentManager commentMgr = ComponentAccessor.getCommentManager();
Collection<Comment> comments = commentMgr.getComments(sourceIssue);
for (Comment comment : comments) {
commentMgr.create(issue, comment.getAuthorApplicationUser(), comment.getBody(), false);
}
But I always got
[scriptrunner.jira.workflow.ScriptWorkflowFunction] Script function failed on issue: ..., file: null
java.lang.NullPointerException
at com.atlassian.jira.issue.comments.DefaultCommentManager.create(DefaultCommentManager.java:258)
Any advice on this?
Thanks
hung.
|
https://community.atlassian.com/t5/Jira-questions/Can-I-use-Script-Runner-s-Clone-Issue-to-copy-comments/qaq-p/455003
|
CC-MAIN-2018-30
|
en
|
refinedweb
|
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
On Fri, Jun 2, 2017 at 1:40 PM, Florian Weimer <fweimer@redhat.com> wrote: > On 06/02/2017 10:19 PM, H.J. Lu wrote: >> On Fri, Jun 2, 2017 at 6:49 AM, Florian Weimer <fweimer@redhat.com> wrote: >>> On 05/18/2017 10:05 PM, Siddhesh Poyarekar wrote: >>>> Why not just have a tst-resolv-res_init.c and >>>> tst-resolv-res_init-thread.c? That's how a lot of the other similar >>>> kinds of tests are rewritten. I don't have a very strong opinion on >>>> this though, you can choose the color of your shed :) >>> >>> I do it this way so that I can use #if instead of #ifdef, following the >>> current guidelines to trigger -Wundef warnings on typos. >>> >>> I'm going to push this without the tests expecting incorrect results. >>> >> >> On Fedora 25/x86-64, I got >> >> [hjl@gnu-6 build-x86_64-linux]$ cat resolv/tst-resolv-res_init.out >> Timed out: killed the child process >> [hjl@gnu-6 build-x86_64-linux]$ cat resolv/tst-resolv-res_init-thread.out >> Timed out: killed the child process >> [hjl@gnu-6 build-x86_64-linux]$ > > I see that too, with 4.11.3-200.fc25.x86_64. What's your kernel version? > > I don't see the delay with 4.10.17-100.fc24.x86_64. There, the poll > system calls return immediately. I wonder if it's some sort of > regression in network namespaces. Yes, I am also running 4.11.3-200.fc25.x86_64. -- H.J.
|
http://sourceware.org/ml/libc-alpha/2017-06/msg00127.html
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
My experience unit testing Premiere
I recently posted about Premiere, a Javascript library I've published to facilitate consuming RESTful APIs and one of my goals to make this library reliable was to achieve 100% test coverage or at least close to that.
To do so, my first choice was to choose the how to do it; so I started reading about the popular Mocha/Chai/Sinon + Istanbul for test coverage. Although I got to setup the basic testing environment and script, my experience was very painful; using Typescript made testing even more difficult than it should be.
If you are used to Karma, Jasmine, Mocha/Chai/Sinon and happy with them, that’s good too. This post is about the experience I've had so far with these technologies.
After a lot of hustle, time spent, and packages imported, the test
watcher and
coverage were still not working for me. To do simple tests I had to import stuff in my code from many libraries, some from
chai, some other from
sinon, others from
sinon-chai and it all looked very difficult and confusing; plus, I was working with Typescript and needed all the typings. By the end I was very frustrated it all turned out to deviate me from the main focus, which was to write tests, not to do configurations.
Doing some research I found out about Jest, a testing framework created and used by Facebook. At first I thought it was designed to be used with React projects only, but going through the Jest Homepage I started to notice how powerful and easy to setup it was. Even better, there is a nice package for handling Typescript without a sweat.
Setting up Jest was easy like a breeze, it has a nice watcher and the test coverage works out of the box. The whole flow felt very smooth, having everything in on place made it a lot easier, the well documented api was very helpful too.
Once everything was in place, it was just a matter of going through each functionality and making sure everything was covered to get the so desired 100% coverage ❤. The basic functions,
describe,
it and
expect were enough in most of the cases and the support to
Promise took care of the rest. To help isolating each test, creating mocks with
jest.fn() also was of great help.
Let's see some code, so this doesn't sound so much as free marketing for Facebook. The following code is written in Typescript and refers to Premiere's Cache class.
To get started, let's import the main class. I followed the pattern of placing the
.spec.ts in the same folder as the "original" file.
import Cache from './Cache';
Now let's set our
describe block and prepare some variables for our tests, so we make our lives easier. Notice that we're using variables with type
any, so we don't need to import more stuff other than Cache, with the goal of trying to make our
spec more isolated.
describe('Cache', () => {
let cache: Cache;
let model: any;
let list: any[];
let promise: any = 'promise instance';
Now, before each test we'll initialize our variables.
beforeEach(() => {
cache = new Cache(null);
model = {key: jest.fn().mockReturnValue('id')};
list = [model];
});
To get a hold of how it works, let's look at a couple tests.
it('should set api on construct', () => {
cache = new Cache('api' as any);
expect(cache.api).toBe('api');
});
it('should resolve key from object', () => {
expect(Cache.resolveKey(model)).toBe('id');
});
it('should set list', () => {
cache.setList('list', list);
expect(cache.lists['list']).toBe(list);
});
If you wish to see the entire file, please refer to
The configuration
The Jest configuration is dead simple. Just added these parts to package.json.
Scripts:
“test”: “jest — coverage — no-cache ${1}”,
“test-watch”: “jest ${1} — watch”,
Dev Dependencies:
"@types/jest": "^16.0.2",
"jest": "^18.0.0",
"ts-jest": "^18.0.0",
And finally the "jest" block.
This part is only necessary because the project uses Typescript. Don't get scared, this is mostly boilerplate that are nicely documented by ts-jest.
"jest": {
"moduleFileExtensions": [
"ts",
"js"
],
"transform": {
"\\.(ts)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "lib/.*\\.spec.(ts|js)$",
"testResultsProcessor": "<rootDir>/node_modules/ts-jest/coverageprocessor.js",
"globals": {
"__TS_CONFIG__": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node"
}
}
}
The full package.json is available at
So if you have a chance, with or without, give Jest a try, you may surprise yourself. It’s very nice to feel that things “just work” \o/
I hope you enjoy :)
|
https://hackernoon.com/from-0-to-100-coverage-real-quick-d71dda7069e5
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
prompter_bp 0.0.1
This is a test from Stephen Grinder's Udemy class
example/main.dart
import 'package:prompter_bp/prompter_b_b_bp/prompter_bp.dart';
We analyzed this package on Jan 17, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
- Dart: 2.7.0
- pana: 0.13.2
Health issues and suggestions
Document public APIs. (-1 points)
11 out of 11 13 col 3: The method askMultiple should have a return type but doesn't.
Format
lib/prompter_bp.dart.
Run
dartfmt to format
lib/prompter_b. (-9.04 points)
The package was last published 56 weeks ago.
|
https://pub.dev/packages/prompter_bp
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
tag:blogger.com,1999:blog-8712770457197348465.post3186178078647488509..comments2020-01-17T10:12:24.230-08:00Comments on Javarevisited: How to Find Middle Element of Linked List in Java in Single Passjavin paul problem.solving.linkedlist.practise; publ...package problem.solving.linkedlist.practise;<br /><br />public class FindMiddleElement{<br /> <br /> private Node head;<br /> private Node tail;<br /> private int size = 0;<br /> <br /> private class Node{<br /> <br /> T data;<br /> Node next;<br /> <br /> public Node(T data, Node next){<br /> this.data = data;<br /> this.next = next;<br /> }<br /> }<br /> <br /> public int size() {<br Unknown @Anonymous, yes, the fast and slow pointer a...Hello @Anonymous, yes, the fast and slow pointer approach should also work but just check with list with even and odd length, may require bit consideration. javin paul another way of solving this would be using...Perhaps another way of solving this would be using Floyd's slow and fast pointer's concept. Increment the fast pointer by two at each incremental stage until the next of it is not null and increment the slow pointer by one and you shall find the middle element.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-43972133837000994512019-06-04T10:08:27.652-07:002019-06-04T10:08:27.652-07:00Easiest way to find the middle element. way to find the middle element.<br /> middleNode(list_t *head, int *val){ i...void middleNode(list_t *head, int *val){<br /> if (!head)<br /> return;<br /> list_t *slow, *fast;<br /> slow=fast=head;<br /><br /> while(fast&&fast->next){<br /> slow=slow->next;<br /> fast=fast->next->next;<br /> }<br /> *val = slow->data;<br />}<br />I am just returning the value of Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-41456132417768272322018-12-15T23:21:56.288-08:002018-12-15T23:21:56.288-08:00Sorry Guys why cant we use this public class Fin...Sorry Guys why cant we use this <br /><br />public class FindMiddleInList {<br /><br /> public static void main(String[] args) {<br /> // TODO Auto-generated method stub<br /><br /> LinkedList list=new LinkedList<>();<br /> IntStream.range(1,11).forEach(i->list.add(i));<br /> <br /> System.out.println(list.get(list.size()/2));<br /> }<br /><br />}<br />Mohit without extra head, Will it return correct leng...Or without extra head, Will it return correct length?Alok Mrityunjay Paul, Why there is extra head when we can c...@Javin Paul, Why there is extra head when we can consider "1" as head?<br />In that case, while loop would look like "while(current != null)" instead of "while(current.next() != null)".Alok Mrityunjay J B public class Middle_Node_Linked_...//Shashikumar J B<br />public class Middle_Node_Linked_List {<br /><br /> public static void main(String[] args) {<br /><br /> LinkedList Checking = new LinkedList<>();<br /><br /> int[] sample = {40, 20, 60, 10, 50, 30};<br /> //int[] sample = {40, 20, 60};<br /> //int[] sample = {40};<br /> for (int i = 0; i < sample.length; i++) {<br />Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-72534523749899636242017-02-04T00:51:28.462-08:002017-02-04T00:51:28.462-08:00I am bit puzzled about this problem and solution. ...I am bit puzzled about this problem and solution. Why did you create your own implementation of LinkedList? I would assume that the question was about java.util.LinkedList. If memory is not an issue than creating an Array from LinkedList would be one pass and much simpler. Yasin Hamid many have pointed out as this answer is looks n...As many have pointed out as this answer is looks not correct. I am agreeing with them.<br />Please change the title of the quesion @Author, @Javin Paul.<br />Its not one pass it is 1.5 passAslam Anwer about ArrayList ? if you add all nodes to Arr...what about ArrayList ? if you add all nodes to ArrayList while traversing you solve indexed search and any search question if there is no cycle there . right ?<br /><br />p.s.: why can't I comment using facebook ?Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-20561752972339849442016-10-03T00:29:57.151-07:002016-10-03T00:29:57.151-07:00Guys let me know if i am wrong but i think followi...Guys let me know if i am wrong but i think following code will give us what we want(assuming the list is even)??.<br /><br />int p = 0;<br /> LinkedList l = new LinkedList();<br /> l.add(0);<br /> l.add(1);<br /> l.add(2);<br /> l.add(3);<br /> l.add(4);<br /> l.add(5);<br /> l.add(6);<br /> <br /> p =(l.indexOf(l.getLast()))/2 ;<br /> <br /> System.out.println(l.get(p));Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-88259892240178080502016-07-14T14:41:18.961-07:002016-07-14T14:41:18.961-07:00I wrote this function to find the middle element. ...I wrote this function to find the middle element. I am getting the results:<br />public void middleElement(){<br /> int length = 0;<br /> Node middle = head;<br /> Node current = head;<br /> while(current.next!=null){<br /> length++;<br /> if(length%2==0){<br /> middle = middle.next;<br /> }<br /> current = current.next;<br /> if(length%2 == 1){<br /> current = current.next;<Akanksha Jain, you may be right. I guess the pass initia...@Joshua, you may be right. I guess the pass initially refer to how many loop you use to find the middle element of linked list, but you are right, it's not the correct word. A pass can also means accessing the linked list twice. Javin Paul have to be honest.... this is a nice solution an...I have to be honest.... this is a nice solution and all but...the real answer is there is no way of completing this with a single pass. Two pointers means you are making two passes. This is the same for all of the implementations I have seen. I think others have echoed the same sentimate and I realize that at some point this could come down to a wording issue. This is not a slight against the Joshua Frost, Thanks for your code, but I think I suggeste...@Huy, Thanks for your code, but I think I suggested to write JUnit tests for your code to verify if the solution works for a linked list with even number of elements and a list with odd number of elements e.g. linked list with 5 elements.<br /><br />nevermind, good practice anyway.Javin Paul jarvin, here's your request. find odd and e...Hi jarvin, here's your request. find odd and even numbers in the list<br /><br />class Numbers {<br /> int N;<br /> Numbers (int R) { N = R;}<br /> public String toString() { return "" + N; }<br /> int getValue() { return N; }<br />}<br /><br />public class FindMiddle {<br /> public static void main(String[] args) {<br /><br />LinkedList Z= new LinkedList<>();Z.add(new NumbersHuy Le** *Find below code for finding the middle elemen.../**<br />*Find below code for finding the middle element by two pointer method<br />*/<br /><br />Node nod1 = list;<br /> Node nod2 = list;<br /> while (nod2.next != null) {<br /> if (nod2.next != null)<br /> nod2 = nod2.next;<br /> else<br /> nod1 = nod1.next;<br /> if (nod2.next != null)<br /> nod2 = nod2.next;<br /> else<br /> nod1 = nod1.next;<br /> }<br /> Unknown, good solution, try writing some JUnit tests ...@Huy, good solution, try writing some JUnit tests as well to see if your program works on boundary conditions e.g. linked list with even number of elements, odd number of elements etc.Javin Paul, my first Java. How to find middle element of L...Hi, my first Java. How to find middle element of LinkedList in one pass.<br />Iterator iterates through the LinkedList always starts at Z.size()/2. The "count" speaks it all. <br /><br />class Numbers {<br /> int N;<br /> Numbers (int R) { N = R;}<br /> public String toString() { return "" + N; }<br />}<br /><br />public class FindMiddle {<br /> public static void main(String[Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-4520383313973689772015-11-22T20:43:42.598-08:002015-11-22T20:43:42.598-08:00// Below there is only one pass, using one ListIte...// Below there is only one pass, using one ListIterator from head, one desendingIterator from tail<br />public static String findMid2(LinkedList list) {<br /> ListIterator iter1 = list.listIterator(0);<br /> Iterator iter2 = list.descendingIterator();<br /> String fromHead = null;<br /> String fromTail = null;<br /> while (iter1.hasNext()) {<br /> fromHead = iter1.next();<br /> if (AT I assume we can remove first and remove last el...// I assume we can remove first and remove last element in a loop<br />public static String findMidNodeInLinkedList(final LinkedList list) {<br /> String mid = null;<br /> while (list.peekFirst() != null) {<br /> mid = list.removeFirst();<br /> if (list.peekLast() == null) {<br /> return mid;<br /> } <br /> list.removeLast();<br /> }<br /> return mid;<br /> } AT static void main(String[] args) { // TODO... public static void main(String[] args) {<br /> // TODO Auto-generated method stub<br /> LinkedList linked = new LinkedList();<br /> Scanner scn = new Scanner(System.in);<br /> System.out.println("How many numbers you want to add");<br /> int n = scn.nextInt();<br /> System.out.println("Start the element to enter in list");<br /> for(int c= 0 ; c <n ; c++ ){<br />Abhishek singh, linked list doesn't allow random acces...@pavan, linked list doesn't allow random access. You can cannot get element by calling get(index). This is true for our own linked list implementation and also for java.util.LinkedList, which is a doubly linked list. Javin Paul
|
https://javarevisited.blogspot.com/feeds/3186178078647488509/comments/default
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
IPermission.
Copy Method
Definition
Creates and returns an identical copy of the current permission.
public: System::Security::IPermission ^ Copy();
public System.Security.IPermission Copy ();
abstract member Copy : unit -> System.Security.IPermission
Public Function Copy () As IPermission
Returns
A copy of the current permission.
Examples
The following code example demonstrates implementing the Copy method. This code example is part of a larger example provided for the IPermission class.
// Return a new object that matches 'this' object's permissions. public: virtual IPermission^ Copy () override sealed { return (IPermission^) Clone(); }
// Return a new object that matches 'this' object's permissions. public sealed override IPermission Copy() { return (IPermission)Clone(); }
' Return a new object that matches 'this' object's permissions. Public Overrides Function Copy() As IPermission Return CType(Clone(), IPermission) End Function 'Copy
Remarks
A copy of a permission represents the same access to resources as the original permission.
|
https://docs.microsoft.com/en-us/dotnet/api/system.security.ipermission.copy?view=netframework-4.8
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
A free and open dialogue is critical to the success of any civilisation. History shows that whenever free speech is oppressed, tyranny ensues.
A free and open dialogue is critical to the success of any civilisation. History shows that whenever free speech is oppressed, tyranny ensues.
I have just received another 30 day ban from FaceBook for sharing an image of the Hindu symbol for peace and unity, because either somebody flagged it or perhaps their algorithms mistakenly identified it as a Swastika, which is illegal in some countries.
Either way, the oppression of expression is the first step toward tyranny. We should all be wary of any attempts to suppress opinion, no matter how inane or offensive they may seem to some. The marketplace of ideas relies on this; good ideas will be encouraged and built upon, while bad ideas will eventually die out through a cultural form of natural selection.
Only those with invested interests seek to silence others who disagree with them. The truth will always emerge if open dialogue is allowed.. slow is that a bucket is only located in one geographical location. The location is selected when you create the bucket. For example, if your bucket is created on Amazon servers in California, but your users are in India, then images will still be served from California. This geographical distance causes slow image loading on your website.
Further, it is not uncommon to see very heavy images on S3, with large dimensions and high byte size. One can only speculate on the reasons, but it is probably related to the publication workflow and the convenience of S3 as a storage space.
Let’s see how we can accelerate image delivery while keeping S3’s workflow and convenience level.Speeding Up Image Delivery on S3
To catch the two flies of global distribution and image optimization at once, let's see how an image CDN like ImageEngine can leverage S3 as an origin.
Step1: Create the S3 bucket
Once logged in to the Amazon console it is easy to create the bucket and store content in it. By default buckets are private. In order for the Image CDN to reach the origin image, we must create a bucket policy to make the contents of the bucket available on the web.
Once you’ve implemented the policy that fits your needs, the bucket should be available in your browser using this scheme for a hostname:
https://<bucket>.s3.amazonaws.com/<file>
Alternatively:-<location>.amazonaws.com/<bucket>/<file>
For example:
Or
Step 2: Sign up for an ImageEngine account.
ImageEngine offers free trial accounts with no strings attached. The signup process will ask for a nickname for the account, a domain name intended for serving images, and an origin location.
Give the account a name you like and provide a domain name you think you’ll be using to serve images on your web site. This can, of course, be changed later. In our case, we choose “s3img.mydomain.com”.
The origin is the S3 bucket we created in step 1. There are two ways to configure the S3 bucket. You can use the S3 protocol or HTTP.
If you want to use the S3 protocol, check the S3 radio button and type the name of the bucket.
If you want to use HTTP, then select the HTTP radio button and type in the fully qualified hostname. Note that if you want HTTPS, you’ll need to use the notation with the bucket name in the path: s3-.amazonaws.com. Submit the hostname for now, and you can edit the origin later and add the bucket name.
On the question “Allow origin prefixing” it is safe to answer “No” for now. Hit submit and the account is created.
Step 3: Configure your DNS
This step is not strictly necessary, but if you want to serve images from the domain name provided in step1 you’ll need to add a CNAME record in the DNS. The DNS info needed is presented to you when submitting the form in step 2.
Record Name: s3img.mydomain.com Record Type: CNAME Record Value: s3img.mydomain.com.imgeng.in
Note that the Record Value can also be used to access images on S3:
Step 4: tune settings
In less than 5 minutes, the S3 bucket is configured, the ImageEngine account is created and ImageEngine is serving optimized images from S3. You can also log in to the ImageEngine dashboard to manage multiple domain names and origins. Also in the dashboard you can tune the default behaviour of ImageEngine. For example tune the image quality, size, formats and so on.ImageEngine Makes Amazon S3 Faster
By these simple steps, images stored on Amazon S3 are now globally distributed and optimized by ImageEngine. If you want more information about the optimization process and the resulting next-gen file formats, then you can read about them here.
To analyse the impact of ImageEngine we took a representative sample of the sites in the HTTParchive data set which store images on S3 and ran them through the ImageEngine demo tool, comparing original and optimized web site performance.
Looking at the optimization aspect isolated, the savings in bytes are dramatic! The average byte size of an original image stored on Amazon S3 is 2.9MB, while the average optimized by ImageEngine is only 0.6MB. 78% less data! The dramatic savings suggest that a typical workflow involves storing images on Amazon S3 does not include any particular steps to reduce the file size before it is stored on S3.
The primary benefit is faster page loading for better user experience. Fewer data delivered also saves the end-users data plan as well as battery life because lighter images require less processing power to decode and display. Additionally, images will be displayed on the screen sooner freeing processing power to other tasks.
Fewer data to transmit over the wire also has a direct impact on the time it takes to display the page in the user’s browser. We’ve looked at the visual complete time; the time it takes for the page to be completely rendered visually in the browser.
On average, the sample using ImageEngine is visually complete 3.4 seconds earlier than then sites with unoptimized images. 3.4 seconds is a huge improvement. Knowing that 53% of users leave the site if it takes more than 3 seconds to load,3.4 seconds improvement just by enabling ImageEngine is a giant leap towards the 3-second goal. Additionally, now that images are served from a CDN, not from a static S3 location, we get the advantage of global distribution and reduced latency.
This is also why addressing images to improve performance, conversion rates and ultimately revenue is considered a low hanging fruit. Relatively little effort, but huge impact. Give ImageEngine a try!
Not sure if SEO questions are relevant for StackOverflow. Feel free to correct me if not.
Not sure if SEO questions are relevant for StackOverflow. Feel free to correct me if not.
Have a "quiz" website that shows many duplicate images. For example - when users are going through a "goals" section of the quiz the image stays the same until the section changes.
<p class= I'm very motivated.</p>
<img id='image1' src='' alt= "Woman shooting bow">
<p class= I want to succeed.</p>
<img id='image2' src='' alt= "Woman shooting bow">
The images are hidden and shown depending on the question.
My question is:
What is the best way to handle this from an SEO standpoint? Just make different alt tags for the same image?
Should I create a variable and somehow use it for the images>
I have a component in React which displays (or doesn't at the moment) an image within an src tag.
I have a component in React which displays (or doesn't at the moment) an image within an src tag.
The file path & file name of the image is passed via props after being selected by the user, so I can't do an import at the top of the file. Apparently, I should be able to do something like src={require(file)} but this causes webpack to throw a hissy fit and give the following error: Error: cannot find module "."
As an e.g., a typical filepath/filename I pass to the component is: '../../../images/black.jpg'
This is a stripped-down version of the code in question:
import React, { Component } from "react";
class DisplayMedia extends Component {
render() {
return (
<div className="imgPreview">
<img src={props.file}
</div>
);
}
}
export default DisplayMedia;
|
https://morioh.com/p/3e7a1728296e
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
React hooks based form validation made for humans
Formalizer
Formalizer is a React Hooks based form validation library made for humans. The cleanest code or your money back ;)
Simple, tiny, extensible, intuitive, documented, fully tested, magical.
Installation
yarn add formalizer
or
npm install formalizer --save
Sample Usage
import { useFormalizer } from 'formalizer'; const UserProfileComponent = () => { const { formRef, useInput, errors, isValid } = useFormalizer(); return ( <form ref={formRef}> <input {...useInput('name', ['isRequired'])} /> <span>{errors['name']}</span> <input {...useInput('email', ['isRequired', 'isEmail'])} /> <span>{errors['email']}</span> <button disabled={!isValid} Submit </button> </form> ); };
For a complete guide on how each of these pieces work, see our tutorial.
In a Nutshell
Use the
useFormalizer hook to gain access to the
useInput hook, the errors currently in your form, whether the form is valid or not and more.
Then, use the
useInput to setup validations on your form inputs.
Formalizer offers two built in validators out-of-the-box and it integrates with the awesome validator library seamlessly, which means if you install it you can use all of their validators.
But know that writing your own custom validators is super easy.
Also, you may create global validators so that they accessible throughout your app. Doing so helps keep your code DRY and facilitates maintaining it.
Finally, if you use Material UI you may like the fact Formalizer integrates with it. If you use some other UI framework, chances are you can tweak our settings to make it work with it.
Contributing
Contributions are very welcome!
We follow the "fork-and-pull" Git workflow.
Create a Fork and clone it
Simply click on the “fork” button of the repository page on GitHub.
The standard clone command creates a local git repository from your remote fork on GitHub.
Modify the Code
In your local clone, modify the code and commit them to your local clone using the git commit command.
Run
npm testand make sure all tests still pass.
Run
tslint --project .and make sure you get no warnings.
Push your Changes
Make sure to update affected tests and/or add tests to any new features you may have created.
We are very careful to make sure coverage does not drop.
Create a Pull Request
We will review your changes and possibly start a discussion.
If changes are required, you can simply push these changes into your fork by repeating steps #3 and #4 and the pull request is updated automatically.
|
https://reactjsexample.com/react-hooks-based-form-validation-made-for-humans/
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't..
I came across the FizzBuzz question in this excellent blog post on conducting data scientist interviews and have seen it referenced elsewhere on the web. The intent of the question is to probe the job applicant’s knowledge of basic programming concepts.
The prompt of the question is as follows:
We will first solve the problem in R. We will make use of control structures: statements “which result in a choice being made as to which of two or more paths to follow.” This is necessary for us to A) iterate over a number sequence and B) print the correct output for each number in the sequence. We will solve this problem in two slightly different ways.
Solution 1: Using a “for loop”
The classical way of solving this problem is via a “for loop“: we use the loop to explicitly iterate through a sequence of numbers. For each number, we use if-else statements to evaluate which output to print to the console.
The code* looks like this:
for (i in 1:100){
if(i%%3 == 0 & i%%5 == 0) {
print('FizzBuzz')
}
else if(i%%3 == 0) {
print('Fizz')
}
else if (i%%5 == 0){
print('Buzz')
}
else {
print(i)
}
}
Our code first explicitly defines the number sequence from 1 to 100. For each number in this sequence, we evaluate a series of if-else statements, and based on the results of these evaluations, we print the appropriate output (as defined in the question prompt).
The double parentheses is a modulo operator, which allows us to determine the remainder following a division. If the remainder is zero (which we test via the double equals signs), the first number is divisible by the second number.
We start with the double evaluation – any other ordering of our if-else statements would cause the program to fail (because numbers which pass the double evaluation by definition also pass the single evaluations). If a given number in the sequence from 1 to 100 is divisible both by 3 and by 5, we print “FizzBuzz” to the console.
We then continue our testing, using “else if” statements. The program checks each one of these statements in turn. If the number fails the double evaluation, we test to see if it is divisible by 3. If this is the case, we print “Fizz” to the console. If the number fails this evaluation, we check to see if it is divisible by 5 (in which case we print “Buzz” to the console). If the number fails each of these evaluations (meaning it is not divisible by 3 or 5), we simply print the number to the console.
Solution 2: Using a function
In general, for loops are discouraged in R. In earlier days, they were much slower than functions, although this seems to be no longer true. The wonderful R programmer Hadley Wickham advocates for a functional approach based on the fact that functions are generally clearer about what they’re trying to accomplish. As he writes: “A for loop conveys that it’s iterating over something, but doesn’t clearly convey a high level goal… [Functions are] tailored for a specific task, so when you recognise the functional you know immediately why it’s being used.” (There are many interesting and strong opinions about using loops vs. functions in R; I won’t get into the details here, but it’s informative to see the various opinions out there.)
The FizzBuzz solution using a function looks like this:
# define the function
fizz_buzz <- function(number_sequence_f){
if(number_sequence_f%%3 == 0 & number_sequence_f%%5 == 0) {
print('FizzBuzz')
}
else if(number_sequence_f%%3 == 0) {
print('Fizz')
}
else if (number_sequence_f%%5 == 0){
print('Buzz')
}
else {
print(number_sequence_f)
}
}
# apply it to the numbers 1 to 100
sapply(seq(from = 1, to = 100, by = 1), fizz_buzz)
The code above defines a function called “fizz_buzz”. This function takes an input (which I have defined in the function as number_sequence_f), and then passes it through the logical sequence we defined using the “if” statements above.
We then use sapply to apply the FizzBuzz function to a sequence of numbers, which we define directly in the apply statement itself. (The seq command allows us to define a sequence of numbers, and we explicitly state that we want to start at 1 and end at 100, advancing in increments of 1).
This approach is arguably more elegant. We define a function, which is quite clear as to what its goal is. And then we use a single-line command to apply that function to the sequence of numbers we generate with the seq function.
However, note that both solutions produce the output that was required by the question prompt!
We will now see how to write these two types of programs in Python. The logic will be the same as that used above, so I will only comment on the slight differences between how the languages implement the central ideas.
Solution 1: Using a “for loop”
The code to solve the FizzBuzz problem looks like this:
for i in range(1,101):
if (i % 3 == 0) & (i % 5 == 0):
print('FizzBuzz')
elif (i % 3 == 0):
print('Fizz')
elif (i % 5 == 0):
print('Buzz')
else:
print(i)
Note that the structure of definition of the “for loop” is different. Whereas R requires {} symbols around all the code in the loop, and for the code inside of each if-else statement, Python uses the colon and indentations to indicate the different parts of the control structure.
I personally find the Python implementation cleaner and easier to read. The indentations are simpler and make the code less cluttered. I get the sense that Python is a true programming language, whereas R’s origins in the statistical community have left it with comparatively more complicated ways to accomplish the same programming goal.
Note also that, if we want to stop at 100, we have to specify that the range in our for loop stops at 101. Python has a different way of defining ranges. The first element in the range indicates where to start, but the last number in the range should be 1 greater than the number you actually want to stop at.
Solution 2: Using a function
Note that we can also use the functional approach to solve this problem in Python. As we did above, we wrap our control flow in a function (called fizz_buzz), and apply the function to the sequence of numbers from 1 to 100.
There are a number of different ways to do this in Python. Below I use pandas, a tremendously useful Python library for data manipulation and munging, to apply our function to the numbers from 1 to 100. Because the pandas apply function cannot be used on arrays (the element returned by the numpy np.arange), I convert the array to a Series and call the apply function on that.
# import the pandas library
import pandas as pd
# define the function
def fizz_buzz(number_sequence_f):
if (number_sequence_f % 3 == 0) & (number_sequence_f % 5 == 0):
return('FizzBuzz')
elif (number_sequence_f % 3 == 0):
return('Fizz')
elif (number_sequence_f % 5 == 0):
return('Buzz')
else:
return(number_sequence_f)
# apply it to the number series
pd.Series(np.arange(1,101)).apply(fizz_buzz)
One final bit of programming details. The for loop defined above calls range, which is actually an iterator, not a series of numbers. Long story short, this is appropriate for the for loop, but as we need to apply our function to an actual series of numbers, we can’t use the range command here. Instead, in order to apply our function to a series of numbers, we use the numpy arange command (which returns an array of numbers). As described above, we convert the array to a pandas Series, which is then passed to our function.
As part of a larger interview, I suppose, this question makes sense. A large part of applied analytical work involves manipulating data programmatically, and so getting some sense of how the candidate can use control structures could be informative.
However, this doesn’t really address the biggest challenges I face as a data scientist, which involve case definition and scoping: e.g. how can a data scientist partner with stakeholders to develop an analytical solution that answers a business problem while avoiding unnecessary complexity? The key issues involve A) analytical maturity to know what numerical solutions are likely to give a reasonable solution with the available data, B) business sense to understand the stakeholder problem and translate it into a form that allows a data science solution, and C) a combination of A and B (analytical wisdom and business sense) to identify the use cases for which analytics will have the largest business impact.**
So data science is a complicated affair, and I’m not sure the FizzBuzz question gives an interviewer much sense of the things I see as being important in a job candidate.*** For another interesting opinion on what’s important in applied analytics, I can recommend this excellent blog post which details a number of other important but under-discussed aspects of the data science profession.
In this post, we saw how to solve a data science interview question called “FizzBuzz.” The question requires the applicant to think through (and potentially code) a solution which involves cycling through a series of numbers, and based on certain conditions, printing a specific outcome.
We solved this problem in two different ways in both R and Python. The solutions allowed us to see different programming approaches (for loops and functions) for implementing control flow logic. The for loops are perhaps the most intuitive approach, but potentially more difficult for others to interpret. The functional approach benefits from clarity of purpose, but requires a slightly higher level of abstract thinking to code. The examples here serve as a good illustration of the differences between R and Python code. R has its origins in the statistical community, and its implementation of control structures seems less straightforward than the comparable implementations in Python.
Finally, we examined the value of the FizzBuzz interview question when assessing qualities in a prospective data science candidate. While the FizzBuzz question definitely provides some information, it misses a lot of what (in my view) comprises the critical skill-set that is needed to deliver data science projects in a business setting.
Coming Up Next
In the next post, we will see how to use R to download data from Fitbit devices, employing a combination of existing R packages and custom API calls.
Stay tuned!
—
* My go-to html code formatter for R has disappeared! If anyone knows of such a resource, it would be hugely helpful in making the R code on this blog more readable. Please let me know in the comments! (The Python code is converted with tohtml).
** And then, of course, once a proper solution has been developed, it has to be deployed. Can you partner with data engineers and/or other IT stakeholders to integrate your results into business processes? (Notice the importance of collaboration – a critical but seldom-discussed aspect of the data science enterprise).
*** In defense of the above-referenced blog post, the original author is quite nuanced and does not only rely on the FizzBuzz question when interviewing.
|
https://www.r-bloggers.com/fizzbuzz-in-r-and-python/
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
Thank you for reply!Thank you for reply!Moe wrote:Yes and no. It's possible, and fairly easy, but you can't just connect them directly - the Pi outputs 3.3V and the Sabertooth needs 5V.
Best way to do this would be an add-on board; there are loads for the Pi and the Sabertooth provides lots of options. You could use simple PWM smoothed by capacitors to give an analogue voltage to each motor (S1 and S2). In this mode, 2.5V is stop, 0V is full speed backward and 5V is full speed forward. It would take a bit of trial-and-error to get the voltages right, and if your motors are big enough to need a 25A driver then a trial-and-error approach might be a little bit dangerous.
But there is an easier option. I use a servo-controller board that outputs 5V RC, because I want to switch between Pi control and manual radio control. This way the servo-controller outputs exactly the same signals you would get from the receiver in a radio-controller toy car and the Sabertooth interprets them in the same way.
It also a has a great little 'differential mode' feature, where the S1 input controls speed to both motors and the S2 input does the steering, which means you can also use the transmitter from a toy car.
Read the manual and decide which option is best for you: ... th2x25.pdf
I would be happy if you will report back.I would be happy if you will report back.Moe wrote:Personally, no. Most Pi robot boards aren't designed to take that current, but I reckon such things should be available somewhere.
My plan is to use the Sabertooth 2x25 to control 4 wheelchair motors; two on each channel. I should be in a position to test this in the next week or so. Will report back. Do you need to control the six motors independently, or just two banks of three?
Code: Select all
int SendPacket(unsigned char * Packet, int count) { if(!emulator) { write(Handle,Packet,count); // printf("%s\n",Packet);fflush(stdout); } return(1); } void SendMotor(BYTE command,BYTE value) { BYTE controller=131; BYTE buffer[8]; int loop; int sum=0; buffer[0]=controller; buffer[1]= command & 0x7f; buffer[2]= value & 0x7f; for( loop=0;loop<3;loop++) sum+=buffer[loop]; buffer[3]= sum & 0x7f; SendPacket(buffer,4);usleep(50000); printf("SendMotor(command=%d,value=%d)\n",command,value); fflush(stdout); }
So for example I have 2 PWM pins on RPi for example :So for example I have 2 PWM pins on RPi for example :Moe wrote:OK, I tried running two motors off the same channel of the sabertooth today and it worked fine, even with one of them reversed. As far as I can tell without bothering with scientific measurements, they go at exactly the same speed. ?Moe wrote:That wiring is correct if you're using the Sabertooth in R/C mode, i.e. using WiringPi to send servo PWM signals. The signals you're quoting look more like 'normal' motor control PWM, in which case you need to convert the digital PWM to an analogue voltage, boost it to 5V somehow and and set the Sabertooth to analogue mode.
Code: Select all
import RPi.GPIO as GPIO import time PIN_MOTOR1=12 #Moteur droite S1 PIN_MOTOR2=19 #Moteur gauche S2 try: #configure les pins GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(PIN_MOTOR1, GPIO.OUT) GPIO.setup(PIN_MOTOR2, GPIO.OUT) motor1=GPIO.PWM(PIN_MOTOR1,1000) motor2=GPIO.PWM(PIN_MOTOR2,1000) #Avance motor1.start(75) motor2.start(75) #GPIO.output(PIN_MOTOR1, GPIO.HIGH) time.sleep(3) #Continue #Fais reculer motor1.start(25) motor2.start(25) #GPIO.output(PIN_MOTOR1,GPIO.LOW) time.sleep(5) #Freine et stoppe le moteur motor1.stop() motor2.stop() except KeyboardInterrupt : pass except : GPIO.cleanup() raise GPIO.cleanup()
Code: Select all
sudo pip3 install pysabertooth
Code: Select all
from pysabertooth import Sabertooth moteurAB = Sabertooth("/dev/serial0",baudrate=9600,address=128) moteur.drive(1,50)
Code: Select all
# Released by rdb under the Unlicense (unlicense.org) # Based on information from: # import os, struct, array from fcntl import ioctl # Iterate over the joystick devices. print('Available devices:') for fn in os.listdir('/dev/input'): if fn.startswith('js'): print(' /dev/input/%s' % (fn)) # We'll store the states here. axis_states = {} button_states = {} # These constants were borrowed from linux/input.h axis_names = { 0x00 : 'x', 0x01 : 'y', 0x02 : 'z', 0x03 : 'rx', 0x04 : 'ry', 0x05 : 'rz', 0x06 : 'trottle',', } axis_map = [] button_map = [] # Open the joystick device. fn = '/dev/input/js0' print('Opening %s...' % fn) jsdev = open(fn, 'rb') # Get the device name. #buf = bytearray(63) #buf = array.array(b'c', [b'\0'] * 64) #ioctl(jsdev, 0x80006a13 + (0x10000 * len(buf)), buf) # JSIOCGNAME(len) #js_name = buf.tostring() buf=b'\0'*64 buf = ioctl(jsdev, 0x80006a13 + (0x10000 * len(buf)), buf) # JSIOCGNAME(len) js_name = buf.decode("utf-8").split('\0')[0] print('Device name: %s' % js_name) # Get number of axes and buttons. buf = b'\0' #buf = array.array('B', [0]) #ioctl(jsdev, 0x80016a11, buf) # JSIOCGAXES buf=ioctl(jsdev, 0x80016a11, buf) # JSIOCGAXES num_axes = struct.unpack('B',buf)[0] buf = b'\0' buf= ioctl(jsdev, 0x80016a12, buf) # JSIOCGBUTTONS num_buttons = struct.unpack('B',buf)[0] #print("num_axes ",num_axes) #print("num_buttons ",num_buttons) #buf = array.array('B', [0]) #ioctl(jsdev, 0x80016a12, buf) # JSIOCGBUTTONS #num_buttons = buf[0] # Get the axis map. buf = b'\0'*64 #buf = array.array('B', [0] * 0x40) #ioctl(jsdev, 0x80406a32, buf) # JSIOCGAXMAP buf = ioctl(jsdev, 0x80406a32, buf) # JSIOCGAXMAP for axis in buf[:num_axes]: axis_name = axis_names.get(axis, 'unknown(0x%02x)' % axis) axis_map.append(axis_name) axis_states[axis_name] = 0.0 # Get the button map. buf = b'\0' * 400 #buf = array.array('H', [0] * 200) buf = ioctl(jsdev, 0x80406a34, buf) # JSIOCGBTNMAP buf = struct.unpack('H'*(len(buf)//2),buf) for btn in buf[:num_buttons]: btn_name = button_names.get(btn, 'unknown(0x%03x)' % btn) button_map.append(btn_name) button_states[btn_name] = 0 print ('%d axes found: %s' % (num_axes, ', '.join(axis_map))) print ('%d buttons found: %s' % (num_buttons, ', '.join(button_map))) # Main event loop while True: evbuf = jsdev.read(8) print(evbuf) if evbuf: time, value, type, number = struct.unpack('IhBB', evbuf) if type & 0x80: print( "(initial)"), if type & 0x01: button = button_map[number] if button: button_states[button] = value if value: print( "%s pressed" % (button)) else: print("%s released" % (button)) if type & 0x02: axis = axis_map[number] if axis: fvalue = value / 32767.0 axis_states[axis] = fvalue print( "%s: %.3f" % (axis, fvalue))
Code: Select all
#!usr/bin/env python #*coding:utf-8* from pysabertooth2 import Sabertooth import serial import time saber = Sabertooth('/dev/ttyS0', baudrate=9600, address=130, timeout=0.1) # drive(number, speed) #number : 1-2 #speed: -100 à +100 saber.drive(1,50) saber.drive(2,50) time.sleep(3) saber.drive(1,-50) saber.drive(2,-50) time.sleep(3) #avance pendant 5 secondes #saber.driveBoth(50,50) #time.sleep(3) saber.stop() saber.close()
|
https://www.raspberrypi.org/forums/viewtopic.php?f=65&t=128486
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
About the Examples
Versions
The examples in this book run with the Java Developer’s Kit (JDK) 1.2 and the Java
Cryptography Extension (JCE) 1.2. The examples in the book were tested with JDK 1.2beta3
and JCE 1.2ea2. Some of the topics covered are applicable to JDK 1.1, especially the
Identity-based key management discussed in Chapter 5 and the
MessageDigest and
Signature classes in
Chapter 6. However, anything involving encryption
requires the JCE. The only supported version of the JCE is 1.2, and it only runs with JDK
1.2. (Although the JCE had a 1.1 release, it never progressed beyond the early access
stage. It is not supported by Sun and not available from their web site any
longer.)
The signed applets in Chapter 8 work with HotJava 1.1, Netscape Navigator 4.0, and Internet Explorer 4.0.
File Naming
This book assumes you are comfortable programming in Java and
familiar with the concepts of packages and
CLASSPATH. The source code for examples in this
book should be saved in files based on the class name. For example,
consider the following code:
import java.applet.*; import java.awt.*; public class PrivilegedRenegade extends Applet { ... }
This file describes the
PrivilegedRenegade class;
therefore, you should save it in a file named
PrivilegedRenegade.java.
Other classes belong to particular packages. For example, here is the beginning of one of the classes from Chapter 9:
package oreilly.jonathan.security; import java.math.BigInteger; import java.security.*; public class ElGamalKeyPairGenerator extends KeyPairGenerator { ... }
This should be saved in oreilly/jonathan/security/ElGamalKeyPairGenerator.java.
Throughout the book, I define classes in the
oreilly.jonathan.* package hierarchy. Some of them
are used in other examples in the book. For these examples to work
correctly, you’ll need to make sure that the directory
containing the oreilly directory is in your
CLASSPATH. On my computer, for example, the
oreilly directory lives in c:\
Jonathan\ classes. So my
CLASSPATH
contains c:\ Jonathan\ classes ; this makes the
classes in the
oreilly.jonathan.* hierarchy
accessible to all Java applications.
CLASSPATH
Several examples in this book consist of classes spread across
multiple files. In these cases, I don’t explicitly
import files that are part of the same example.
For these files to compile, then, you need to have the current
directory as part of your classpath. My classpath, for example,
includes the current directory and the Java Cryptography Extension
(JCE—see Chapter 3). On my Windows 95
system, I set the CLASSPATH in autoexec.bat as
follows:
set classpath=. set classpath=%classpath%;c:\jdk1.2beta3\jce12-ea2-dom\jce12-ea2-dom.jar
Variable Naming
The examples in this book are presented in my own coding style, which is an amalgam of conventions from a grab bag of platforms.
I follow standard Java coding practices with respect to capitalization. All member variables of a class are prefixed with a small m, like so:
protected int mPlainBlockSize;
This makes it easy to distinguish between member variables and local variables. Static members are prefixed with a small s, like this:
protected static SecureRandom sRandom = null;
And final static member variables are prefixed with a small k (it stands for constant, believe it or not):
protected static final String kBanner = "SafeTalk v1.0";
Array types are always written with the square brackets immediately following the array type. This keeps all the type information for a variable in one place:
byte[] ciphertext;
Downloading
Most of the examples from this book can be downloaded from. Some of the examples,
however, cannot legally be posted online. The U. S. government
considers some forms of encryption software to be weapons, and the
export of such software or its source code is tightly controlled.
Anything we put on our web server can be downloaded from any location
in the world. Thus, we are unable to provide the source code for some
of the examples online. The book itself, however, is protected under
the first amendment to the U. S. Constitution and may be freely
exported.
Get Java Cryptography now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
|
https://www.oreilly.com/library/view/java-cryptography/1565924029/pr03s04.html
|
CC-MAIN-2020-05
|
en
|
refinedweb
|
Docs |
Forums |
Lists |
Bugs |
Planet |
Store |
GMN |
Get Gentoo!
Not eligible to see or edit group visibility for this bug.
View Bug Activity
|
Format For Printing
|
XML
|
Clone This Bug
Please, test and mark net-p2p/museek+-0.1.13 ~amd64..
Even though only museeq ( USE="qt" ) has language support, maybe we should keep
the LINGUAS?
(In reply to comment #1)
>.
Done, thanks for pushing, I was actually being lazy to write extra patches. Now
the version to keyword is 0.1.13-r1.
> Even though only museeq ( USE="qt" ) has language support, maybe we should keep
> the LINGUAS?
Upstream has changed their build system to a mix of CMake and distutils (and
optionally qmake and SCons). I'm using CMake since it's the recommended one,
and distutils for the stuff that strictly requires it. Support for selecting
languages has been dropped in their CMake build system and now all locales are
installed unconditionally. I'm not patching it for _not_ installing some locale
files, if you're interested in getting it done speak with the authors or send
them a patch.
If they apply a patch in SVN repo, I may apply it in portage.
amd64 has to pass on this uncomplete ebuild.
drac@unique ~ $ musetup-qt
Traceback (most recent call last):
File "/usr/bin/musetup-qt", line 9, in <module>
from qt import *
ImportError: No module named qt
drac@unique ~ $ musetup-gtk
Traceback (most recent call last):
File "/usr/bin/musetup-gtk", line 2894, in <module>
Mapp = MainApp()
File "/usr/bin/musetup-gtk", line 2885, in __init__
self.app = MuseekSetupGTK()
File "/usr/bin/musetup-gtk", line 445, in __init__
self.tryReadConfig()
File "/usr/bin/musetup-gtk", line 2273, in tryReadConfig
self.readTemplate()
File "/usr/bin/musetup-gtk", line 2242, in readTemplate
self.readConfig(self.TEMPLATE_PATH)
File "/usr/bin/musetup-gtk", line 2283, in readConfig
doc = minidom.parse(CONFIG)
File "/usr/lib64/python2.5/xml/dom/minidom.py", line 1913, in parse
return expatbuilder.parse(file)
File "/usr/lib64/python2.5/xml/dom/expatbuilder.py", line 922, in parse
fp = open(file, 'rb')
IOError: [Errno 2] No such file or directory:
'/usr/share/museek/museekd/config.xml.tmpl'
drac@unique ~ $
Any news on this?
Added an elog message about it (I don't want to add extra stupid USE flags or
uneeded deps).
Keyworded ~amd64 myself since I run it currently.
ebuild has,
gtk? ( >=dev-python/pygtk-2.6.1 )
then,
elog "musetup-gtk: dev-python/pygtk"
and it still fails -- pygtk was installed from the beginning.
plus the postinst message is ridiculous, since it already depends on pygtk with
USE gtk, why not depend on pyqt with USE qt?
musetup-gtk's bug fixed in 0.1.13-r2.
I'm not changing USE flags handling at the moment, you can file an upstream bug
asking them to add a better error so musetup-* don't give a traceback when PyQt
or pygtk are installed. Anyway, I may write such patch eventually.
|
http://bugs.gentoo.org/193444
|
crawl-002
|
en
|
refinedweb
|
Docs |
Forums |
Lists |
Bugs |
Planet |
Store |
GMN |
Get Gentoo!
Not eligible to see or edit group visibility for this bug.
View Bug Activity
|
Format For Printing
|
XML
|
Clone This Bug
I tried emerging advancemenu-2.4.9 with several configurations on two different
systems.
First with
[ebuild N ] games-emulation/advancemenu-2.4.9 +alsa -debug +expat -fbcon
+ncurses +oss +sdl +slang +static -svga +truetype +zlib
resulted in an error telling me thas alsalib was not found. But I am absolutely
sure, it is installed:
* media-libs/alsa-lib
Latest version available: 1.0.8
Latest version installed: 1.0.8
Next, I disabled alsa:
[ebuild N ] games-emulation/advancemenu-2.4.9 -alsa -debug +expat -fbcon
+ncurses +oss +sdl +slang +static -svga +truetype +zlib
now configure interrupts with an error that sdl was not found, but also this
time I am sure, it is installed:
* media-libs/libsdl
Latest version available: 1.2.8-r1
Latest version installed: 1.2.8-r1
last, I disabled the sdl flag:
[ebuild N ] games-emulation/advancemenu-2.4.9 -alsa -debug +expat -fbcon
+ncurses +oss -sdl +slang +static -svga +truetype +zlib
but this time configure stopped with:
configure: error: no video library found. If you have the SDL library installed
somewhere try using the --with-sdl-prefix option.
(Other ebuilds find alsa and sdl)
Reproducible: Always
Steps to Reproduce:
1. as root: emerge advancemenu
2.) Celeron(R) CPU 2.00GHz
Gentoo Base System version 1.6.12
Python: dev-lang/python-2.3.5 [2.3.5 (#1, Jun 15 2005, 04:41:00)]
dev-lang/python: 2.3.5
sys-apps/sandbox: [Not Present]10
sys-devel/libtool: 1.5.16
virtual/os-headers: 2.6.8.1-r2
ACCEPT_KEYWORDS="x86"
AUTOCLEAN="yes"
CFLAGS="-O2 -march=pentium3 -fomit-frame-pointer -pipe"
DISTDIR="/usr/portage/distfiles"
FEATURES="autoaddcvs autoconfig ccache distlocks sandbox sfperms strict"
GENTOO_MIRRORS=""
LINGUAS="de"
MAKEOPTS="-j2"
PKGDIR="/usr/portage/packages"
PORTAGE_TMPDIR="/var/tmp"
PORTDIR="/usr/portage"
SYNC="rsync://rsync.gentoo.org/gentoo-portage"
USE="x86 16bit 3dfx X Xaw3d a52 aac aalib alsa apm arts artswrappersuid asm avi
beepmp bitmap-fonts cacheemu cdr delays dga dpms dts encode esd expat fam flac
ggi gif glut gnokii gpm gtk gtk2 hal imlib jack jack-tmpfs java javascript jikes
jit joystick jpeg jpeg2k kde kdeenablefinal kqemu lcms libcaca libdsk libg++
livecd mad matrox mikmod mips16 mmx mng motif mp3 mpeg multislot multitarget
ncurses nls nocd nodrm nptl nvidia ogg oggvorbis openal openexr opengl oss pam
pcre pda pdflib physfs pic png portaudio python qt quicktime readline real
sblive sdl slang sndfile softmmu sse static svg symlink tcltk tetex threads tiff
transcode truetype truetype-fonts type1-fonts unicode vidix vorbis win32codecs
wmf wxgtk1 wxwindows xml2 xmms xrandr xv xvid zlib linguas_de userland_GNU
kernel_linux elibc_glibc"
Unset: ASFLAGS, CBUILD, CTARGET, LANG, LC_ALL, LDFLAGS, PORTDIR_OVERLAY
Created an attachment (id=62414) [edit]
emerge output
output of emerge advancemenu using +alsa and +sdl
let's have the config.log from the build directory please. Attach it as
text/plain. So far, I suspect you've been neglecting some local maintenance,
but the log will make it more clear.
Created an attachment (id=62416) [edit]
/var/tmp/portage/advancemenu-2.4.9/work/advancemenu-2.4.9/config.log
Till now, I did not know, that this file is kept when errors occure...
looks like remerging glibc and alsa-lib might help. Just for fun, let's see
the
output from "emerge -evp world" before you kick that off.
Created an attachment (id=62418) [edit]
emerge -evp world > emerge_-evp_world
looks clean. thanks for doing that. proceed with the glibc and alsa-lib
remerge and see if that clears things up for you wrt advancemenu.
just started emerge glibc alsa-lib
It will probably take a rather long time, because I have not ccache installed on
that system and my computer is not really fast. nptl is set, but nptlonly is unset.
Now, I've done:
emerge glibc alsa-lib
[...]
>>> No outdated packages were found on your system.
* Regenerating GNU info directory index...
* Processed 125 info files.
env-update
>>> Regenerating /etc/ld.so.cache...
* Caching service dependencies ...
emerge advancemenu
[...]
checking for port in/out... yes
checking for snd_pcm_open in -lasound... no
configure: error: the ALSA library is missing
!!! ERROR: games-emulation/advancemenu-2.4.9 failed.
!!! Function egamesconf, Line 66, Exitcode 1
!!! egamesconf failed
!!! If you need support, post the topmost build error, NOT this status message.
still the same problem
darn. does running revdep-rebuild turn up anything?
revdep-rebuild does not find any problems:.
well, my next guess is that this is caused by you having set pic in your use
flags.
/ # prelink -ua
prelink: /usr/lib/nwwine/bin/wine: Could not find one of the dependencies
prelink: /usr/lib/nwwine/bin/wine: Could not find one of the dependencies
prelink: /usr/i686-pc-linux-gnu/gcc-bin/3.3.5-20050130/i686-pc-linux-gnu-g++ is
no longer hardlink to
/usr/i686-pc-linux-gnu/gcc-bin/3.3.5-20050130/i686-pc-linux-gnu-c++
/ # nano /etc/make.conf
/ # env-update
>>> Regenerating /etc/ld.so.cache...
* Caching service dependencies ...
[ ok ]
/ # emerge world -Npv
These are the packages that I would merge, in order:
Calculating world dependencies ...done!
[ebuild R ] app-arch/gzip-1.3.5-r7 -build +nls -pic* +static 0 kB
[ebuild R ] sys-libs/glibc-2.3.4.20041102-r1 -build -debug -erandom
-hardened (-multilib) +nls -nomalloccheck +nptl -nptlonly -pic* +userlocales 0 kB
Total size of downloads: 0 kB
/ # emerge world -N
currently running... I will got to bed now.
~ $ date +%X
01:16:37
Thank you for your help. I'll post the result tomorrow.
both packets successfully remerged with -pic
still the same problem
USE=pic does not cause issues for anyone ... the use of it in gzip/glibc is
unrelated
it's failing because of the static USE flag
when linking against libasound.a you have to add -lpthread to your linking flags
if you're using -static ... libasound.so has the info recorded in the lib itself
so you can just do -lasound
in this case, the configure.ac is misbehaving in that it uses AC_CHECK_LIB() on
libasound instead of consulting the alsa.pc file installed for pkg-config ... if
we update configure.ac like this, it should work:
elif test $ac_lib_alsa = yes; then
AC_CHECK_LIB(
[asound],
[snd_pcm_open],
[],
[AC_MSG_ERROR([the ALSA library is missing])],
- [-lm]
+ [`pkg-config alsa --libs`]
)
AC_MSG_CHECKING([for ALSA version])
AC_TRY_COMPILE([
#include <alsa/asoundlib.h>
], [
#if SND_LIB_VERSION < ((0<<16)|(9<<8)|0)
choke me
So, if I just remove the static flag an do a emerge world --newuse it should
work.
I tested it on a system with everything compiled -static. Emerges cleanly.
With your patch it should also work for +static, right?
Well, I applied this patch, created a new ebuild and tried to emerge it. But I
still get the same error.
added patch to 2.4.10 in cvs, thanks for the bug report
|
http://bugs.gentoo.org/97628
|
crawl-002
|
en
|
refinedweb
|
double atan ( double x );
float atan ( float x );
long double atan ( long double x );
<cmath>
Compute arc tangent
Returns.In C++, this function is overloaded in <valarray> (see valarray atan).
/* atan example */
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
int main ()
{
double param, result;
param = 1.0;
result = atan (param) * 180 / PI;
printf ("The arc tangent of %lf is %lf degrees\n", param, result );
return 0;
}
The arc tangent of 1.000000 is 45.000000 degrees.
|
http://www.cplusplus.com/reference/clibrary/cmath/atan/
|
crawl-002
|
en
|
refinedweb
|
I had read about SOAP and attended a few conferences on the subject about a year ago, but didn't have much of a need for the technology back then. Recently our voice applications platform provider, Bevocal, started to make their call logs and telephony functions available via SOAP. Ah, the perfect excuse to finally jump in and start writing some SOAP client software. I found these documents below to be extremely helpful in ramping me back up on XML, SOAP, and the power these bring to interop. I hope these can help you too. It seems that the Java community currently favors the Apache Axis SOAP API, so I decided to learn that. It helped that Bevocal's sample code also uses Apache Axis.
Apache Axis Java DocsThese javadocs really helped make sense of some of the sample Axis java code from the documents below.
Apache Axis Documentation and InstallationThe official Apache site with instructions, downloads, newsgroups, etc. Note that they didn't seem to have the javadocs online here. Those come with the download.Creating Web Services with Apache AxisIn a nutshell, how to deploy and access a web service with Apache Axis. Explains how to use Java2WSDL and WSDL2Java.
Java & XML O'Reilly book chapter on SOAPFull text off the chapter on SOAP
Simple Java Axis SOAP Examples
Using SOAP with Tomcat - On Java OReilly.com
Bevocal's Call Detail Record Access Service documentationA comprehensive example that uses Apache Axis Call class, namespaces, and serialization to obtain simple Java object types made up of complex data. Bevocal did a nice job documenting their SOAP interfaces similar to a Javadoc, and provides example of the request soap xml and response soap xml.
Web Services InteroperabilityExcellent primer on web services interfaces with perl, java and .net example. You gotta love how simple Perl makes things.Top Ten FAQs for Web ServicesVery nice overview of the web service XML syntax and vocabularyJava and Soap, O'Reilly BookAbsorb the first 50 pages of this book and you're all set. Pg 210 has an early Apache Axis client example. When this book was written, Axis wasn't stable yet, and Apache SOAP was more common.Dave Winer's 'A Busy Developers Guide to SOAP 1.1'Very straightforward SOAP XML examples and explanation.Description on namespacesNot having formally studied XML previously, the reference to namespaces and XML-Schema in most of the documentation was a bit confusing. I found this document helpful in getting up to speed.XFront tutorial on XML SchemasAnother very good resource to help make sense of all the namespace and XML Schema talk. XML Schemas are rather new, and will likely replace the use of DTDs someday. Excellent powerpoint slides that explain the difference between DTDs and XML-Schemas. Finally, a picture that's worth a thousand words. XML Schemas will make complete sense to you after reviewing slides 1 thru 44 of xml-schemas1.ppt. From the link shown click on the link in upper right "XML Schema Tutorial"Web Services class from University of North CarolinaProf John Smith of the University of North Carolina has a nice set of class notes online. There is even a link to an IBM powerpoint presentation on Apache Axis. This had some nice diagrams to for simple explanation.
|
http://radio.weblogs.com/0100236/stories/2003/04/21/documentsIUsedToRampUpOnUsingSoapWithJava.html
|
crawl-002
|
en
|
refinedweb
|
Tales of the Malazan
Ranked #882 in Arts , #16,693 overall | Donates to Acumen Fund
Steven Erikson's Tales of the Malazan Book of the Fallen
Introduction to the Malazan Empire
Where the Tales Begin
The Empire has expanded to three continents, all of which are undergoing religious upheavels of one sort or another. The Malazan armies are spread rather thin, and, initially, allies are thin on the ground. While the cast of characters is huge, we follow in each book the fortunes of three siblings, Ganoes, Tavore, and Felisin Paran, as well as the adventures of a motley crew of marines and sappers, christened the Bridgeburners, under the leadership of Sergeant Whiskeyjack. The Bridgeburners are not precisely what they appear to be, and Whiskeyjack is not your typical noncom.. As indicated by the series title, Book of the Fallen, many people die, including major characters we've come to love and respect.
As the series progresses, the world expands, new continents, races and cultures are introduced, along with their gods and magic. The Empire is in disarray, the plots thicken, and we come to realize that these tales encompass a world war, a war of the gods, an armegeddon rising on the horizon. Good stuff.
Table of Contents
Gardens of the Moon
Book 1 in the Tales of the Malazan Book of the Fallen
The Empress Laseen seeks to destroy the last of the Bridgeburners, only a handful of whom now survive after the distrastrous, yet victorious, seige of Pale. She sends them on a secret mission to infiltrate Darujhistan and undermine the city from within, assuming their failure. Plots within plots, betrayals and alliances, a highly confusing array of characters. This introduction to the series is difficult to follow, to say the least.
Frankly, while I admired Erikson's writing, I did not particularly connect with this book or any of the characters (as I knew them then). The atrocities and very mature subject matter made other "hard-bitten" fantasy series seem almost tame. After reading Gardens of the Moon, I waited a year before picking up Deadhouse Gates. Very glad I finally did.
Buy Gardens of the Moon at Amazon
Gardens of the Moon (The Malazan Book of the Fallen, Vol. 1)
Book 1 in the series introduces many of the main characters, such as the Bridgeburners, Ganoes Paran, Tattersail, Anomander Rake, Cotillion, along with the geography and races of Genabackis, the magic Warrens, and more.
Release Date: 12/28/2004
Amazon Price: $7.99 (as of 07/06/2009)
List Price: $7.99
Deadhouse Gates
Book 2 in the Tales of the Malazan Book of the Fallen
At the end of Gardens of the Moon, the remaining Bridgeburners split up, with Fiddler and Kalam off on a "cover" mission to return Apsalar to her home, though their real aim is to reach the Empress Laseen and, possibly, assassinate her. To reach the Malazan homeland, they choose to travel through another main continent held by the Empire called Seven Cities.
While Seven Cities has been under Malazan rule for a number of years (Kalam, in fact, is a native of Seven Cities), they find on their surreptitious arrival that the entire continent is on the brink of revolt, due to the imminent fulfillment of a religious prophecy in which their prophetess, Sha'ik, will be reborn, initiating the Whirlwind, an apocalypse of rebellion against the Empire and a return of Seven Cities past glory. This plot line follows their adventures in traversing Seven Cities in the midst of violent chaos and introduces yet more very interesting characters.
(By the way, I am trying to avoid spoilers in these summaries, though naturally as the book summaries continue some plot advancements will be unavoidably obvious.)
The second plot line follows Felisin Paran. First, a little background on the Parans (we have mentioned that the Paran family figures prominently in the series). The Parans are a rich, noble family from the heart of Malazan. We have met Ganoes already; as a Malazan army officer, he had found himself attached to the Bridgeburners in Gardens of the Moon, while serving under Adjunct Lorn, and is presently finding himself enmeshed in, hmmm, shall we say, "higher" entanglements.
Tavore Paran, the elder sister, has just been appointed the new Adjunct to the Empress. An Adjunct seems to function as the visible manifestation of the Empress, her right-hand woman, her executive assistant, her chief advisor, and who knows what else. A very, very powerful position. Sadly, no sooner has Tavore achieved this prominence than Laseen decides another purge of the nobility is in order (those pesky nobles often dislike dictatorship).
The Paran patriarch falls in the purge, the mother dies of grief, and Felisin, youngest of the Paran family, is sent off to the slave camps at the otataral mines, on an island in the north of Seven Cities. Felisin is very angry with her sister for not saving her from this fate. Very angry. Very, very angry. This second plot line follows the adventures of Felisin and two of her enslaved companions, Heboric and Baudin, as they reach the mines, and, later, when the Seven Cities uprising reaches them, as they escape and make their way through Seven Cities.
So, we have an entire continent ablaze with rebellion. Huge armies of rebels are forming under variously competent leaders. A new Prophetess is expected to initiate the Whirlwind momentarily. Malazan garrisons are either being slaughtered (if small), retreating into their forts under seige, or off-loading onto any available ships or dinghies and sailing away as quickly as possible.
And the Empress deals with these problems in a very peculiar way. She fortifies the southernmost of the Seven Cities port cities - Aren. She leaves her troops holed up there under the command of a dithering, pampered, cowardly noble who will not make a move. She withdraws her fleet to that port and refuses to allow the Admiral (a great guy) to relieve, or even rescue, stranded troops in the north.
Then she sends the renowned Wickan commander, Coltaine, to the northern port of Hissar to take command. The general consensus is that she fears Coltaine, and his Wickans (the best cavalry in the world, and only recently subservient to the Empire), and is expecting that he and they should perish. Apparently, her plan is to lose Seven Cities with the aim of purging her army of those she fears, and then retaking the continent after the flames of heated rebellion have died down.
Through the eyes of an Imperial Historian named Duiker (charged with accurately recording every move the Empire makes), we follow Coltaine as he takes command, wins the loyalty of the Malazan troops under his command, and then, against all odds, begins a trek of well over 1,000 miles to escort over 50,000 Malazan refugees to safety in Aren - surrounded at all times by several rebel armies many times the size of his seeking total destruction of every man, woman and child, through a desert without water, without supplies, and without any relief or help from the fleet or the other Malazan armies.
You will rage. You will weep. You will cheer. You will have to lay the book aside at times to punch walls or walk around or have a drink. I wept through the last hundred pages nonstop. This is the story of the power of the will of one man, and the will of many common people, determined to take one more step, travel one more day, win one more battle. Their suffering is indescribable (by me; Erikson does a fine job). Their strength and perseverance is amazing. Coltaine's story is the most affecting, to me, of all the Tales of the Fallen I've read so far. I cannot recommend Deadhouse Gates highly enough.
Buy Deadhouse Gates at Amazon
Deadhouse Gates (The Malazan Book of the Fallen, Book 2)
Book 2, Deadhouse Gates, focuses on the uprising called the Whirlwind on the continent of Seven Cities, and the Chain of Dogs, a 1,000 mile plus retreat and rescue operation under the command of Coltaine. A great read.
Release Date: 02/07/2005
Amazon Price: $7.99 (as of 07/06/2009)
List Price: $7.99
Used Price: $3.03
Memories of Ice
Book 3 in the Tales of the Malazan Book of the Fallen
Dujek Onearm, High Fist of the Empire's Army on Genabackis, has repudiated the Empress. After the events in Darujhistan, he and his entire army have gone rogue and are now free to roam about the continent. No longer at odds with Anomander Rake and his Tiste Andii, Caladan Brood, and Prince K'azz D'Avore with his Crimson Guard, they seek to forge an alliance amongst all the forces of northern Genabackis to battle a greater threat. The enemy of my enemy is my friend.
In the South, a new religion/empire has arisen, under the direction of the Pannion Seer, an evil sorcerer and stooge of the Crippled God. Called the Pannion Domin, these hellbent hordes are recruiting/subdueing vast numbers of starving, mindless fanatics who engage in cannabilism and other atrocities. Marching north, they leave a huge swath of destruction and lifelessness in their wake. The alliance of the free peoples of Genabackis, along with Onearm's Host, are tasked with their defeat.
There are multiple story lines advanced as we learn much more about the Deck of Dragons, representing the pantheon and its primary servants; the sentient races, most particularly the T'lan Imass, undead warriors relentlessly stalking their enemy for 300,000 years; and the stirrings of the Crippled God.
The Crippled God, chained for eons, has become unbound. Inklings of his arousal and activities are rumored and surmised as he begins recruiting for his cause. His cause, the destruction of the world, is the armegeddon towards which all the novels in the series inexorably march. We begin to get a clearer understanding of who is who, who is nice and who is naughty. Who will we root for, and who will cause us great gnashing of teeth.
Characters we had thought lost, including Toc the Younger, snatched into oblivion before the very eyes of Ganoes Paran in book 1, reappear and undergo marvelous transformations. Characters whom we have come to know and love meet their end, or, for some at least, their corporeal end. Others are elevated into surprising new roles. New characters are introduced, as well as new gods and ascendants.
There are two main story lines. First, the alliance moves south to meet the oncoming horde of the Pannion Domin and there are battles and momentous confrontations. The second primary plot line is about an honorable mercenary company, called the Grey Swords, who had accepted the job of providing security to the southern city of Capustan. They hadn't bargained on defending the city from an onslaught of fanatic religious zealots determine to obliterate the city and all its inhabitants. Surrounded by the hordes of the Pannion Domin, they fight to hold the city until Onearm and his allies can relieve them. An impossible task, taken on with resolve and fierce determination. The Grey Swords' stand in Capustan is the most clearly demonstrated example of gallantry and honor in fantasy fiction.
One of the best books in the series, Memories of Ice will grip your heart and your imagination. If you are not solidly hooked on the series by now, you never will be.
Buy Memories of Ice at Amazon
Memories of Ice (The Malazan Book of the Fallen, Book 3)
Book 3, Memories of Ice, chronicles the Crippled God's testing of the waters in his bid for domination and destruction, countered by Dujek Onearm and his allies on Genabackis, providing a temporary setback for evil, a small measure of breathing room for good, and a chance to assess the changes taking place in the Deck of Dragons.
Release Date: 08/01/2006
Amazon Price: $7.99 (as of 07/06/2009)
List Price: $7.99
Used Price: $2.48
House of Chains
Book 4 in the Tales of the Malazan Book of the Fallen
House of Chains begins with the most extensive prologue to date, a lengthy account, beginning several years prior to present events, of the life and adventures of Karsa Orlong, a Toblakai warrior to whom we had been briefly introduced in Deadhouse Gates, as a bodyguard of prophetess Sha'ik in her first incarnation.
Karsa's tale begins in the far north of the Genabackis continent, where his people, the Teblor, have unknowingly worshipped a group of unbound (clanless) T'lan Imass for eons. Karsa seeks to reenergize his people, restore their honor and reputation, and eventually lead them to conquest and glory. He starts out on a quest to kill whoever he can, leading two friends out of the mountains and to their deaths and his own captivity.
Along the way, Karsa learns he is a descendant of the Thelomen Toblakai, one of the most ancient of sentient races. He continues to pursue his destiny while the Whirlwind Goddess awaits the coming battle with the Malazans, returning in time to conduct some personal business of his own during that confrontation.
Meanwhile, we follow Tavore Paran's attempt to gain the respect of her new army, mostly raw recruits, a small remnant of Coltaine's Wickans under Temul's leadership, and the troops who'd been stationed at Aren. Most of the action here is relayed through Fiddler's eyes, who has joined a new platoon of marines and sappers under another name.
The Empress Laseen's political machinations during this time revolve around discrediting Coltaine and his accomplishments, putting it about that he was to blame for the failure to initially contain the Seven Cities uprising and that the ensuing deaths were his fault. An anti-Wickan pogrom is encouraged on Quon Tali (the home continent of the Malazan Empire). Indeed, Laseen seems hellbent on destroying all competence and conscience within her realm. One begins to seriously wonder about her connection to the Crippled God.
The pace here is a bit slower, as Erikson has much to reveal about some of the people who will have important roles to play as the series progresses, particularly Tavore Paran, Karsa Orlong, and the marines of the 14th Army. The book culminates in a decisive battle at Raraku with Tavore's army receiving unexpected aid in their attack.
Buy House of Chains at Amazon
House of Chains (The Malazan Book of the Fallen, Book 4)
Book 4, House of Chains, begins the adventures of Tavore Paran and her new 14th army, as they march to crush the Seven Cities rebellion within the Whirlwind in the Holy Desert Raraku. We also come to know Karsa Orlong, his fighting abilities and his ego, both of which are of epic proportions.
Amazon Price: $7.99 (as of 07/06/2009)
List Price: $7.99
Used Price: $3.16
Midnight Tides
Book 5 in the Tales of the Malazan Book of the Fallen
The Letherii trace their descent from the First Empire. Their legends detail the escape of a small group of Letherii to this unknown continent, their rise to glory, and their unending conquests. Their magic and religion is based on the ancient Holds; the Warrens are unknown to them. We meet Ascendants whom we cannot fit into the Deck of Dragons as we know it.
With most of the continent under their control, the Letherii have turned their eyes to the North, now seeking to claim the lands of the Tiste Edur through economic subterfuge. They anticipate no trouble here, as the Tiste Edur are composed of several tribes which do not work in concert. However, that has recently changed. A new Warlock King has arisen among the Tiste Edur, uniting the tribes.
The main story line in Midnight Tides traces the fortunes of the Tiste Edur through the Sengar family. We have met Trull Sengar before. Now we meet his brothers, Rhulad, Fear, and Binadas. The Warlock King tasks these brothers with a perilous journey to the far north to retrieve a special sword which will make the Warlock King, and the Edur, invincible and allow them to turn the tables on Lether. They are warned not to touch the sword.
The brothers find the sword, but must engage in battle with the Jheck, Soletaken wolves, to get it. In the course of the battle, youngest brother Rhulad, ambitious and conceited, naturally picks up the sword. He is fatally wounded in battle, yet the others are unable to remove the sword from his grip. They get home, prepare him for burial and face the wrath of the Warlock King.
Then Rhulad comes back to life. Yeah. Okay, so the upshot of all this is that the Sword belongs to the Crippled God, Rhulad is basically possessed and, when himself, pretty much insane. He can't be killed - coming back each time crazier than he was before. But the Tiste Edur accept him as their Emperor and begin a march down through Lether to take over. The Letherii are not prepared.
The second, and far more amusing story line, follows the adventures of Tehol Beddict (one of the three Beddict brothers, the other two being Brys and Hull; lots of brotherly interactions in this novel). Tehol and his manservant, Bugg, are hatching a plot to crash Lether's stock market and bring down the entire Lether economy. The ways in which they operate, the inside look at the underbelly and overbelly of Lether city life, and the relationship between Tehol and Bugg are all highly entertaining.
Overall, I found this novel slightly weaker than the others. At first, I thought it was because it takes place on a different continent with unfamiliar characters (aside from Trull Sengar and a god or two). But I think it's really because Erikson uses this story as an opportunity to beat us over the head a bit with the general nastiness of unbridled capitalism and economic imperialism. Political views should always be implicit in the stories and the characters - it's a cop out when they are explicitly narrated.
Midnight Tides is very important in the story as a whole. For one thing, it is made crystal clear that the coming apocalypse will be world-wide in scope, preparing the way for the shocking events coming up in The Bonehunters. We also get to tear our hair out over the complexities of the god/ascendant/magic systems and throw our Decks of Dragons against the wall in frustration. Finally, we are introduced to many new characters, several of whom will possibly play significant roles down the road. My personal favorite of these was Seren Pedac, the Letherii trader guide.
Buy Midnight Tides at Amazon
Midnight Tides (The Malazan Book of the Fallen, Book 5)
Midnight Tides, book 5, takes us to a whole new continent, a new cast of characters, and a new perspective on the changes and challenges facing the good guys as the Crippled God makes his biggest move to date and gains a strong foothold for unleasing chaos upon the world
Amazon Price: $7.99 (as of 07/06/2009)
List Price: $7.99
Used Price: $3.44
The Bonehunters
Book 6 in the Tales of the Malazan Book of the Fallen
The empire's mopping up operations include sending Dujek Onearm's army (now back in Laseen's good graces) to northwest Seven Cities. Here they are stymied by plague, let loose by the goddess Poliel, consort of the Crippled God. Ganoes Paran, on a fact-finding trip of his own, finds them camped outside the city, with most of their officers dead or dying. After dealing with Poliel (not single-handedly, mind you), Ganoes takes command and makes plans to march south. Meanwhile, the plague has spread west, leaving destruction in its wake, with Tavore's army endeavoring to stay one step ahead of it.
A second and third story line, rather related, involves the further adventures in Seven Cities of Karsa Orlong and his new female companion, and Mappo and Icarium, who become separated from one another. Both Karsa and Icarium eventually find themselves on Letherii ships (yes, that is why Midnight Tides is positioned as book 5), bound for Lether to provide dueling fun for Rhulad, immortal pawn of the Crippled God.
Normally, I don't mention the peripheral story lines, nor have I discussed much about the gods, the Elder Gods, the ancient Holds, the sentient races, or the Deck of Dragons. I'm still not going to, since that would constitude a Malazan encyclopedia with hundreds of pages. Still, The Bonehunters is a very busy book and a few things just must be mentioned.
Cutter and some companions are escorting Heboric back to the jade statue on Otataral Island. Heboric has a lengthy vision which I, personally, do not really get. Sighs. Another story line follows Apsalar on a mission to assassinate various parties on behalf of Cotillion. We come to appreciate Cotillion more and more. Kalam and Quick Ben are also busy bees.
In short, The Bonehunters gathers threads from all over the place, ties a lot of things together, introduces a new Elder goddess, a new House, and moves the overall story along at a remarkable pace. We find that the gods are also making decisions about which side they'll take in the coming showdown. But that's not nearly all.
Okay, now for the main story line. (some spoilers here, I just can't resist) Tavore is chasing the remnants of Sha'ik's army under Leoman west across the subcontinent. Leoman beats her to the ancient, well-fortified holy city of Y'Ghatan and holes up there. Amid uncertainty and dissent amongst her advisors, Tavore prepares to break the walls, naturally using her sappers and marines to lead the way. With the plague on their heels and supplies running low, there is no time for a lengthy siege.
Once a great many Malazans have breached the walls, Leoman torches the entire city's inventory of that years' olive oil harvest, creating a gigantic firestorm that consumes the city, including his own troops. What a jerk. He has made a deal with the Queen of Dreams and escapes the city with his new lady friend.
A group of Malazans, some frightened children, and Leoman's erstwhile right hand man, manage to find passage underneath the city, escaping the fire and eventually emerging into the light days later, thanks to Bottle's gift for communication with small creatures. The experience leaves a lasting impression, they have been forged in fire, and they are now the Bonehunters.
You'd think that would be enough for one book, but no. Having completed her assignment, Tavore marches to the west coast, meeting up with Admiral Nok for the return journey to Quon Tali. Word reaches them of sightings of the Letherii expeditionary ships. They also meet up with another fleet and meet the Perish, a nation we have not met before, under service to the newest House in the Deck of Dragons, the House of War, devoted to the wolf god and goddess, Togg and Fanderay. And what do the Perish do? They pledge their allegiance to Tavore. Not the Empire. Just Tavore.
They sail together to Malaz City, where Tavore has her final confrontation with Laseen, who has become concerned about Tavore's ambitions. The final pages of The Bonehunters are extremely fast-paced. Much is revealed. Much is hinted. Fiddler fiddles. That right there is worth the price of the book.
Buy The Bonehunters at Amazon
The Bonehunters: Book Six of The Malazan Book of the Fallen
The Bonehunters, book 6, is an action-packed, fast-paced novel chockful of revelations, mysteries, new people and new gods. The series has now definitely moved away from a focus on the Malazan Empire and takes up the greater battle with the Crippled God on a world-wide scale.
Release Date: 07/01/2008
Amazon Price: $7.99 (as of 07/06/2009)
List Price: $7.99
Used Price: $1.99
Reaper's Gale
Book 7 in the Tales of the Malazan Book of the Fallen
First, we pick up the travels of one of my favorites from Midnight Tides, Seren Pedac, and her unlikely companions, Fear Sengar, Udinaas, Silchas Ruin and Kettle, that strange little girl brought to life by the Azath house in Letheras. Along the way, they add a cocky young companion, Clip, who is said to be the Mortal Sword of Dark (but who we suspect may be something else). As you may recall, their mission is to find the soul of Scabandari, erstwhile Father Shadow, so that a) Fear can confront him for the truth about his betrayal and/or b) Silchas Ruin can destroy him.
Here's the thing. Scabandari's soul is held in a Jaghut Finnest (a Finnest is any item with a Soul embedded. For example, a Jaghut could lock someone's soul in a cookie jar.) Apparently, Silchas Ruin knows where to find it. Others want it for its power, or want it destroyed. Namely, the three sisters of Dawn, Dusk and Dapple. Namely, Shadowthrone. In the end, we find several old friends making their way to where the Finnest is hidden (which turns out to be an enclave of living Tellann tucked away within a dead realm of Omtose Phellack. I think. Ugh, very complex). Anyhoo, Trull and Onrack get there. Hedge gets there. Quick Ben gets there. The dragon sisters get there. Udinaas' son with Menandore is already there.
Frankly, the process by which they all arrive, as we track their travels, is rather dull. Yet, we do learn a great deal more about the Imass. Seren has some personal revelations. Udinaas' backbone shows more and more inherent strength. We learn a lot about the dragons, their history and their realms (Dark, Light and Shadow). But still, it dragged a bit. The showdown was not particularly exciting. The conclusion was satisfactory. That's about the best that can be said.
The second storyline simply baffles me. I'll be honest. Why is it even there? Ok, I can think of several reasons. Granted the necessity, why is it presented in such an incomplete and unsatisfying manner? I'll try to summarize.
In eastern Letheras, there are various tribal nations, mostly free of direct Letherii control. One of them, though, borders Letheras and the chief merchant there wants their land. So he (with the help of his contacts) manufactures a war justifying the land grab. Much of this part of the book is a continuation of Erikson's theme of capitalistic imperialism gone wild.
Anyway, this Awl tribe has a new leader who is determined to fight the Letherii (we never know why). He is up against the Letherii atri-preda and the Edur nominally in charge of the province. Everyone fights. More than once. The Awl are defeated in the end. Everyone dies. The empty lands are now in care of a Barghast tribe under Tool's leadership, newly arrived from the east coast, dedicated to the House of War (the Wolves).
Apparently, this entire story was meant to prepare the way for some sort of showdown in an upcoming book that takes place in this geographic area. The Barghast are already there. Tavore's Perish are also in place. Tavore herself will be coming along shortly.
I will tell you what really bothered me about this story line. First, the destruction of the Grey Swords in a one-sentence reference. They deserved better. Second, Toc the Younger. He deserved better (though, he may get better, you never know ;o ). Three, the people fighting in this story did their jobs, nothing more. Nothing elevating. Nothing worth note. I'm sure Erikson meant it that way - to drive home his point on the human wastefulness of greedy aggression. But....I did not care for this story. In my mind, it bore no comparison to the Chain of Dogs or the Grey Swords stand.
The third story line is the ugliest. A bit of background. When the Edur conquered Letheras, they really didn't conquer. They took some money, and some were appointed to nominal positions of supposed power. But the real power, both economic and political, stayed firmly in Letherii hands. Rhulad has alienated his Edur. Many have returned home. Many are living in style in outlying provinces. The nation is in the slimy grip of Tribal Gnol, that nasty little councillor, who has complete control over what Rhulad hears and sees. He and his fellow Nazis, the power-hungry among the Letherii, have taken the opportunity in this vacuum of leadership to reshape Letheras into their own little police state for personal profit and sadistic fun. Their power extends to imprisoning the Sengar parents, most of the Letherii intelligentsia, merchants they seek to rob, and anyone good looking enough to merit repeated rapes. Thankfully, they all receive their comeuppance at the end. For which we are profoundly grateful.
Tehol's storyline is worked into this, as he and Bugg continue their operations. They are amusing as ever, and the denouement as far as Tehol is concerned is highly entertaining. There are a few minor stories taking place in Letheras at the same time. One involves the Errant and Featherwitch. The Errant may prove to be important. Featherwitch not at all. Another baffling story element.
A minor (at this point) story involves an honorable Edur named Bruthen Trana, who is betrayed by Hannan Mosag (yes, he's still around and about, rather ineffectually) and wanders the depths in search of Brys Beddict, whom he finds. Brys is wanted by several parties of Ascendant persuasion, but at his return (which is pleasing), Erikson explicitly states that Brys is Savior of the Empty Hold.
Regarding the Empty Hold, of which much mention is made in this novel. You're guess is as good as mine. My guess is that the Empty Hold is the Elder equivalent of House Shadow. Empty, because Scabandari is not around. Empty and up for grabs. Shadowthrone does not have his hands on it, I don't think. The Errant wants it, too.
Moving right along (at about the same pace as Erikson in this book), the fourth story line is about Tavore and the Bonehunters. She arrives up north in that big bay (the name escapes me) with about half her fleet. The rest of them, including the Perish, are on their way to the other side of the continent.
Suffering under a misapprehension that the Edur control the Letherii, and that they would like to be "free", Tavore sends her marines in under Keneb and Faradan Sort to infiltrate the Edur and incite the Letherii to an uprising. The original plan is to join up with the rebellious Letherii, work with them in destroying the Edur, while moving steadily south to meet up with Tavore and the fleet when they arrive at the capitol. Well, haha on them. The Letherii are not in rebellion.
Moving in small groups of two platoons, we follow the adventures of our favorite crackpots and dirt-smeared Ascendants (eg, Fiddler and co., Gesler and co., Hellian and co., etc.), as they desperately fight their way south, teaching hundreds, then thousands, of Letherii and Edur alike to respect Moranth munitions, Malazan marines, and the magic of the non-Elder warrens. These people are nuts. Really. And not in a good way. But we love them, anyway.
This story includes one of only four really affecting scenes in this book (two involving Toc and Karsa Orlong - hold your horses, I'll get there shortly. One that I'm not going to spoil). Faradan is companioned by an idiot savant mage named Beak, of extraordinary power and with a horribly sad past. To keep it short, when the Bonehunters arrive at Letheras city and are confronted with a Letherii army in front of them and an Edur army behind them, Beak saves the day. I won't say more.
At this point, Tavore arrives, everyone converges on the capitol, which is in shambles and disarray already due to Tehol's efffectiveness in rousing the masses to revolution and the effects of Icarium's visit, and the Bonehunters take the city. Under new leadership, the future begins to look brighter, or at least sillier, for Letheras.
Okay, the final story line is the one we all waited for - Karsa and Icarium's confrontations with Rhulad. Well now, until the last few pages of the book, nothing happens. I mean that. Nothing. Rhulad is not in the mood to fight these guys. So everyone cools their heels in the city.
As it turns out, Icarium chooses not to duel with Rhulad and instead pursues his own quest for knowledge of himself and his past. The results are not fortuitous. We do not know where Icarium is, or what state he is in, at the end of this book.
Karsa, however, is another story. His character becomes ever more fascinating. Our respect for him begins to truly blossom. Spoiler alert: Karsa defeats Rhulad in a very ingenious way that allows Rhulad to be permanently free of the Crippled God. As he departs the Crippled God's realm, Karsa delivers the most memorable line in the entire novel. This scene is well worth the reading. Well worth it.
Reaper's Gale is a long book with lots of plot threads. Fans of the series will trod their way through, grasping those moments of revelation and pathos, laughter and triumph. No one else will read it, nor should they. In every series, there are books that simply must be gotten through to see the whole through to the end. Here's hoping Toll the Hounds is a bit more exciting.
Buy Reaper's Gale at Amazon
Reaper's Gale: Book Seven of The Malazan Book of the Fallen
Reaper's Gale, book 7, takes the Bonehunters to Lether, along with Karsa and Icarium, who we know will be kicking some serious ass
Release Date: 02/03/2009
Amazon Price: $9.99 (as of 07/06/2009)
List Price: $9.99
Used Price: $4.90
Toll the Hounds
Book 8 in the Tales of the Malazan Book of the Fallen
Book Summary: These tales take place on the continent of Genabackis, primarily in the beautiful city of Darujhistan and in the Tiste Andii city of Black Coral and its environs. Secondary, but important, locations include Hood's Realm, Anomander Rake's sword Dragnipur, and the burial mound of Itkovian, former Shield Anvil of Fener and the Grey Swords (readers might want to refresh their Memories of Ice before reading this one).
The time seems to be a few months following the events of Reaper's Gale, as Karsa Orlong and Samar Dev have made their way to Genabackis, as well as Clip, Nimander and the other Tiste Andii young people. However, some readers feel the events may take place as much as two or three years later. No matter.
An Event is going to happen in Darujhistan and a great many people are drawn to the City of Blue Lights like flies to honey. Spite arrives by boat with her rescuees: Cutter, Scillara, Barathol, Chuur, Mappo, and Iskaral Pust. Torvald Nom returns to his wife, home and friends. The Azath releases Rallick Nom and Vorcan. (Turns out the Nom family is quite extensive and talented in a variety of useful ways.)
While on the road, Karsa and Samar Dev meet up with Traveller (his identity is confirmed very early as Dassem Ultor, so I don't consider that a spoiler). Karsa and Traveller become friends and they travel to Darujhistan together. Karsa is ultimately headed home, while Dassem is after Hood.
Kallor also is making his way to Darujhistan. The Fallen God (eg., the Crippled God) now has a Prophet and a temple there. Kallor's intent is to knock him off his Throne and become King of Chains (I say that deliberately, because Kallor's not the kind to want to be King in Chains).
What happens in Darujhistan? About 700 pages of "slice of life" stories, generally sad and unpleasant, involving scads of people we know and don't know, from the nobility to an ox. Yes, the ox has it's own storyline. *sighs*
In brief, Scillara, Barathol and Chuur become friends with the former Bridgeburners and Duiker. Things happen. Sister Spite discovers her twin, Lady Envy, is now living in Darujhistan. They don't get along. Cutter discovers that you can't go home again.
Iskaral Pust installs himself at the Temple of Shadow and tries to lay the beautiful High Priestess. Aside from that, he does nothing else at all. There is a mulish stand-off late in the story that is meant to be funny. In all of Erikson's other books, it would have been. But he misses the mark this time.
Mappo hires the services of the Trygalle Trade Guild to take him to Icarium. Gruntle is bored and signs on as a Shareholder. They have some adventures and get side-tracked along the way.
Meanwhile, down Black Coral way, two new gods are strugggling to be born. One, the Dying God, is another Crippled God tool or wannabe injected simply to provide a means to bring the other one to fruition and reflect the Chaos taking over the world. The other, now called Redeemer, was once Itkovian.
Nimander and his group are peripherally involved with this storyline, though it really has nothing to do with them or their "true" storylines. Basically, it's another opportunity for Erikson to explicate his central themes. Love matters. Life is suffering. Self-sacrifice and redemption are possible and desirable. We create our gods/religions to suit our perceived needs. Chaos versus order.
I am going to make a leap of faith here that this book was meant to set the stage for the final showdowns coming in the last two books and, therefore, that Erikson deliberately shoved a whole bunch of information about the Houses, Holds, and ascendants into this story so we would be prepared to understand what is coming. To review:
The good: The final pages of Toll the Hounds, and some of the middle parts here and there provide many, many answers for those who (like me) are intensely interested in the Deck of Dragons and the ancient Holds and the gods/ascendants who currently hold titled positions in these pantheons. Personally, I keep a spreadsheet on these matters, and I can now confirm quite a few blank spots while noting that others are now, or soon will be, vacant.
We get to meet Fisher Kel Tath, the Bard. Which is fun, since we've been reading his poetry for years now. He turns out to be a most interesting fellow.
We learn much, much more about the Tiste Andii and Mother Dark. This is important stuff for the final two books and the only reason for Toll the Hounds to exist, in my opinion.
The bad: Most of Toll the Hounds is narrated in Erikson's usual third-person subjective omniscient viewpoint (look it up, I had to), swtiching between various characters along the way. Eg., "Samar wanted to kick Karsa in the you know what, but was diverted by the big Elder God bear standing behind her."
However, a significant portion of the story is narrated to the reader by Kruppe, in an omnisicent mode. Are we surprised that Kruppe is omniscient? No. Are we surprised he is talking? No. Are we surprised Erikson is interjecting the extremely rare second-person omniscient narrative mode? After eight books, not especially. Does it work? Not for me.
We know Kruppe is something special. Maybe Really Big Special. But consider his manner of speech. Consider reading about 200 pages of it. That's one thing. But the really sad thing is that much of what Kruppe says to us ends up sounding trite. Trite. I can't believe I am having to type that word in reference to a Steven Erikson novel. Which brings us to:
The ugly: This was a boring book. After 100 pages, I began to wonder which threads would be emphasized. After 300 pages, I began to wonder if any of the threads would be emphasized. By 600 pages, I had lost interest in most of the threads. After 700 pages, I found out none of the threads mattered a damn.
That's a strong statement, I know. If the mini-stories had been more entertaining. If there had been sufficient interjections of quality humor. If Erikson had progressed to the finale in such a way that I had some anticipation and excitement about what I thought, at least, was going to happen. But no. The ending was interesting and, for me, surprising. Yet, the impact was muted by my sense that so much of the book had been simply futile and dull.
I will admit to you that I read this book during a period when I was severely depressed in real life. No doubt, this has significantly influenced my perceptions. Toll the Hounds was so depressing that I despaired to the point where I almost wished Mother Dark would just suck up the entire universe and end it all. Maybe she will.
Buy Toll the Hounds at Amazon
Toll the Hounds: Book Eight of The Malazan Book of the Fallen
Toll the Hounds returns us to Genabackis where the Tiste Andii show their quality and our beloved Kruppe can't shut up
Release Date: 09/16/2008
Amazon Price: $16.27 (as of 07/06/2009)
List Price: $27.95
Used Price: $10.85
Dust of Dreams
Book 9 in the Tales of the Malazan Book of the Fallen
The Crippled God
Book 10 in the Tales of the Malazan Book of the Fallen
Tales of the Malazan Links and Fan Sites
- Malazan on Wikipedia
- The Tales of the Malazan wiki pages are quite extensive with lots of good info and links.
- Malazan Empire
- This is the main fan site with lots of info and an active forum. Erikson visits and sends messages.
- Malazan Art Guild
- Malazan fan art. Very cool.
- Encyclopaedia Malazica
- A fan wiki. Under construction. Join the wiki and add your knowledge.
- Interview with Erikson
- There are lots of interviews with Steven Erikson on the interweb. I found this one more interesting and a little less pretentious than some of the others. In describing his aims, he states very clearly what I, personally, have gotten from the books. In other words, what I felt were his aims, are actually his aims, so I guess I'm on the right page. :)
- Steven Erikson on Fantasy Fan
- Newish fantasy fan site has lots of info on Erikson and other popular fantasy authors.
- Steven Erikson biography and bibliography
- Short bio of Erikson and a book list.
Malazan Fan Feedback
Please let me know what you think of my lens and/or Steven Erikson's books.
spirituality wrote...
Great lens - you've been blessed by a squidoo angel :)
RolandTumble wrote...
I did vote for Quick Ben, but it was a close thing.... Any of them could be, whenever they're center stage.
Posted September 08, 2008
My Other Links
Nothing to do with Tales of the Malazan
- LagKills T-Shirts and Stuff
- Mine and my husband's t-shirt and gift store. Please visit us.
- Sunny Days Designs
- Our other t-shirt and gift shop. This one is family friendly.
- Sunny Days T-shirts
- Our t-shirt store at printfection
- The Medievalist
- Medieval, celtic and fantasy books, movies and articles.
- Celtic T-shirts
- Celtic knotwork t-shirts, celtic art t-shirts.
|
http://www.squidoo.com/talesofthemalazan
|
crawl-002
|
en
|
refinedweb
|
Nullcreations.net Viviti 2009-06-10T13:08:00-07:00 Nullcreations.net tag:nullcreations.net,2009-06-10:/entries/35473 AJAXify your Viviti Site 2009-06-10T13:08:00-07:00 2009-06-10T13:08:15-07:00 <p>I recently noticed an <a href="">interesting Viviti site</a> that utilizes the built in <a href="">jQuery</a> and some simple JavaScript to make all the pages load via AJAX, and thought I'd quickly do a write up for anyone else using <a href="">Viviti</a> who would like to do the same thing.<br /><br />Since the main content area of Viviti is inside a div#location_0, all you have to do is hook into the primary navigation links and use the <a href="">jQuery load function</a> to replace the contents of #location<em>_</em>0 on the current page with the contents of #location_0 on the target page. Adding a <a href="">slideUp</a>/<a href="">slideDown</a> with some callbacks makes it have a nice transition as well.<br /><br />The JavaScript to do this is: </p> <pre class="highlighted_code highlighted_code_jquery_javascript">$j('#primary_navigation li a').click(function() { loadPage( $j(this).attr('href')); return false; }); function loadPage( page ) { $j('#location_0').slideUp(300, function() { $j('#location_0').load( page + ' #location_0 > *', function() { $j('#location_0').slideDown(300);}); }); } </pre> <p> <br />You will need to add this in a script tag to your Viviti theme or as an external JavaScript file. YuAo's script is a bit more complicated and adds a loading indicator as well as dealing with url hash stuff so bookmarking and history works as well, you can check it out at <a href=""></a>. </p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2009-05-14:/entries/35020 Memcache Problems with Rails 2.3 and Litespeed or Passenger? 2009-05-14T00:11:00-07:00 2009-05-14T00:12:55-07:00 <p>This week was a fun week of code spelunking. </p> <p>Turns out, ActionController::Session::MemCacheStore runs through all the servers and checks to see if they are alive when the session store is first setup from your environment.rb. This causes it to connect to the Memcache server(s) and if you use a web server like <a href="">Litespeed </a>or <a href="">Passenger </a>that fork from a parent process, you end up with multiple processes sharing the same socket.</p> <p>This is bad because then your child processes trip over each other in their eagerness to get data from Memcache. This can result in all kinds of strange behavior from errors to having incorrect data returned. The Passenger documentation does a good job of example of <a href="">showing an explanation of the problem</a> (and a solution for those of you using Passenger).</p> <p>The easiest way to solve this is to ensure your parent process disconnects from Memcache before the fork occurs. In Litespeed this means editing RailsRunner.rb - specifically adding a call to <strong>reset </strong>to RailsRunner.rb, right before the existing call to <strong>ActiveRecord::Base.clear_active_connections!</strong> (which is there for the same reason). To do this we have to create a Memcache client and tell Rails to use it, otherwise there is no clean way to access the instance it will create.</p> <p>In environment.rb:</p> <pre class="highlighted_code highlighted_code_ruby"># you might have to require 'memcache' SESSION_CACHE = MemCache.new( 'myserver.com:11211', :namespace => 'myapp_session' ) config.action_controller.session_store = :mem_cache_store config.action_controller.session = { :cache => SESSION_CACHE, :key => '_my_app_session', :expires => 1.hour}</pre> <p> <br />Then in Litespeeds RailsRunner.rb add <strong>SESSION_CACHE.reset</strong> right after where it does it's <strong>ActiveRecord::Base.clear_active_connections! </strong><br /><br />This should do the trick. Monkey patching the MemCacheStore to reset after doing the alive? check (or not doing the check) should also fix it.</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2009-04-29:/entries/34755 Rails 2.3 count with named scope 2009-04-29T11:22:00-07:00 2009-04-29T11:22:54-07:00 <p>There is a <a href="">known bug </a>in Rails 2.3 that is worth being aware of, count no longer works on anything using named_scope. There are some patches and a fix available in the ticket there and it looks like it will be resolved in the next version... but for now, beware!</p> <p>also, I'm not sure when but somewhere between rails 2.1 and 2.3 they changed the (partialname)_counter back to it's long lost behaviour of the index starting at 0 (it was changed to 1 awhile ago, and is now back to 0). Please, make up your mind!</p> <p> </p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2009-04-29:/entries/34751 BC Single Transferable Vote (BC-STV) 2009-04-29T08:20:00-07:00 2009-04-29T08:23:33-07:00 <p>In 2005 we had a chance to change the way our electoral system works. It failed because when most people arrived to vote they didn't know what they were voting on. Even then, it was supported by 58% of the voters - but 60% or higher is required for it to pass. On may the 12th we get another chance at it, and this time there is a lot more information available. I highly recommend checking out the <a href="">stv.ca</a> site and get informed!</p> <p> For the lazy, the BC-STV is a system proposed by the <a href="">Citizens Assembly</a>, 141 members of the public drawn from the voters list. It's not a new or untested system, STV is used by a lot of other countries including Australia, New Zealand, Ireland, Northern Ireland, and Scotland. It's a system that will reduce the effects of "strategic voting" and bring a more fair representation into our parliamentary system. </p> <p> Spend some time before you vote, read the <a href="">Myths</a> and the <a href="">faqs</a>. Everyone always complains that the system doesn't work... Let's stop complaining and change it.</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2009-01-21:/entries/9352 Mid Island Web Workers Group 2009-01-21T11:57:00-08:00 2009-01-21T12:04:10-08:00 <p>Last night was the first meeting of the newly created Mid Island Web Workers Group at the <a href="">Longwood Brewpub</a> in Nanaimo. There were a lot of familiar faces as well as a bunch of new people, it was fun to meet some new people from the area. If anyone who reads this is living in the area, you should come to the next meeting! There is a group on facebook called 'Mid-Island Web Workers Users Group' you can join that has information on when meetings are, and I'm sure there will be a non-facebook site somewhere in the near future.</p> <p>The description of the group on facebook is 'A users group for people working with Web/Internet technologies in the mid Vancouver Island region.', It's been started and organized by <a href="">Jim Rutherford</a> and the focus is on getting together a group of people from all languages and aspects of internet tech - designers, programmers, etc. </p> <p>There is a newly created <a href="">google group</a> as well!</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-12-02:/entries/6512 Reality Check, Mr. Harper. 2008-12-02T10:41:00-08:00 2008-12-03T13:14:40-08:00 <p>I'm getting sick of people calling what's going on in Canada Undemocratic. I'm looking at you, Harper.</p> <p>What Harper does not seem to realize is that in the Canadian Parliamentary system, we do not vote for him, or his Government. We vote for local MP's who then we send to parliament. The Governor General, who is our head of state (that's right Harper, not you) then asks a party leader to form a Government. Her job is to ensure that our parliament works. If the party in power loses confidence of the Parliament, it is then her duty to dissolve the acting Government and call upon another leader to form a new Government that will work.</p> <p>This is not Undemocratic, it's simply how our system works. We elected a Parliament, and it's now her job to make sure a Government based off it works. If that means changing who is in charge, that's what she has to do. There is no coup here. The MP's that each Canadian elected are still going to be serving in the capacity they were elected for, that won't be changing.</p> <p>It's sad, and a little pathetic, that the Conservatives are resorting to <a href="">illegal recordings</a>, <a href="">propaganda</a> (Radio ads? comon, and who's paying for those?), <a href="">slander</a>, and <a href="">outright lies</a> to try to cling to power in a government where most of the Parliament does not agree with them. And then they have the arrogance to call the opposition (which for the record, is every single political party in Canada except the Conservatives) Undemocratic.</p> <p>What would be Undemocratic would be allowing a leader who has lost confidence of the Parliament to continue running the country. For a good interview about this, check out part 3 of <a href="">todays 'The Current'</a> (it's at the bottom).</p> <p>Don't let the door hit you on the way out, Mr. Harper. </p> <p>Maybe after you have more time on your hands you should do a little reading on how the Canadian Parlimentary system works.</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-12-01:/entries/6474 Viviti enters Open Beta 2008-12-01T17:31:00-08:00 2008-12-01T19:48:25-08:00 <p>We did it! Today marks the first day of open beta for <a href="">Viviti</a>, and we are pretty excited about it. Along with the open beta, <a href="">Shawn</a> did a great job on the new design for the front page so it looks pretty too. This is a personal milestone for all members of the team here as we've all put a lot into this project. <a href="">Dan</a> and <a href="">Tyler</a> have both worked tirelessly with me to get this out the door. Thanks to you both! Now we are on the home stretch to out of beta (no, we won't be in "beta" forever, this is actually a beta.).</p> <p>We still have lots to do, but we feel it has a solid enough feature set for most people to find useful, already surpasing a lot of our competition - and we still have a bunch more stuff before we drop the beta and start asking people for money (don't worry, we'll keep offering a free version!)</p> <p>If you've a blog and haven't played with Viviti yet, now's your chance - and we are always looking for <a href="">feedback</a>!</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-11-22:/entries/6006 Redesigned! 2008-11-22T21:57:00-08:00 2008-11-27T23:50:23-08:00 <p>I've redesigned my blog again! I'm always open to feedback so if anyone thinks I missed anything or finds anything broken, let me know.. I've got a few small tweaks I want to do, but I think I'm mostly done. This is the second design I've done of nullcreations.net since it was moved to <a href="">Viviti</a>, and this time it feels much more complete. It didn't take much time to get working once I was done the mockups in photoshop!</p> <p>I was also very pleased to not have to do anything special to make it work in Internet Explorer. I checked in IE7 after I was finished, experienced the impending-doom feeling in my stomach as it contacted the server, and then joy upon seeing it render everything pixel-perfect! It will probably get destroyed by IE6, but I don't care :D</p> <p>Now I have to go finish reorganizing the downstairs of my house, as I've been changing everything there, too. I think I need a new table, and a new TV :(</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-11-20:/entries/5954 Google SearchWiki 2008-11-20T21:13:00-08:00 2008-11-22T02:12:22-08:00 <p>It's been a long time since google has made any real noticable changes to their search engine, so i was a little suspicious when two little icons appeared beside my search results allowing me to promote or demote search results... Had some malicious software found it's way to my computer? </p> <p>A quick search eased my mind - no, it's not malicious software - instead it's a new feature Google has added called 'SearchWiki' that allows users to provide feedback to search results. After poking around a bit I've come to the conclusion that it's actually pretty neat. When you remove results that are not relevant, they won't re-appear on repeat searches. You can also see a list of all the results you have promoted or removed, which is handy if you accidentaly remove something you want back. </p> <p>There is an <a href="">article on timesonline.co.uk</a> with more information on it, or just login to your google account and go search for something. There is more to it than just promoting and removing results, so it's worth a quick read.</p> <p>Interestingly enough, Google also saw fit to release some newness to Gmail as well, in the form of <a href="">themes</a>.</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-11-17:/entries/5462 Simply Flickr library in ruby 2008-11-17T19:31:00-08:00 2008-11-22T21:03:35-08:00 <p>A long time ago, in a summer far, far away, I was working on <a href="">Flickr</a> integration in <a href="">Viviti</a> and found most of the ruby libraries I could find were for the old and now defunkt Flickr API. To solve this i created a very simple wrapper around their REST interface, and then fleshed it out a little bit to simplfy some of the more common things I needed to get done.</p> <p>If anyone is in a similar boat needing to interface with Flickr via ruby, feel free to check out the repo on github. It's not a proper gem yet, but one day i'll get that fixed. If anyone uses it and finds missing peices (I know there are a bunch, since there is lots of stuff you can do with Flickr that I haven't needed to do yet), please send me patches! I like patches!</p> <p>Usage is pretty simple: </p> <p> <pre class="highlighted_code highlighted_code_ruby">client = Flickr::Client.new( 'apikey' ) person = client.person( 'jerrett taylor' ) => #<Flickr::Person:0x11e5e14 ...> person.photosets.first.title => "Macro" person.photosets.first.photos => [#<Flickr::Photo:0x116ab10 ...></pre> Any call that you need to make that is not already wrapped can be directly made via Flickr::Client#request( method, args ), which will return hpricot. </p> <p>Anyways, the git repo is here: <a href="">simple-flickr.</a> Enjoy!</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-10-15:/entries/3992 40th Canadian Parliament 2008-10-15T09:15:00-07:00 2008-10-15T16:19:57-07:00 <p>Well, it's the next day and things are more or less as they were. The Conservatives still don't have a majority, the Bloc still holds almost all the seats in Quebec, and the Liberals are still the official opposition. </p> <p>So who won? In my opinion there were no real winners. Sure, there were small victories - the conservatives gained a few more seats and thus have a little more power, the NDP also gained some seats and and made history with their first seat in Quebec, and the green did very well in popular vote - but still have no seats. </p> <p>The real story here though was who lost, and I don't mean the Liberals even though they had their worst turnout in the history of their party. Who really lost was Canadians. Not because nothing changed, and not because the conservatives are still in power, but because we had record low voter turnout. Our loss was our own fault, and we have nobody to blame but ourselves. </p> <p>I still can't understand how almost half the population of Canada can't be bothered to get out and vote. The arguments of not knowing enough about each party are garbage, especially these days where their platforms are so easily viewable online, on TV, radio, or even just talking to other people. While our system is not perfect, we'll never have a true representation of Canadian values in the Parliament if people can't be bothered to be a part of the system.</p> <p>This is an old and perhaps a boring, cliche argument, but it still pisses me off, and it's still a problem. Drop the apathy people, and do your civic duty next time we are sent to the polls. Stop bitching about how we are in another election and instead take pride in the fact that we have a system that allows for us to be in another election, and make a difference. Yes, every vote does count. </p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-09-19:/entries/3404 Fixing OpenSSL Certificates on OS X 2008-09-19T04:08:00-07:00 2009-02-10T15:31:01-08:00 <p>While trying to use OpenURI in Ruby to connect to a https site, I kept running into an error with certificates - <em>OpenSSL::SSL::SSLError: certificate verify failed. </em></p> <p>After some digging around on google I found <a href="">a lot</a> of <a href="">solutions</a>, but all of them involved manually specifying a path to a cert file or disabling certificate verification entirely, <a href="">or both</a>. For the code I'm writing the linux boxes it's deployed on don't have this problem so I wasn't happy with either solution. Adding extra code and cert files to the codebase just for my dev box, or skipping verification both seemed like Bad Ideas™.</p> <p>Turns out the solution is actually pretty simple. The problem is that while openssl is included by OS X complete with the standard Root Certificates that are needed for this to work, they are only available via Keychain. This means Ruby has no access to these certificates, and can't verify any SSL certificates.</p> <p>To fix it, open "Keychain Access" and select all the certificates under "System Roots", then export them (right click) to a cert.pem file and put it in: <strong><br />/System/Library/OpenSSL</strong></p> <p>That's it.</p> <p>If you want, you could probably grab <a href="">the list from haxx.se</a> instead, which is extracted from mozilla.</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-08-22:/entries/2874 Back from Greece 2008-08-22T18:43:10-07:00 2008-11-17T20:08:46-08:00 <p>I'm back!</p> <p>My absence for the last 4 weeks was due to a much needed vacation, most of which was spent sailing <a href="">down the Pelleponese</a> with my father on the gaff-rigged schooner he built. Part vacation, part training so I'll be able to sail Iliopotissa without help, we had quite the adventure.</p> <p style="text-align: center;"><img src='/files/resized/15448/480;480;52595f5664eb13173b5d4e681ee3ef25790c2fa9.jpg' alt='Image'/></p> <p style="text-align: left;">In the 3 weeks sailing we managed to pack everything in - We had weather ranging from nearly flat calm to 6-7<a href="">bf</a>, engine problems made it very much a sailing trip, and I got to spend some good time getting acquainted with hanging from the top of the masts working on the rigging. We ran into people in the middle of knowhere who had heard about the boat and her trip from Canada to Greece, and when we got back to the house in Aegina 150 cubic meters of water was missing (and still is). I even managed to somehow find myself dancing at 6am. I blame the Bacardi.</p> <p style="text-align: left;">We went to some fantastic places in the trip, my favorites being Kyparisi and Astros. In Astros we arrived just in time for a festival in an outdoor amphitheater with traditional Greek music and dancing. Kyparisi has some of the most beautiful beaches I've seen (and yet, somehow, quiet), although the bay isn't that well protected for boats.</p> <p style="text-align: center;"> <img src="" alt="Image" /></p> <p style="text-align: left;">I'm back to work on Monday now, and am looking forward to getting back at it - even though I'm already missing Greece and the lounging around in the sun on a boat. I took a bunch of pictures, for those curious I've been uploading them to <a href="">a photoset</a> on my Flickr account. Likely I'll be adding a few more over the next few days as I dig through my memory card!</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-07-16:/entries/1939 Explosions, Fires, and Birds 2008-07-16T22:54:38-07:00 2008-09-26T11:09:34-07:00 <p>Monday was planned to be our release day of a new version of <a href="">Viviti</a>, but it was not to be. An <a href="">underground explosion and fire</a> took down a chunk of the power in downtown Vancouver, and while the water cooled generators worked, they stopped working in a hurry when the Vancouver Fire Department tapped into the water supply to put out the fire. Oops.</p> <p>Tuesday we were getting ready to release in the afternoon when a bird flew into a transformer a block or two away from our offices, killing power to the building. Fortunately, our office buildings have nothing to do with our servers so this was mostly just a minor inconvenience, but pushed us to Wednesday.</p> <p>Today we managed to make it through the entire day without anything exploding or catching fire, so we've <a href="">pushed up the new build</a>!</p> <p> </p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-06-18:/entries/1019 New bike! 2008-06-18T19:18:10-07:00 2008-11-17T20:08:45-08:00 <p>After riding a supermarket giveaway bike (which proudly displayed the MJB Coffee logo on it's frame) for a couple years I finally gave in and bought a new bike. Perhaps more accurately, the bike gave out and I replaced it!</p> <div style="text-align: center"><img src='/files/resized/4070/480;480;8cfdf6a93b9d95b7dfb84f3375fecb239ddc3bae.jpg' alt=''/><br /><br /></div> <div style="text-align: center"><img src='/files/resized/4071/480;480;0c60ff1f94ea56f403a592516875848c445f4dde.jpg' alt=''/></div> .</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-06-14:/entries/908 The Canadian DMCA 2008-06-14T12:07:09-07:00 2008-09-26T11:09:33-07:00 <p>The Conservatives have finally introduced the <a href="">DMCA</a>, resulting in somewhat predictable <a href="">outrage from Canadians</a>. For those not familiar with what this means if it's passed, I urge you to read some of <a href="">Micheal Geist's</a> recent posts - he breaks down <a href="">the fine print</a>. He's also posted a nice list of <a href="">30 things you can do</a> to make a difference.</p> <p>For those that don't know why this is bad, It's similar to the American DMCA - It has privacy concerns and removes a lot of consumer rights. It adds a few as well, to be fair, but the problems need to be addressed. For more information I suggest you read Geist's <a href="">summary of the problems</a> with the bill.</p> <p>The easiest thing you can do is contact your MP - Call them, mail them, email them, meet them in person - whatever you are able to do, and ask them to oppose the bill. For the lazy, onlinerights.ca has a <a href="">simple form</a> you can use to select your MP and send them an email. They do read these, and it only takes a minute or two to send.</p> <p>Keep in mind, we do have a minority government, and we can be heard.</p> <p>There are good things in the bill, and there is nothing wrong with updating copyright laws in Canada. They are out of date, and out of step with the world we live in. We just need to make sure the Government hears our concerns, and modifies the bill to help protect consumer rights and privacy as well as the rights of content producers.</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-06-02:/entries/817 Serialized hashes with partial_updates in Rails 2.1 2008-06-02T19:55:00-07:00 2008-11-22T21:11:26-08:00 <p>In Rails 2.1, they added <a href="">partial updates</a> - which is a great idea and a long time coming. This makes ActiveRecord only updates the parts of a model that has actually changed, and also gives you the ability to see if a field (or a record) has changed since retrieving it from the database. (via <a href="">model.changed?, model.attribute_changed?, and friends</a>)</p> <p>There is a gotcha though, If you are using <a href="">serialized</a> attributes it won't trigger the changed flag unless you assign to it - so if you are doing something like:</p> <pre class="highlighted_code highlighted_code_ruby">model.foo[:bar] = true</pre> <p>ActiveRecord will not realize you have changed anything and it won't get saved. You can get around this by doing something like:</p> <pre class="highlighted_code highlighted_code_ruby">model.foo = model.foo.merge( :bar => true )</pre> <p><strong>Update</strong>: You can also tell ActiveRecord it has changed, by calling model.foo_will_change!</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-05-20:/entries/89 New layout, now using Viviti 2008-05-20T19:44:41-07:00 2008-09-26T11:09:32-07:00 <p>I've regressed back to the late 90's in terms of design for my personal blog, and once again have a black-based design. Not sure how long it will last, but for now I like it!</p> <p>Also, in the name of '<a href="'s_own_dog_food">eating your own dogfood</a>' I am now using <a href="">Viviti</a> for this blog. Previously it was custom blog software, which I'm not missing in the least. Now when I add new features to my blog, other people can enjoy them as well!</p> <p>My photography has gone missing from this site as anyone who may be looking for it will notice, I've decided along with going back to black, to also go back to splitting my blog and photography into two separate sites and I haven't put that up yet. Soon!</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-04-03:/entries/74 Nanaimo movie listings 2008-04-03T11:34:26-07:00 2008-09-26T11:09:32-07:00 <p>A friend was complaining that there was nowhere he could find to get an RSS listing of movie showtimes, so I made a little script using Hpricot to parse forreel.com. Hopefully they don't mind!</p> <p>Fr those of you locally, feel free to use it: <a href=""></a></p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> tag:nullcreations.net,2008-03-13:/entries/73 Viviti Launched! 2008-03-13T01:32:56-07:00 2008-09-26T11:09:32-07:00 <p>Well we've finally launched <a href="">Viviti</a> - It's a web based/hosted CMS system that's component based. Fully themable using normal HTML, and all editable in browser (drag-n-drop to move stuff around, etc.).</p> <p>As it is now, it supports adding custom blocks (text or html blocks), rss feeds, blogs, and a few other components. It's pretty neat, and as we add more components will become more and more flexible.</p> <p>Currently it's still in a invite only phase, as we work through some final touches - but we will start sending out invites to people who request a beta key soon.</p><div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/>
|
http://feeds.feedburner.com/Nullcreations
|
crawl-002
|
en
|
refinedweb
|
Journal tools |
Personal search form |
My account |
Bookmark |
Search:
...prize winning book
oregon zipcodes
minnesota business listing
millibar pressure
remington police ... web site design
american appraisal chicago business valuation
oregon police record
... york psychiatry depression test
arizona travel center
minnesota equipment rental
one ... high school hockey association
oregon business licensing
minnesota workforce center duluth
...
... sports
viola williams
european male
uk business travel statistics
panasonic co uk lumix
...very short haircuts for women
applied business technology
windows web hosting australia
1997 ... saddle tac
rp 2001
albanian alphabet
chicago public high school basketball
boob flashing ...ozarks marine
brunette short hair
west chicago real estate
selteco flash designer 5...
... download
example positive statement
arizona road travel
samantha power biography
race horse owner... purpose wall
perfect teeth dental spa chicago
license plates for front of cars...population density distribution
air travel tip jamaica business travel tips lagos
deportation due...new jersey aquarium stores
electrical service business development consultant
def hbo jam poetry...
... movie the game
westin city center chicago
valentine aim expression
egg experiment science ...door latch
william pitt union
kirksville business
dust mite anatomy
outdoor team games...oregon ducks apparel
air travel tip jamaica business travel tips kumamoto
goldensun2 cheats...olakes butter
good earth lighting
insulin travel case
contribute global volcano warming
hotel...
... cell plant typical
florida vacation connection
business quote zig ziglar
new york city blizzard 2003
heated driving range chicago
illinois credit union league
georgia stalking ... police
barometric lowest pressure recorded
in business travel
osha competent person
minnesota ... approved wrist watches
washingtonpost.com travel
led zeppelin physical graffiti track ...
...2002 screaming eagle
rack mount computers
business object oriented paradigm proposal
westside medical...zone engineer
shelters for women in chicago
boyz 2 man motownphilly
sharp cell...architectural hardware
starting a psychic reading business book
caleb engstrom
avalon country club...ticket
1995 vw gti
officiating classes
business travel weekly
suare dance
hakata ...
... hills quotes
bill swad chevrolet
switzerland travel and tourism
buffalo legend soldier
county...lse
galactic civilisations keygen
analyst become business changing
atlantic city ticket broker
alabaster...zx9
halloween funny stuff
tribune books chicago the firm by grisham
lolapalooza 1992... up
styrofoam building materials
uk business travel
secretary of health and ...
... map missions
maryland criminal defense attorneys
chicago heights ill
blank venn diagram printout
small business consultancy
blanket merrow stitch
border decorative ... of san pietro
air travel tip jamaica business travel tips kishinev
adobe photoshop ...
assabet valley
1996 fleetwood mallard trailer travel
applied biotechnology inc
international atomic energy...
...jobs high paying
real estate appraisal chicago
barbie chillin scene
2002 porsche boxter ... visited
security questionaire
air travel tip jamaica business travel tips teresina
airline atlantic ...from historical line space through time travel
louisburg highschool
1994 ls mercury sable...nurse practical
denison site myspace.com
business computer consulting guide it services.info...
...minnesota dog breeders
american agriculturist magazine
business buying in renting
motorola cable modem ...georgia income tax mileage allowance for business travel
minnesota senate districts
american express ... locations
blue planet biome
buy chicago house quick
long range aircraft of... care
hurley clothes
better borrow business
american egypt generation international new ...
Accommodations
Agent Chicago In Travel
Chicago Business Travel Hotel
Chicago
Business Chicago Solution Travel
Chicago Convention
Business Traveler
Chicago Entertainment
Business Traveler Workout
Chicago Hotel Travel
American Business Traveler
Chicago Illinois
Business Travel
Chicago Tourism
Business Travel Planner
Chicago Travel Deal
Business Travel Luggage
Chicago Travel Times
Business Travel Incentive Italy
City Of Chicago
Result Page:
1
2
3
4
5
6
7
8
9
for Chicago Business Travel
|
http://www.ljseek.com/Chicago-Business-Travel_s4Zp1.html
|
crawl-002
|
en
|
refinedweb
|
.
Say, we are writing a module for storing user accounts to memory and an XML file interchangeably at runtime.
This requirement implies two different “storage” classes: one for memory storage and the other for XML file storage.
public class BaseAccountStorage { public virtual void Save(Account account) { // Left blank intentionally } } public class MemoryAccountStorage : BaseAccountStorage { public override void Save(Account account) { // Saves the account to memory } } public class XmlAccountStorage : BaseAccountStorage { public override void Save(Account account) { // Saves the account to an XML file } }
To save an account, the following code would be written.
... public void SaveAccount(string destination, Account account) { BaseAccountStorage storage; if ("memory".Equals(destination)) { storage = new MemoryAccountStorage(); } else if ("xml".Equals(destination)) { storage = new XmlAccountStorage(); } storage.Save(account); } ...
Introducing the Factory Design Pattern
Although this code works, it is not very flexible. For each new type of storage, we need to create an extra class and add a conditional statement to the
SaveAccount method. This requires changes to both the storage library code and the client code using them.
To end this inconvenience, we create a class that is specialised inproducing storage objects of a specified type. Such a class is called a factory class and follows the Factory Design Pattern.
SIDENOTE: Factory Design Pattern
In real life, a factory is a highly specialised building fitted with machinery designed for the production of a unique product.
In object-oriented programming, the factory class is specialised in instantiating objects of a specific class.
Applying the Factory design pattern, we create the
AccountStorageFactory class.
public class AccountStorageFactory { string type; public AccountStorageFactory(string type) { this.type = type; } public BaseAccountStorage GetStorage() { BaseAccountStorage storage; if ("memory".Equals(type)) { storage = new MemoryAccountStorage(); } else if ("xml".Equals(type)) { storage = new XmlAccountStorage(); } return storage; } }
To use this class, we create an instance, passing the type of storage we want to the constructor. Then, we call the
GetStorage method to obtain the storage object.
We change the client code accordingly.
... public void SaveAccount(string type, Account account) { AccountStorageFactory f = new AccountStorageFactory(type); BaseAccountStorage storage = f.GetStorage(); storage.Save(account); } ...
We can already see the benefit of this approach. The client code does not have to concern itself with choosing which storage object to create; instead, it delegates this task to the
AccountStorageFactory class.
If we need to have new storage types, we only have to create the appropriate sub-classes of
BaseAccountStorage and modify the
AccountStorageFactory.GetStorage class.
But, there is still one serious flaw in this design: we cannot be sure that a new storage class created by someone else will provide a
Save method as expected by the client code. In other words, the extensibility of our solution is not assured.
Introducing the interface
Our basic definition of the interface at the beginning of this article states that it specifies what methods a class should expose. Therefore, we can use interfaces to address this issue.
SIDENOTE: Interface
If you recall from Computer 101, an interface is the means by which a user interacts with the computer. It can either be a physical device, for example, a keyboard, or it can be a software, for example, the command prompt. We also have programmatic interfaces, such as the .NET Framework.
In OOP, interface refers to the public methods of a class that can be called from client code.
We start by defining an
IAccountStorage interface.
public interface IAccountStorage { void Save(Account account); }
Notice the keyword
interface.
Also notice that the
Save method does not contain any code. This makes perfect sense, considering that an interface does nothing more than specifying what methods be present in sub-classes; it does not concern itself with how those methods are implemented. And, no accessibility modifier is specified for the
Save method, as the methods defined in an interface are implicitly
public.
SIDENOTE: Implementation
When a class inherits from an interface, we say that the class implements that interface. Sometimes, the class is said to be an implementation of the interface.
In Java, the keyword implements makes this clear. For example:
public class MemoryAccountStorage implements IAccountStorage {
...
}
Now that we have an interface, we modify our storage classes to inherit from it.
public class MemoryAccountStorage : IAccountStorage { public void Save(Account account) { // Stores the account in memory } } public class XmlAccountStorage : IAccountStorage { public void Save(Account account) { // Stores the account to an XML file } }
Note that if these classes do not contain the
Save methods as
public, the code will not compile.
We need to modify the
AccountStorageFactory class to return the new
IAccountStorage mapping from the
GetStorage method.
public class AccountStorageFactory { string type; public AccountStorageFactory(string type) { this.type = type; } public IAccountStorage GetStorage() { IAccountStorage storage; if ("memory".Equals(type)) { storage = new MemoryAccountStorage(); } else if ("xml".Equals(type)) { storage = new XmlAccountStorage(); } return storage; } }
From now on, any class inheriting from
IAccountStorage is assured to be a valid storage class for saving user accounts.
The client code also requires a slight change to accommodate the
IAccountStorage interface.
... public void SaveAccount(string type, Account account) { AccountStorageFactory f = new AccountStorageFactory(type); IAccountStorage storage = f.GetStorage(); storage.Save(account); } ...
At this point, our storage infrastructure for accounts is completed. But, we may want to make a more generic storage factory to produce storage objects for saving other types of objects, for example, contact details.
As you may have guessed, the use of interfaces is part of the solution once again. To be precise, we need a common ancestor from which all storage classes will be derived regardless of what objects they are designed to save.
This top-most interface is
IStorage.
public interface IStorage { }
We modify our
IAccountStorage to inherit from
IStorage.
public interface IAccountStorage : IStorage { void Save(Account account); }
Let’s also add another hypothetical interface that will specify the requirement for storage classes responsible for saving contact details.
public interface IContactStorage : IStorage { void Save(Contact contact); }
Then, the implementation.
public class XmlContactStorage : IContactStorage { public void Save(Contact contact) { // Saves the contact to an XML file file } }
Perhaps the absence of methods in the
IStorage interface puzzles you. This interface is what is known as a marker interface. It does nothing other than mark the type of interfaces and classes that are derived from it. It allows us to have a very generic factory class that creates objects from its sub-classes.
public class StorageFactory { string type; public StorageFactory(string type) { this.type = type; } public IStorage GetStorage() { // Left blank intentionally } }
Our solution is not yet extensible enough if we still need conditional statements to determine what classes to instantiate. To fix this, we need a mapping of what “class” corresponds to what “type”.
So, we refine
StorageFactory.
public class StorageFactory { private Dictionary<string, Type> mapping; public StorageFactory(Dictionary<string, Type> mapping) { this.mapping = mapping; } public IStorage GetStorage(string name) { IStorage storage = null; if (mapping.ContainsKey(name)) { Type type = mapping[name]; storage = (IStorage) Activator.CreateInstance(type); } return storage; } }
There is quite a bit to digest here.
First, note that
Type does not mean the same thing as the
type variable in the
AccountStorageFactory class. In this case,
Type is a .NET Framework class that represents the type of an object.
The other thing to note is, we have made our factory more flexible. Instead of specialising in the production of only one type of storage classes, it can now produce different types (for account storage, for contact details storage, etc.) Actually, the
StorageFactory can produce any storage class that implements the
IStorage interface.
Then, there is a
Dictionary object that holds the name-type mapping.
Finally, the
GetStorage method itself has changed to instantiate objects on the fly by using the
Activator.CreateInstance method. We will not go into the details of how that is done, but it suffices to know that the method allows us to create an instance of a given type. In this case, the
Type that is instantiated is the one corresponding to
name.
The
StorageFactory class makes the
AccountStorageFactory class obsolete since it can create different storage classes for different types of objects, including both
Account and
Contact objects.
Let’s rewrite our client code to take advantage of this new factory class.
... StorageFactory factory; public void Initialise() { Dictionary<string, Type> mapping = new Dictionary<string, Type>(); mapping.Add("account", typeof(MemoryAccountStorage)); mapping.Add("contact", typeof(XmlContactStorage)); factory = new StorageFactory(mapping); } public void SaveAccount(Account account) { IAccountStorage storage = (IAccountStorage) factory.GetStorage("account"); storage.Save(account); } public void SaveContact(Contact contact) { IContactStorage storage = (IContactStorage) factory.GetStorage("contact"); storage.Save(contact); } ...
When the application is initialised, we define a mapping of storage name versus the implementation class. In this example, accounts are saved to memory storage, and contacts are saved to XML file storage, so we map “account” to
MemoryAccountStorage, and “contact” to
XmlContactStorage. We then create our factory, passing to it the mapping definitions.
Then, in the
SaveAccount and
SaveContact methods, we only have to pass the name of the storage we want to use to the
GetStorage method, which returns the appropriate storage object.
All this just works thanks to the magic of interfaces. The
StorageFactory.GetStorage method knows how to create
IStorage implementations; therefore, any class that has
IStorage up in its inheritance tree (as do
MemoryAccountStorage and
XmlContactStorage) can be instantiated from that method.
This concludes the tutorial on the factory design pattern and interfaces and how they can be harnessed to create extensible and robust application.
Eddy.
2 Comments
RSS feed for comments on this post. TrackBack URI
Very nice article :)
Comment by Joel Wan — Tuesday, 31 July 2007 10:25 GMT #
[...] In my previous post, I described how to use the Factory Design Pattern and interfaces to create a generic class that instantiate storage objects at run-time as specified in the configuration file of an application. [...]
Pingback by Eddy Young » Abstract factory design pattern — Sunday, 5 August 2007 13:57 GMT #
|
http://m.mowser.com/web/priscimon.com%2Fblog%2F2007%2F07%2F25%2Ffactory-design-pattern-and-interfaces%2F
|
crawl-002
|
en
|
refinedweb
|
tag:blogger.com,1999:blog-89182482008-05-06T01:36:15.301-07:00Jim RoosJim RoosBlogger69125tag:blogger.com,1999:blog-8918248.post-37218415751341565792008-05-06T01:29:00.000-07:002008-05-06T01:36:15.329-07:00Come to ScrumOk, I should seriously be asleep by now. Especially considering I have a two-day meeting starting tomorrow at 9:00 AM in Napa. But, I wanted to point to this <a href="">interesting video</a> featuring Ken Schwaber one of the co-creators of Scrum.<br /><br />I've used Scrum both at Microsoft and Symantec and I love it. Is it a cult? Sure it is. And the Scrum purist can drive you mad! But as Schwaber says repeatedly in this video, it's a fantastic tool for transparency. <br /><br />If you want to know where your project stands at all times, consider Scrum. If you're happy living in the dark knowing that when the tough time come around you can just get yourself moved onto a different project, by all means try something else.<img src="" height="1" width="1"/>Jim Roos of Yahoos!As long as I'm talking about rescinded buyout offers, I guess I should mention Yahoo! No doubt the shareholder lawsuit is already being drafted. Despite the fact that Jerry Yang and company are convinced the stock in undervalued, I don't expect them to use any of the company's $2 billion cash to buy back shares. Instead, expect them to cling to that money.<br /><br />Bringing back Jerry was probably a mistake. Let's face it Mr. Yang, you're no Steve Jobs.<br /><br />Let me also say what a brilliant move this could have been for Microsoft. There are two steps to being successful on the Internet:<br /><br /><b>Step 1.</b> <br />Build Web sites that people want to visit and use (Helps to start with search)<br /><br /><b>Step 2.</b> <br />Build an ad platform that serves up market, down market, and everything in between, and that offers real value to customers<br /><br />Microsoft has pretty much failed on both fronts. A Yahoo! acquisition would have represented some progress on Step 1.<img src="" height="1" width="1"/>Jim Roos of America and CountrywideMonths ago, Bank of America agreed to purchase Countrywide for what amount to $7.16 a share. Pretty much everyone knows that's never going to happen and Countrywide's stock hasn't traded anywhere near that level in months.<br /><br />Last week, Bank of America issued a curious statement that there was "no assurance that any of the mortgage lender's outstanding debt would be redeemed, assumed, or guaranteed." The BofA offer exchanges each CFC share for some fraction of a BofA share. Now how exactly do you cast off billions in bad debt and still leave shareholders with anything?<br /><br />Ask Bear Stearns.<br /><br />No one took the bait last week. Expect BofA to start playing hardball soon. It will start when they lower their bid. That won't be enough, of course, because Countrywide is worth less than nothing. Seriously. LESS than zero. So they could lower their bid to $1/share and doubt Countrywide could refuse it.<br /><br />It won't be before BofA rescinds their bid entirely that you'll be asked to pony up, you know, for the sake of the economy. National interest, right? But that's never been used to justify a crime before, has it?<img src="" height="1" width="1"/>Jim Roos StearnsA couple months ago I predicted that the word "subprime" would be dropped from the phrase "subprime mortgage crisis." I was right, but I never predicted that the word "mortgage" would also be dropped. What we are now experiencing is just a "crisis."<br /><br />Two days ago, Bear Stearns CEO Alan Schwartz appeared on CNBC to say "<span style="font-style:italic;">We don't see any pressure on our liquidity, let alone a liquidity crisis.</span>" Today, the 86-year-old institution came as close to failing as any investment bank since the Great Depression.<br /><br />I'll restrain myself from giving my full opinion of Mr. Schwartz. Suffice it to say, I'd be fairly embarrassed if I were him.<img src="" height="1" width="1"/>Jim Roos Predictions<ul><br /><li>"Option-ARM" will be the new "subprime" and the word "subprime" will be dropped from the phrase "subprime mortgage crisis." Everything I said that made me look crazy in 2005 will make me look like a genius in 2008.</li><br /><li>Northern Californians will continue to insist they've got Southern California beat. Southern Californians will spend exactly zero time thinking about Northern California.</li><br /><li>Somewhere, a software development team will begin a total rewrite of a failed project. The setback will have brought them none of the humility they'd need in order to do the job right. </li><br /><li>After less than two hours of labor, my nephew will be born and he will be <i>awesome</i>!</li><br /><li>I will continue a lucky streak stretching back so far I can hardly remember when it began.</li><br /></ul><img src="" height="1" width="1"/>Jim Roos Acquires Vontu<img src="" style="float: left; padding-right:2em; padding-bottom:1em;"><span style="font-style:italic;">"Symantec Corp.<br /><br />Data loss prevention solutions help organizations."</span><img src="" height="1" width="1"/>Jim Roos biggest news in Technology this week was Microsoft's $240 million investment in Facebook. Microsoft's 1.6% stake in the company marked Facebook at a valuation of $15,000,000,000. <br /><br />The wire was filled with storied about Facebook's apparent $15 billion valuation, but none that saw this transaction for what it was. For Microsoft, this is not any kind of investment in Facebook. This is an advertising partnership. The $240 million is simply a one-time payment to Facebook that has been structured to be tax free. <br /><br />My advice for anyone considering a job at Facebook is to run. This deal just destroyed the value of any new stock options at least until they do another round of financing at a substantially lower valuation. Considering the checking account is flush with $240 million, I wouldn't expect that to happen anytime soon. In other words, no one has any incentive to accept a job at Facebook for the foreseeable future.<br /><br />Anyone who thinks Facebook is worth $15 billion, please contact me; I have a blog for sale. (Not to mention a few San Francisco landmarks)<img src="" height="1" width="1"/>Jim Roos, the Xbox is coming up with the dreaded red ring of death. I guess it's off to the service center. This probably means a few weeks without GOW. Perhaps I'll try the outdoors.<br /><br /><center><img src=""></center><img src="" height="1" width="1"/>Jim Roos WayfarerEarlier this year, Ray-Ban re-released the Wayfarer, the iconic sunglasses made famous by the Blues Brothers and Risky Business. Yesterday, I bought my own pair of these distinctive trapezoidal frames that scream unstable dangerousness. This officially makes me cooler than you.<br /><center><img src=""></center><img src="" height="1" width="1"/>Jim Roos Messaging and AT&T WirelessIt's been nearly four weeks since I picked up the Samsung Blackjack and switched to AT&T wireless. I have to say, I am every bit as enamored with this device as I was the day I brought it home. I am, however, somewhat less impressed with AT&T Wireless. earlier this week, I received my first bill, complete with some 5 pages documenting each and every instant message I sent from the device, each apparently charged against my account as a "message" equivalent to an SMS or MMS message. Thankfully, my account comes replete with 1500 such messages, but you'd be surprised how many of those you can use up using the built in IM client.<br /><br />Thankfully, there are alternatives. The Web-based messenger beta, available at <a href="">mobile.live.com</a> provides a reasonable facsimile of the instant messaging experience. You wind up having to manually refresh the page to check for updates, but if all you're trying to do is login and have a quick exchange with a buddy, this solution works pretty well. And it comes with the added bonus of actually supporting emoticons, something the client application that ships with the Blackjack does not. I have to warn you, it's not clear to me whether you can actually escape AT&T's watchful eye using this app. When you login using the Web-based messenger, you will still be reported to other users as being logged in from a mobile device along with the warning that you may be charged for usage. <br /><br />My new best friend is <a href="">Fring</a>, which is really billed as a mobile VoIP solution. It does a reasonably good job of allowing you to make VoIP calls over Skype or to VoIP equipped instant messenger clients. Unfortunately, your caller's voice will be playing out of the external speakers. You'll have no trouble hearing it, unfortunately, neither will anyone around you.<br /><br />Personally, I've been using Fring exclusively as an IM client. It has a couple of advantages over the IM client that ships with the Blackjack. First, it supports a number of IM services including Windows Live Messenger, Google Talk, ICQ, and others. This app provides a unified contact list and you are logged into all of your IM services simultaneously. Even better, Fring provides tabbed conversations making it a lot easier to manage multiple concurrent conversations. Unfortunately, there appears to be no way to turn off the audible alerts that play when a new message is received. Arg.<img src="" height="1" width="1"/>Jim Roos YouTube DebateThe last several years in politics have taught us all some important lessons. Unfortunately, they haven't given the folks at CNN enough forsight to know a bad idea when they see it. Ladies and gentlemen, I implore you, let us promise never again to hold any kind of <a href="">YouTube debates</a>. <br /><br /><center><img src=""></center><img src="" height="1" width="1"/>Jim Roos BlackjackI've been thinking about a smart phone for awhile now. I guess it was the release of the iPhone that finally pushed me over the edge, but the iPhone's $500 price seems positively ridiculous considering you can pick up the nifty Samsung Blackjack for just $100 after mail-in rebate.<br /><br /><center><img src="" style="padding: 10px;" /></center><br />I love this phone! Some advice for anyone considering the Blackjack:<br /><ul><li>The phone still ships with Windows Mobile 5.0. Upgrade to Windows Mobile 6.0 before you do anything else. That'll give you HTML email as well as mobile versions of Word, Excel, and PowerPoint. And, it looks a lot nicer too. The upgrade re-images your phone, so don't spend too much time setting things up before you get to it. There's no official release of WM6 for the Blackjack yet, but if you sniff around the Web long enough, you'll find it.</li><li>Next, pickup the Google Maps and Live Search applications for Windows Mobile. These alone are worth the price of the phone.</li><li>The mobile version of IE does a decent job, but if you want to see desktop-style renderings of Web pages, pickup both mobile versions of Opera. Opera Mini is a Java-based application that actually gives you a mouse cursor. It renders Web sites on a remote server and sends them down to the phone as images. Not the best solution, IMHO, but it an interesting idea. Also, try Opera for Windows Mobile Smartphones, which is a native application that can actually handle some AJAX sites. Neither of these browsers are as good as Safari for iPhone, but they're both worth having around.</li></ul><img src="" height="1" width="1"/>Jim Roos CreepPlease tell us, would you like to edit this item, move this item, delete this item, zoom to street, zoom to city, zoom to region, drive from, drive to, or send in an e-mail?<br /><br /><center><img src=""></center><img src="" height="1" width="1"/>Jim Roos 7-Eleven across the street from Microsoft is one of just twelve stores in North America that have been <a href="">converted into Kwik-E-Marts</a> this month to promote the upcoming Simpsons movie. Dennis, Justin and I walked over this afternoon. I picked up some Buzz cola, a Squishee, and the latest issue of Radioactive Man!<br /> <br /><center><img src=""></center><img src="" height="1" width="1"/>Jim Roos the iPhoneJust got back from the Apple Store, and I have to admit, the iPhone makes some impressive strides in phone UI. I found the on-screen keyboard to be highly usable and I think, with practice, it would be a great text input device. <br /><br /><b>One important word of warning:</b> if you drop by the Apple store to test out the device, the network connectivity will seem very snappy. Web pages will download quickly, Google Maps will be responsive, and Youtube videos will start playing immediatly. I suspect that's because the devices are picking up the store's WIFI connection. AT&T's Edge network won't provide nearly the thoughput you'll experience while testing out the phone.<img src="" height="1" width="1"/>Jim Roos for WindowsApple has announced that <a href="">Safari is available for Windows</a>. Also, it seems building iPhone applications means writing JavaScript for Safari. All of this should help build more broad based support for Safari now that you don't need a Mac to build a Safari compatible Web site.<img src="" height="1" width="1"/>Jim Roos AutoCompleteHere I've used my Easy Ajax framework to build AJAX autocomplete. To start, add a little html to build the input field and a container for the suggestions when they appear:<br /><div style="margin-left: 30px"><code ><br /><input type="text" id="input" style="width: 250px"/><br/><br /><div style="position: absolute;"><br /> <easy:ajax</easy:ajax><br /></div><br /></code></div><br /><code>AutoComplete.aspx</code> accepts a single parameter named <code>prefix</code> and uses it to generate a response that looks something like this:<br /><br /><div style="margin-left: 30px"><code><div class="autocomplete"><br /> <div>Jim Reed</div><br /> <div>Jim Van</div><br /> <div>Jim Zaner</div><br /></div></code></div><br />A little bit of CSS will make sure everything looks right:<br /><br /><div style="margin-left: 30px"><code>#suggestions<br />{<br /> position: relative;<br />}<br /><br />.autocomplete<br />{<br /> background: #D8EAFF;<br /> border: solid 1px #55A6C8;<br /> width: 200px;<br />}<br /><br />.autocomplete DIV<br />{<br /> padding: 2px 4px 2px 4px;<br />}</code></div><br />And to kick things off, include <code>EasyAjax.js</code> and <code>AutoComplete.js</code> and instantiate <code>AutoComplete</code> as follows:<br /><br /><div style="margin-left: 30px"><code><script type="text/javascript" src="EasyAjax.js" ></script><br /><script type="text/javascript" src="AutoComplete.js"></script><br /><br /><script type="text/javascript"><br /> new AutoComplete(<br /> document.getElementById("input"), <br /> document.getElementById("suggestions")<br /> );<br /></script></code></div><br />And here's what it looks like in action:<br /><br /><center><iframe style="border-style:none;border-width:0px;" frameborder=0 scrolling=no height=150 width=300</iframe></center><br /><b>Note: </b>Using arrow keys and hitting enter seems to work fine in Firefox, but the design of the fool Live Search box I have integrated into the top of my page prevents this feature from working correctly in IE. To view on a page that is free of poorly design Windows Live code, please visit my <a href="">auto complete demo page</a><img src="" height="1" width="1"/>Jim Roos Live Hotmail ShipsThe efforts of hundreds of people and millions of beta testers came to fruition this weekend as we launched Windows Live Hotmail. Starting this morning, new sign-ups will get their choice of either the Hotmail-like "classic" experience, or the Web 2.0-like "full" experience. <br /><br />CNET has an interesting article asking if the full version was <a href="">Too Hotmail to Handle</a> which feature Mike Schackwitz describing how the classic version came to be. Also, checkout out the <a href="">announcement on the Mailcall Blog</a> and look for pictures of some of the people who made it happen.<img src="" height="1" width="1"/>Jim Roos AJAX RequestsOne issue people often overlook when building their first AJAX application surrounds multiple concurrent requests. Your AJAX application may display some non-deterministic behavior if you aren't careful to queue your XMLHttp requests.<br /><br />Queuing requests is especially important in Internet Explorer as too many simultaneous request can actually cause IE to barf. Of course, we generally want to bundle requests together and avoid making concurrent requests. But no matter how you design your application, in the end you can't control how quickly your users clicks around within the UI.<br /><br />The following demonstrates why queuing is important. In Firefox, you'll notice clicking the <b>No Queue</b> button leads to highly indeterminate results. Under Internet Explorer, the situation is worse. Firing off 50 simultaneous XMLHttp requests in IE can cause the browser to lock up. Queuing requests so that the next doesn't start until the first has finished fixes both of these problems.<br /><br /><center><iframe style="border-style:none;border-width:0px;" frameborder=0 scrolling=no height=370 width=620</iframe></center><img src="" height="1" width="1"/>Jim Roos Made EasyIt's easy to over-engineer AJAX sites. Many of the AJAX frameworks available look a lot like RPC or even CORBA-type solutions, complete with marshaling of complex data types (almost as if JavaScript were a strongly typed language). While there are lots of reasons someone might want such a sophisticated framework, there are also plenty of problems that could be solved using a more basic solutions. <br /><br />In many cases, all a developer is looking to do is grab a piece of HTML and drop it into the DOM somewhere. Here I've created a very easy mechanism for doing just that. To prepare a page to use my EasyAjax framework, modify your HTML tag to include the <code>easy</code> XML namespace and reference EasyAjax.js. Once you've done that, you can use the <code><easy:ajax></code> tag to define AJAX-updateable regions within your page.<br /><br /><center><a href=""><img style="vertical-align:middle;" src="">Download EasyAjax.zip</a></center><br />The simplest EasyAjax page looks like the following:<br /><div style="margin-left:30px"><code><br /><html <span >xmlns:</script><br /> <span ><easy:ajax</span><br /> <span >Initial Content</span><br /> <span ></easy:ajax></span><br /> </body><br /></html><br /></code></div><br />When first loaded, the <code><easy:ajax></code> tag contains the string "Intial Content". Shortly there after, this content is replaced with whatever HTML content is generated by <code>somepage.aspx</code>. The page then automatically polls somepage.aspx every 5000 ms.<br /><br />The effect is similar to what you see on a lot of business news sites today that provide continuously updating quotes inline with the text of the articles. To demonstrate, I've used the framework to create a clock. The clock displays current time according to the server hosting my site and uses <a href=""></a> to get the current time:<br /><div style="margin-left:30px"><code><br /><img src="earth.gif"><br /><div style="float:right;"><br /> <div><br /> Current Time<br /> </div><br /> <div><br /> <easy:ajax<br /> 00:00:00<br /> </easy:ajax><br /> </div><br /></div><br /></code></div><br />And here's the result:<br /><br /><center><iframe style="border-style:none;border-width:0px;" frameborder=0 scrolling=no height=115 width=300</iframe></center><br />There are times when we'd rather update the page based on some user action rather than polling the server. In those cases, we omit the <code>interval</code> attribute and call <code>reload()</code> on the <code><easy:ajax></code> element. For example, we can modify the example above so that instead of polling the server, we only update when the user clicks on the time:<br /><div style="margin-left:30px"><code style="margin-left:15px"><br /><easy:ajax <span style="font-weight: bold;background:yellow;"><br /> 00:00:00<br /></easy:ajax><br /></code></div><br />Of course, we can update the page based on any user action. For example, if we rather update the page when the user clicks on the Earth image, we make the following modifications:<br /><div style="margin-left:30px"><code><br /><img src="earth.gif" <span style="font-weight: bold;background:yellow;"><br /> <div><br /> Current Time<br /> </div><br /> <div><br /> <easy:ajax <span style="font-weight: bold;background:yellow;"><br /> 00:00:00<br /> </easy:ajax><br /> </div><br /></div><br /></code></div><br />We can also use this framework to create more sophisticated features. Consider Google's search suggestion system which presents you with a continuously updating list of search suggestions with each key you press. In order to implement something like this, we'll need some facility to post data with our request. To accomplish this, the <code>reload()</code> function accepts, as a parameter, a JavaScript object representing name value pairs for the post data:<br /><div style="margin-left:30px"><code><br />var params = {<br /> firstname : document.forms[0].firstname.value,<br /> lastname : document.forms[0].lastname.value<br /> };<br /><br />document.getElementById("myelement").reload(params);<br /></code></div><br />Note that the framework will only make a POST request if parameters are provided. Otherwise, it will generate a GET request and append a nonce.<img src="" height="1" width="1"/>Jim Roos Docs & Spreadsheets & ...With the Web 2.0 conference going on this week in San Francisco, we might have expected a significant announcement from Google, and they haven't disappointed. (BTW, why am I not off on that boondoggle, hmm?) Eric Schmidt announced a new addition to Google's growing suite of Web-based productivity products: presentations. <br /><br />At the same time, Google has announced it acquired Tonic Systems, a company who's entire Web site has been yanked from the Internet and replaced with an <a href=>FAQ on the acquisition</a>. Cached versions of Tonic's Web site describe the company as offering "a library that provides a 100% Java API to read, create and manipulate PowerPoint presentations," which seems to be a positively frightening preview of what Google presentations might be like. <br /><br />I'm a long time Java developer and a big fan of the language and I suppose time will tell whether Google intends to use this API client-side or server-side, but anyone who has ever used the Internet knows the horror of that dreaded coffee cup icon and the utterly ridiculous wait for the JRE to crank up. <br /><br />Whether Google presentations makes use of Java applets or not, Eric Schmidt's assertion that Google presentations is not an attempt to compete with Microsoft's PowerPoint is untrue and Google's acquisition of Tonic Systems makes that clear.<img src="" height="1" width="1"/>Jim Roos Fools<div style="border: solid 1px #ddd; padding: 10px;"><strong>Update:</strong><br />Since it's after April 1st, it's probably worth noting that I did not, in fact, move to Australia. :)</div><br />People who know me know I'm accustomed to moving. I moved nine times as child and attended three high schools. I've continued the pattern as an adult, moving from Texas to California and back again to Texas, and back again to California. But in all that moving I've never lived outside the United States.<br /><br />I've finally decided to take a chance. I'm moving to Australia in the morning. It's all very spur of the moment and there's a lot of people in my life who I haven't even had the chance to tell yet. Somehow I managed to arrange for my things to be packed up and stored today as I prepare to leave everything behind and start fresh down under.<br /><br />To celebrate my decision, I've created an Australian version of my map game:<br /><center><iframe style="border-style:none;border-width:0px;" frameborder=0 scrolling=no height=390 width=500</iframe></center><br />If you're struggling to remember the names of the seven Australian states and territories, here's a list:<br /><ul><li>New South Wales</li><li>Northern Territory</li><li>Queensland</li><li>South Australia</li><li>Tasmania</li><li>Victoria</li><li>Western Australia</li></ul><img src="" height="1" width="1"/>Jim Roos Wars 30th Anniversary MailboxesStar Wars themed mailboxes began appearing all over San Francisco this week. This one is right across the street from me at the corner of 4th and Townsend. Frankly, I'd be afraid to drop a letter in one of these; it's only a matter of time before they start showing up on Ebay. Rumor has it the mailboxes are intended to promote a set of Star Wars 30th anniversary stamps to be release at the end of the month.<br /><br /><center><img src=""></center><img src="" height="1" width="1"/>Jim Roos Bug in Internet ExplorerImagine the saddest you've ever felt; that's what the last 12 hours of my work life have been like. I've spent most of the last two days investigating a situation in which closing the browser window would cause IE to continuously spawn new windows. Since we're dealing with a "Web 2.0" application containing thousands of lines of Javascript, the first instinct is to scrub the code for <code>window.open()</code>. But that revealed nothing.<br /><br />Instead, I've discovered a bizarre bug in the way IE handles framesets. Turns out, if a frameset frame contains a url containing an anchor, and the browser is closed before that particular frame has completed downloading, IE will begin endlessly spawning new windows.<br /><br />The lesson?, avoid anything looking like this:<br /><br /><div style="margin-left:3em;"><code><frameset><br /> <span style="margin-left:3em"><frame src="somepage.aspx<span style="font-weight: bold;background:yellow;">#anchor</span>"></frame></span><br /></frameset></code></div><img src="" height="1" width="1"/>Jim Roos MapHere I've built a reusuable state map widget. The <code>Map</code> class generates a grayed-out map of the United States and allows you a to programtically show states. You might use this to generate maps of, say, states that went for Bush during the 2004 election or to generate an animated timeline of when each state joined the union.<br /><br />Below, I've built a demo that challenges you to name all 50 states in less than three minutes. Good Luck!<center><iframe style="border-style:none;border-width:0px;" frameborder=0 scrolling=no height=350 width=500</iframe></center><br />If you'd like to use the map widget for your own purposes, download the source below:<br /><br /><center><a href=""><img style="vertical-align:middle;" src="">Download map.zip</a></center><img src="" height="1" width="1"/>Jim Roos
|
http://feeds.feedburner.com/JimRoos
|
crawl-002
|
en
|
refinedweb
|
My first F# application for AutoCAD
I.
What is the advantage compare with C#? Is it necessary to learn this new language?
Posted by: Spring | November 02, 2007 at 09:25 PM
There's certainly no need to learn it: it's another tool that may be of use to developers working in certain domains. The Wikipedia link in the article should be of some use in understanding the basic concepts of functional programming languages, otherwise this page has a quite good explanation/comparison.
Kean
Posted by: Kean | November 02, 2007 at 11:11 PM
Kean,
Will the F# open an opportunity to Autodesk replaces the AutoLISP language?
F# is a functional programming as AutoLISP so it would be easier to create a cross-language conversion tool to migrate AutoLISP code to F#?
Maybe Autodesk is planning to create its own .NET based AutoLISP...say A# ? :)
Please keep posting information about F# x AutoCAD.
Regards,
Posted by: Fernando Malard | November 04, 2007 at 09:20 PM
There are no plans to replace AutoLISP with F# (and I don't see us having any in my lifetime): the F# language is likely to be of use to developers integrating math-intensive/simulation technologies with AutoCAD (and other, yet-to-be-determined-by-me-at-least uses), but it is not an easy leap, even from LISP.
I'd like to gather information on what we might do inside AutoCAD to make F# a more natural environment for development, but only to provide tighter integration of an additional language option.
Kean
Posted by: Kean | November 04, 2007 at 11:09 PM
NA
Posted by: Ram Raja Hamal | November 06, 2007 at 07:41 AM
You've been kicked (a good thing) - Trackback from CadKicks.com
Posted by: CadKicks.com | November 10, 2007 at 03:46 PM
With Lisp one could use a function from a text string in a database (for example "(setq QTY (* 2.5 WIDTH))" to calculate part specific quantities for BOM:s. I haven't found a way to do this in vb(.net), perhaps F# could do the trick?
Posted by: Thomas | November 16, 2007 at 06:56 AM
Hi Thomas,
Yes - one of the features of LISP is the (eval) function.
It doesn't appeat to be native functionality in either C# or VB.NET, but it does appear to be possible to implement:
It remains to be seen whether either technique can be used to call through AutoCAD's managed API (the first one seems likely, I haven't really looked into the implementation of the second).
The equivalent in F# appears to be the quotations mechanism.
Regards,
Kean
Posted by: Kean | November 16, 2007 at 09:11 AM
DO YOU HAVE ANY DevTV Introduction to REALDWG Programming ?
Posted by: ALBERTO BENITEZ | November 28, 2007 at 07:13 PM
It's in the works and should be available sometime next year.
Kean
Posted by: Kean | November 28, 2007 at 08:03 PM
Are there any extra dependencies on the F#-compiled dll as compared to a C#-compiled one?
I can run this example fine on my machine, but my colleague cannot get the TEST command after he NETLOADs the dll.
Would you have any guess why?
It's always tricky to debug things that work on one machine and not the other, when there's no obvious difference in the setup. He doesn't have F# installed, but I'm assuming that's not necessary?
Any ideas would be greatly appreciated.
Thanks.
Posted by: namin | March 15, 2008 at 06:31 AM
While F# code does compile down to IL, it does depend on certain new namespaces implemented in assemblies that are installed by with the F# implementation. So you will (for now) need to install F# on machines running the code, until it becomes a more fully integrated part of Visual Studio and probably the .NET Framework.
Regards,
Kean
Posted by: Kean | March 15, 2008 at 03:41 PM
Just for completeness, I should mention that it's possible to remove the dependency of an F# application to the F# assemblies by compiling with the --standalone flag. This has the disadvantage of adding about 1Mb to the application as it statistically links the F# library.
Posted by: namin | April 11, 2008 at 08:08 AM
|
http://through-the-interface.typepad.com/through_the_interface/2007/10/my-first-f-appl.html
|
crawl-002
|
en
|
refinedweb
|
Adobe
You can create a Java servlet that invokes an Adobe LiveCycle ES long-lived or short-lived process. An advantage of using a Java servlet is that you can write the return value of the process to a client web browser. That is, a Java servlet can be used as the link between a LiveCycle ES process that returns a form and a client web browser.
Assume, for example, that a LiveCycle ES process returns an interactive form (after the process performs other business tasks, such as retrieving customer data from an enterprise database and populating some of the form fields with data). Using a Java servlet, you can write the form to a client web browser so that a customer can enter data into the form. After populating the form with data, the web user clicks a submit button located on the form to send information back to the Java servlet, where the data can be retrieved and processed. For example, the data can be sent to another LiveCycle ES process (see Figure 1).
Figure 1. A web application invoking a LiveCycle ES process and sending the results to a web browser.
This document describes how to create a Java servlet that invokes a LiveCycle ES short-lived process named GetMortgageForm. For more information about invoking processes, see the "Invoking LiveCycle ES Processes" section in Programming with LiveCycle ES.
The following illustration shows the GetMortgageForm process (see Figure 2).
Figure 2. A LiveCycle ES process that returns an interactive form.
Note: This document does not describe how to create a process by using Adobe LiveCycle Workbench ES. (For information, see Workbench ES Help.)
The following table describes the steps in this diagram.
This interactive loan form is rendered by the GetMortgageForm process (see Figure 3).
Figure 3. An interactive form.
Note: This document describes how to use the Invocation API to invoke a LiveCycle ES process. It is recommended that you are familiar with the Invocation API before you follow along with this document. (See "Invoking LiveCycle ES Processes" in Programming with LiveCycle ES.)
To create a Java servlet that invokes a LiveCycle ES process, perform the following steps:
Note: Some of these steps depend on the J2EE application on which LiveCycle ES is deployed. For example, the method you use to deploy a WAR file depends on the J2EE application server that you are using. This document assumes that LiveCycle ES is deployed on JBoss®.
The first step to create a Java servlet that can invoke a LiveCycle ES process is to create a new web project. The Java IDE that this document is based on is Eclipse 3.3. Using the Eclipse IDE, create a web project and add the required JAR files to your project. Finally, add an HTML page named index.html and a Java servlet to your project.
The following list specifies the JAR files that you must add to your web project:
For the location of these JAR files, see "Including LiveCycle ES Java library files" in Programming with LiveCycle ES.
Note:
The adobe-forms-client.jar file is required because the process returns a
FormsResult object,
which is defined in this JAR file.
To create a web project:
InvokeMortgageProcessfor the name of your project and then click Finish.
To add required JAR files to your project:
InvokeMortgageProcessproject and select Properties.
To add a Java servlet to your project:
Invoke Mortgage Processproject and select New > Other.
GetFormfor the name of the servlet and then click Finish.
To add an HTML page to your project:
Invoke Mortgage Processproject and select New > Other.
index.htmlfor the file name and then click Finish.
You
create Java application logic that invokes the GetMortgageForm process from
within the Java servlet. To invoke a LiveCycle ES process, such as the
GetMortgageForm process, use
the Invocation API. The following code shows the syntax of the GetForm Java
Servlet:
public class GetForm Invocation API code here to invoke the LiveCycle ES Process }
Normally,
you would not place client code within a Java servlet's
doGet or
doPost methods. A better programming
practice is to place this code within a separate class, instantiate the class
from within the
doPost method (or
doGet method), and call the
appropriate methods. However, for code brevity, the code examples in this
section are kept to a minimum and code examples are placed in the
doPost method.
When invoking a LiveCycle ES process, you must prepare
input values that are required by the process. This step is specific to the
process. That is, if the process requires four input values, you must prepare
four input values to pass to the process. The
GetMortgageForm process
requires two input parameters.
When using the Java Invocation API to invoke a process,
pass required input values by using a
java.util.HashMap object. For each parameter to pass, invoke the
java.util.HashMap object's
put method and specify the name-value pair that is required by
the process. You must specify the exact name of the parameter that belongs to
the process and a corresponding value. For example, if the name of the input
parameter is
custId and requires string value, you can create a String
variable to pass to the process.
To invoke a LiveCycle ES process by using the Invocation API, perform the following tasks:
doPostmethod, create a
ServiceClientFactoryobject that contains connection properties. (See "Setting connection properties" in Programming with LiveCycle ES.)
ServiceClientobject by using its constructor and passing the
ServiceClientFactoryobject. A
ServiceClientobject lets you invoke a service operation. It handles tasks such as locating, dispatching, and routing invocation requests
java.util.HashMapobject by using its constructor.
java.util.HashMapobject's put method for each input parameter to pass to the long-lived process. The
GetMortgageFormprocess requires two string input values: a custom identifier value and the form name.
Create an
InvocationRequest object by invoking the
ServiceClientFactory object's
createInvocationRequest method and passing the following values:
GetMortgageForm.
invoke.
java.util.HashMapobject that contains the parameter values that the service operation requires.
Booleanvalue that specifies true, which creates a synchronous request (used to invoke a short-lived operation).
Note: The
difference between invoking a long-lived process and a short-lived process is
that a short-lived process can be invoked by passing the value true and the
fourth parameter of the
createInvocationRequest method. Passing the value
true creates a synchronous request.
ServiceClientobject's
invokemethod and passing the
InvocationRequestobject. The
invokemethod returns an
InvocationReponseobject.
InvocationReponseobject's
getOutputParametermethod and passing a string value that specifies the name of the output parameter. The name of the output parameter for the
GetMortgageFormprocess is
RenderedForm. This is a process variable and its data type is
FormsResult. Cast the
getOutputParametermethod's return value to
FormResult.
com.adobe.idp.Documentobject by invoking the
FormsResultobject ‘s
getOutputContentmethod. The
FormResultobject contains the interactive form returned by the process.
com.adobe.idp.Documentobject by invoking its
getContentTypemethod.
javax.servlet.http.HttpServletResponseobject's content type by invoking its
setContentTypemethod and passing the content type of the
com.adobe.idp.Documentobject.
javax.servlet.ServletOutputStreamobject that is used to write the form data stream to the client web browser by invoking the
javax.servlet.http.HttpServletResponseobject's
getOutputStreammethod.
java.io.InputStreamobject by invoking the
com.adobe.idp.Documentobject's
getInputStreammethod.
InputStreamobject. Invoke the
InputStreamobject's
availablemethod to obtain the size of the
InputStreamobject.
InputStreamobject's
readmethod and passing the byte array as an argument.
javax.servlet.ServletOutputStreamobject's
writemethod to send the form data stream to the client web browser. Pass the byte array to the
writemethod.
The following code example represents the Java servlet that
invokes the
GetMortgageForm short-lived process.
/* * This Java Servlet uses the following JAR files * 1. adobe-forms-client.jar * 2. adobe-livecycle-client.jar * 3. adobe-usermanager-client.jar * 4. adobe-utilities.jar * * These JAR files are located in the following path: * <install directory>/Adobe/LiveCycle8/LiveCycle_ES_SDK/client-libs * * For complete details about the location of these JAR files, * see "Including LiveCycle ES library files" in * Programming with LiveCycle ES */ import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.adobe.idp.Document; import com.adobe.idp.dsc.clientsdk.ServiceClientFactory; import com.adobe.idp.dsc.clientsdk.ServiceClient; import com.adobe.idp.dsc.clientsdk.ServiceClientFactoryProperties; import com.adobe.idp.dsc.InvocationRequest; import com.adobe.idp.dsc.InvocationResponse; import com.adobe.livecycle.formsservice.client.FormsResult; /** * This Java servlet invokes the LiveCycle ES GetMortgageForm short-lived process */ public class GetForm extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L; public GetForm() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ String custId = null; String formName = null; //Get the values submitted from the web page custId = request.getParameter("custID"); formName = request.getParameter("formName"); / ServiceClient object ServiceClient myServiceClient = myFactory.getServiceClient(); //Create a Map object to store the parameter value Map params = new HashMap(); //Populate the Map object with a parameter value //required to invoke the GetMortgageForm process params.put("formName", formName); params.put("custId", custId); //Create an InvocationRequest object InvocationRequest esRequest = myFactory.createInvocationRequest( "GetMortgageForm", //Specify the LiveCycle ES process name "invoke", //Specify the operation name params, //Specify input values true); //Create a synchronous request //Send the invocation request to the process and //get back an invocation response object InvocationResponse esResponse = myServiceClient.invoke(esRequest); FormsResult formOut = (FormsResult)esResponse.getOutputParameter("RenderedForm"); //Create a Document object that stores form data Document myData = formOut.getOutputContent(); //Get the content type of the response and //set the HttpServletResponse object's content type String contentType = myData.getContentType(); response.setContentType(contentType); //Create a ServletOutputStream object ServletOutputStream oOutput = response.getOutputStream(); //Create an InputStream object InputStream inputStream = myData.getInputStream(); //Get the size of the InputStream object int size = inputStream.available(); //Create and populate a byte array byte[] data = new byte[size]; inputStream.read(data); //Write the data stream to the web browser oOutput.write(data); }catch (Exception e) { e.printStackTrace(); } } }
The index.html web page provides an
entry point to the Java servlet and invokes the
GetMortgage process. This web page is a basic
HTML form that contains two text boxes and a submit button. The names of the
text boxes are custID
and formName.
When the user clicks the submit button, form data is posted to the GetForm Java
servlet.
The following illustration shows the contents of the HTML page (see Figure 4).
Figure 4. An interactive web page.
The Java servlet captures the data that is posted from the HTML page by using the following Java code:
//Get the values submitted from the web page String custId = request.getParameter("custID"); String formName = request.getParameter("formName");
The following HTML code is located in the index.html file that was created during setup of the development environment.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> <html xmlns=""> <head> <meta http- <title>Web Application</title> </head> <body> <form name="form1" action="/InvokeMortgageProcess/GetForm" method="post"> <br> <label>Customer Id <input type="text" name="custID" id="custID" /></label> <br> <label>Form Name <select name="formName" id="formName"> <option>Mortgage Form</option> <option>Car Loan</option> <option>Personnal Loan</option> </select> </label> <br> <label>submit <input type="submit" name="submit" id="submit" value="submit" /> </label> </form> </body> </html>
To deploy the Java servlet that invokes the GetMortgageForm process, package your web application to a WAR file. Ensure that external JAR files that the component's business logic depends on, such as adobe-livecycle-client.jar and adobe-forms-client.jar, are also included in the WAR file.
The following illustration shows the Eclipse project's content, which is packaged to a WAR file (see Figure 5).
Figure 5. A web application project.
To package a web application to a WAR file:
InvokeMortgageProcessproject and select Export > WAR file.
InvokeMortgageProcessfor the name of the Java project.
InvokeMortgageProcessfor the file name, specify the location for your WAR file, and then click Finish.
You can deploy the WAR file to the J2EE application server on
which LiveCycle ES is deployed. After the WAR file is deployed, you can access
the HTML web page that invokes the
GetMortgageForm process by using a web browser.
To package a web application to a WAR file:
After you deploy the web application, you can test it by using a web browser. Assuming that you are using the same computer that is hosting LiveCycle ES, you can specify the following URL:
Enter a customer identifier value and a form name, and then click the submit button. If problems occur, see the J2EE application server's log file.
For more information about creating applications that invoke LiveCycle ES, see Programming with LiveCycle ES.
Scott Macdonald is a senior SDK technical writer at Adobe Systems with more than 10 years in the software industry working with Java, C/C++/C#, as well as other programming languages.
|
http://www.adobe.com/devnet/livecycle/articles/java_servlets.html
|
crawl-002
|
en
|
refinedweb
|
I have following module in _M01.ts:
export module _M01 {
export default class Foo {
constructor () {}
}
}
import Foo from "./_M01"; // error "./_M01" has no default export
You don't need the module wrapper around your class in _M01, so this will do what you want
_M01.ts:
export default class Foo { constructor () {} }
_M02.ts
import Foo from "./_M01"; //This works
There's more information here, but the TLDR versions is that you don't use the Module keyword anymore in TS. You can define a Namespace instead, however for what you need the simple example above is fine.
|
https://codedump.io/share/CjpcPKOKfm4x/1/typescript-can39t-resolve-exported-default-class
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Hi,
I'm trying to compare two text files (outputs from a database and corresponding spatial table in a GIS) to check for errors. Basically, i'm assuming that the output from the database is correct and any missing/repeat numbers in the spatial table will be errors and should be reported. I've written the part of the program that searches for a specific number in the spatial output and returns the errors, but i can't work out how to change the number it's searching for.
Here's what i've done so far:
#include <string> #include <fstream> #include <iostream> #include <stdlib.h> using namespace std; fstream DBinput("DB.txt", ios::in); fstream SPinput("SP.txt", ios::in); fstream output("Errors.txt", ios::out); int i = 0; string correct; string word; void count(void); void SPcompare(void); void main(void) { while(DBinput >> correct) { //////// Presumably this is where the 'find number to search for' part should come in //////// SPcompare(); } } void SPcompare(void) { while(SPinput >> word) { count(); } if(i == 0) output << "Error - '" << word << "' has no matches in spatial database" << '\n'; else if(i > 1) output << "Error - '" << word << "' has " << i << " matches in spatial database" << '\n'; } void count(void) { if(word == "5") i++; }
As you can see, so far it only searches for how many times the specific number 5 appears in the SP.text file.
What i'd like it to do is read the DB.txt file, find the first number to search for, then find out how many times it appears in SP.txt, then move on to the next number in DB and repeat until the end, generating a txt file output of all the errors. The SP.txt file has every number containted within inverted commas, and the DB.txt file has each number at the beginning of a new line follow by a lot of " delineated text/
Any help would be greatly appreciated, as would any 'you're making this a lot more complicated that it needs to be, here's how you can solve your problem in fifteen seconds' :)
P.S apologies for length
|
https://www.daniweb.com/programming/software-development/threads/9434/help-with-error-checking-code
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
NAME
Tcl_AddErrorInfo, Tcl_SetErrorCode, Tcl_PosixError - record information about errors
SYNOPSIS
#include <tcl.h>
Tcl_AddErrorInfo(interp, message)
Tcl_SetErrorCode(interp, element, element, ... (char *) NULL)
char *
Tcl_PosixError(interp)
ARGUMENTS
Tcl_Interp *interp (in) Interpreter in which to record information.
The errorInfo variable is gradually built up as an error unwinds through the nested operations. Each time an error code is returned to Tcl_Eval it calls the procedure Tcl_Add. Tcl_AddErrorInfo may be used for this purpose: its message argument contains an additional string to be appended to errorInfo. For example, the source command calls Tcl_AddErrorInfo to record the name of the file being processed and the line number on which the error occurred; for Tcl procedures, the procedure name and line number within the procedure are recorded, and so on. The best time to call Tcl_AddErrorInfo is just after Tcl_Eval has returned TCL_ERROR. In calling Tcl_AddErrorInfo, you may find it useful to use the errorLine field of the interpreter (see the Tcl_Interp manual entry for details).
The procedure Tcl_SetErrorCode is used to set the errorCode variable. Its element arguments give one or more strings to record in errorCode: each element will become one item of a properly-formed Tcl list stored in errorCode. Tcl_SetErrorCode is typically invoked just before returning an error. If an error is returned without calling Tcl_SetErrorCode then the Tcl interpreter automatically sets errorCode to NONE. interp->result.
It is important to call the procedures described here rather than setting errorInfo or errorCode directly with Tcl_SetVar. The reason for this is that the Tcl interpreter keeps information about whether these procedures have been called. For example, the first time Tcl_AppendResult is called for an error, it clears the existing value of errorInfo and adds the error message in interp-.
SEE ALSO
Tcl_Interp, Tcl_ResetResult, Tcl_SetErrno
KEYWORDS
error, stack, trace, variable
Table of Contents
|
http://www.ue.eti.pg.gda.pl/tcl/www/wtcltk/TclTkMan/tcl7.6b1/AddErrInfo.3.html
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Removing rows from TableModel
I'm currently learning Qt and I've found a Qt Address Book Example.
I would like to change some features but I've been struggling with the TableModel class.
This method used to work with a user interaction, the user clicks on a contact and then clicks the "Delete contact" button to delete the contact.
I'd like to implement instead a method that simply deletes all the entries in my TableModel table.
IpWidget.h
#ifndef IPWIDGET_H #define IPWIDGET_H #include "TableModel.h" #include <QItemSelection> #include <QTabWidget> class QSortFilterProxyModel; class QItemSelectionModel; class IpWidget : public QTabWidget { Q_OBJECT public: IpWidget(QWidget *parent = 0); void addEntry(QString name, QString address); void removeAllEntries(); signals: void selectionChanged (const QItemSelection &selected); private: void setupTabs(); TableModel *table; QSortFilterProxyModel *proxyModel; }; #endif // IPWIDGET_H
IpWidget.cpp
void IpWidget::addEntry(QString name, QString ip) { QList<QPair<QString, QString>> list = table->getList(); QPair<QString, QString> pair(name, ip); table->insertRows(0, 1, QModelIndex()); QModelIndex index = table->index(0, 0, QModelIndex()); table->setData(index, name, Qt::EditRole); index = table->index(0, 1, QModelIndex()); table->setData(index, ip, Qt::EditRole); } void IpWidget::removeEntry() { QTableView *temp = static_cast<QTableView*>(currentWidget()); QSortFilterProxyModel *proxy = static_cast<QSortFilterProxyModel*>(temp->model()); QItemSelectionModel *selectionModel = temp->selectionModel(); QModelIndexList indexes = selectionModel->selectedRows(); foreach (QModelIndex index, indexes) { int row = proxy->mapToSource(index).row(); table->removeRows(row, 1, QModelIndex()); } } void IpWidget::removeAllEntries() { table->removeRows(0, table->rowCount(QModelIndex()), QModelIndex()); }
I wrote this, but I'm not sure it's correct, could you guys clarify me this class ?
- SGaist Lifetime Qt Champion
Hi and welcome to devnet,
Just to be sure I understand your question correctly, are you asking us to review your code and explain it to you ?
@SGaist I said this code was coming from Qt Address Book Example. I've tried it, but I'd like to change some features.
By the way, i'm not sure to understand how the TableModel works. I tried to clear it but
table->removeRows(0, table->rowCount(QModelIndex()));
doesn't work. So yes, can you clarify me this example ?
table->removeRows(0, table->rowCount(QModelIndex()));
doesn't work. So yes, can you clarify me this example ?
What does "doesn't work" mean? Compile error? Runtime error? Not the behaviour you expected? ...
- What is your
table->editStrategy()? Docs state that only
OnManualSubmitallows mutliple-row deletion. And then you'll need a
submitAll().
- Check the return result of your
table->removeRows(), and
lastError()if that's
false.
- I think
table->clear()is a quick way of deleting all rows, though that may not affect what you are wanting to learn about.
I run through a Runtime Error ! I'm trying to fix it with your advice ! I believe the
table->clear()
method doesn't exist in TableMethod btw ;) Can you use
table->removeRows()
it if the table is empty ?
So tell us the runtime error! And/or check the return result +
lastError()!
clearmethod: what is your
TableModelderived from?
My
TableModelcomes from
QAbstractTableModel.
lastError() works only for SQL Databases right ? Which object is it stored in ?
Can't check the return of the function because I get a runtime error.
Here is the console output
Debugging starts
ASSERT: "last >= first" in file itemmodels\qabstractitemmodel.cpp, line 2743
Debugging has finished
@theo_ld
Yeah, I had assumed
QSqlTableModel....
ASSERT: "last >= first" in file itemmodels\qabstractitemmodel.cpp, line 2743
I would guess this is telling you that your start row number + number of rows >= last row in table.
So: look at value of
table->rowCount(QModelIndex()). Is it 0? In which case, if there are 0 rows, no, you cannot delete any rows from an empty table, even if you specify a count of 0 rows to delete. At a guess!
P.S.
Also,
QAbstractTableModelrequires you to subclass (
TableModel), and unless that has implemented
removeRows()is does nothing? You sure the example which did work did not use
removeRow()(note the spelling)?
@JNBarchan You might be right, so I added a condition and it doesn't runtime anymore.
Although, my user isn't visible at all in the graphical interface -_-.
Trying to fix this problem now :p
@theo_ld said in Removing rows from TableModel:
@JNBarchan You might be right, so I added a condition and it doesn't runtime anymore.
In that case, I'd suggest I was right... ;-)
This post is deleted!
|
https://forum.qt.io/topic/83792/removing-rows-from-tablemodel
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
following.
Basically this is my dimensional array project
i need to take my userNumber and add it to the array?
while looping i want to check the arrays with arrays[i] not sure if i did it right?
how to properly use a boolean searchArray?
import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.Scanner; //import public class DimensionalArrays { // instance variables - replace the example below with your own int[] userNumber = new int[5]; Scanner scan = new Scanner(System.in); your add method should do ONLY 1 thing add a number you can call that method many times BUT, you do not always want to add it to the array //add method ** gets a number as a parameter and adds to array public void add(int num) { int i = 0; while (i < 5) { num = num[i]; answers[i] = num; System.out.println(answers[i]); i = i +1; } } //for loop to search the array ** for (int i=0; i< array.length; i++){} then while looping over you gotta check the array with array[i] public static void main(String args[]){ //for loop to ask person to add digit to array for (int index = 0; index < userNumber.length; index++){ userNumbers[index]= i; //store number as value in array }
|
http://www.dreamincode.net/forums/topic/271016-java-one-dimensional-array-help/
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Putting this up to garner feedback for a possible SIP.
While AnyVal is a great tool and is widely used, there are developers who are unsatisfied with it as a method of writing wrapper types (also known as the newtype pattern) because of the associated runtime cost.
AnyVal
@S11001001 has written an article titled “The High Cost of AnyVal subclasses”, in which he goes through some of the issues (boxing and unboxing penalty, O(n) complexity for wrapping and unwrapping containers), and argues convincingly that contrary to popular belief, the issues are not caused by Scala’s targeting of the JVM.
Instead, these runtime costs are because of the need to incorporate:
support for isInstanceOf, “safe” casting, implementing interfaces, overriding AnyRef methods like toString, and the like.
support for isInstanceOf, “safe” casting, implementing interfaces, overriding AnyRef methods like toString, and the like.
Goal:
In terms of changes to the language, I think it could live along side AnyVal (e.g. we don’t necessarily need to get rid of AnyVal or change its behaviour). It might make sense to have it as a separate thing entirely, like newtype Label(s: String).
newtype Label(s: String)
@adriaanm @SethTisue @odersky @dragos Would you mind having a read through this SIP proposal? @lloydmeta, @non and I were thinking of putting it together and would like to get some early feedback on it. Perhaps we can discuss it in our next SIP meeting, too.
Even though we haven’t figured out yet the technical details of the proposal and how such a feature would be added to the language (and interact with others), @S11001001’s blog post goes into some of these details, which give hints on how it could be implemented. I recommend reading the blog post.
Also, we would like to get what the Community thinks about this feature. So please, do comment or thumbs up if you like the proposal.
I think this would be a great addition! I know @adriaanm has said he doesn’t like the current tag encoding, but as the article shows it works better than value classes for many of these applications.
My sense is that this SIP should be easier to put together than SIP-15 (Value Classes) because the encoding is much less complex:
Other than generalized anxiety over changing the language and spec, does anyone think this is a bad idea, or difficult?
As far as the API, I could imagine an annotation which changes the meaning of AnyVal or a new type to extend (e.g. AnyVal.NewType).
AnyVal.NewType
I wouldn’t be opposed to such a SIP. There are a few things that come to my mind, that should be carefully considered in the SIP:
newtype
newtype Int
j.l.Integer
asInstanceOf[Foo]
asInstanceOf[underlying of Foo]
isInstanceOf
Foo
classOf[Foo]
classTag[Foo]
Array[Foo]
If we are working with these types:
class Meter(val toDouble: Double) extends AnyVal
class IntOps(val toInt: Int) extends NewType
class MeterOps(val toMeter: Meter) extends NewType
Then I’d answer your questions as follows:
IntOps
Integer
Int
int
MeterOps
Meter
isInstanceOf[IntOps]
isInstanceOf[Int]
classOf[IntOps]
classTag[IntOps]
Array[IntOps]
Array[Int]
A SIP would require a better formal specification, but I think these are the right properties to want.
Because total erasure makes these things easier to reason about, I think that we can even allow newtypes of newtypes, but I haven’t fully worked through enough examples to be sure.
Why not use a Scalameta macro annotation and generate the same kind of code as in the blog post? This way the thing can live entirely in library and no language modifications are needed.
This is more flexible, as it could lend itself to user configuration/customization (like macro-based case classes would, a.k.a. data types à la carte). For example, it could be made to generate Scalaz-style subst functions.
subst
AFAICT, the only thing that currently cannot be achieved is to erase a newtype of a primitive type P not to Object but to P itself, so that the compiler can avoid boxing the primitive. That is, without having to use a <: P bound, which partially defeats the purpose.
P
Object
<: P
Therefore, I propose to only add to Scala an @erasureOf[T] checked annotation, that tells the compiler what an abstract type should erase to. For example:
@erasureOf[T]
class LabelAPI {
@erasureOf[Int]
type Label
}
val LabelImpl: LabelAPI = new LabelAPI {
// type Label = String // error: the erasure of String does not correspond to Int
type Label = Int
}
This way, Label is still completely distinct from Int as far as the type checker is concerned, but the erasure phase will turn it into Int and so it will be the same as Int throughout the rest of the compilation, allowing for unboxed usage and for the right bytecode signatures.
Label
Correct me if I’m wrong, but I think this would be relatively easy to add to the compiler, and thus to get accepted into the language, as compared to having a new stab at an AnyVal-like feature.
@LPTK I don’t think that proposal is a good substitute. My main concern with it is that it looks like “a compiler feature” rather than “a language feature”. It is an annotation that tweaks what the compiler should do when compiling a given piece of code, altering its semantics in non-obvious ways in the process, rather than properly defining semantics in the first place, and letting the compiler do whatever it takes to correctly implement those semantics.
Does it actually alter the semantics? At least on the JVM, I don’t see where the semantics would be different with and without the annotation (perhaps related to JVM integer interning and referential equality?).
My point was that, as the blog post shows, the language features required to do wrapper-free newtypes are already there. The only “missing” part is related to performance (not boxing primitive types). In other words, I think we need a compiler feature rather than a language feature.
Hey guys, yesterday I started to work on an implementation for this proposal, just a prototype to show how it should work. It’s not possible to use macros to implement the whole feature, so I’m implementing it with annotation macros (to avoid touching typer for simplicity) + a compiler plugin. I hope to finish it off soon to get the proof of concept out. Erik is working on the spec, so at some point we’ll put our work together. After that, if such proposal is numbered in the next SIP meeting, I’ll invest some of my free time to port the prototype to the compiler (Scalac, maybe Dotty too).
@LPTK With regard to your comment, note that the main goal of this proposal is to make newtypes available to the whole Scala community. That’s why I don’t want my prototype to become the official way of consuming this feature – I just want it to be a tool to test and make the process review faster. IMO, this is something that merits inclusion in the language, so far it seems technically better than value classes in Scalac.
That said, I don’t think @erasureOf is a good idea because it’s a very specific compiler feature to enable the creation of certain language features. Its main goal is to circumvent the limitations of existing extension mechanisms like macros. I don’t think we should add features to the compiler just to enable the creation of other language features, it brings complexity for nothing. It’s better to add fully-baked language features that do work, bring immediate value and can be widely used to solve problems that we experience in our day-to-day jobs.
@erasureOf
@LPTK @erasureOf does alter the semantics, because val x: Any = "hello"; x.asInstanceOf[Label] would succeed without @erasureOf[Int] but fail with @erasureOf[Int].
val x: Any = "hello"; x.asInstanceOf[Label]
@erasureOf[Int]
If it was a library, it could be included in the Scala Platform, which is designed for this purpose.
Nitpicking here, but @erasureOf is not to circumvent the limitations of macros. It actually has nothing to do with macros.
I agree it is rather ad-hoc. If there are really no other use for the annotation and all other things being equal, it’s probably better to go with a language feature. It just seems like more work to do the latter. On the other hand, if we found more uses for @erasureOf then my opinion may change, as it would enable the mantra from the Programming in Scala book mentioned in my first link: “Instead of providing all constructs you might ever need in one ‘perfectly complete’ language, Scala puts the tools for building such constructs into your hands”.
No, it’s not designed for this purpose. The compiler is designed for this purpose. The Scala Platform is opt-in. The point of this feature is to make it available by default.
It circumvents the fact that you cannot modify erasure with macros. Otherwise you wouldn’t need erasureOf.
erasureOf
And it does, to some extent (and way more than other programming languages). But I would say that erasureOf is borderline. There’s probably people in the community more entitled to discuss this than I am.
Are you sure? I’m not knowledgeable enough in the Scala compiler to know how type-checking affects asInstanceOf casts. I would have thought that at the end of the day, it would be equivalent to x.asInstanceOf[Int], which does not fail.
asInstanceOf
x.asInstanceOf[Int]
EDIT: never mind, I read too fast. It would indeed fail in one case and not the other. Shouldn’t asInstanceOf on an abstract type with no bounds at least yield a warning?
Hey folks, using SIP-15 as a template I did a quick pass in creating something we could potentially build a SIP out of:
I am sure there are typos, mistakes, and oversights, but hopefully this gives us a common basis of comparison. I just threw it up into a gist to make it easy to read, but we can move this into a repo or other shared environment if people think it’s useful to collaborate on it.
One thing to add – I chose to use the extends NewType syntax in the document to be clear that this is different from AnyVal but to preserve some continuity. In practice I don’t care what the name is, or if this is done with an extends X versus an annotation (or even new syntax).
extends NewType
extends X
Thanks for putting that up! I think it would be a good idea to put it up somewhere for collaboration
This already exists as a library as, including the macro annotation. It implements Stephen’s blog posts as well. Syntax is like:
@opaque type ArrayWrapper[A] = Array[A]
@translucent type Flags = Int
Where opaque types box like generics (never unless primitive) and translucent types are subtypes of the types they are newtypes over, with the advantage that primitives are not boxed unless in a generic context.
Thanks! That’s really great prior art!
I think this proposal is slightly more ambitious (or misguided, depending on your stance) in that it allows you to create things that look like methods on the new types (whereas if I understand correctly newts just provides a type member plus wrapping, unwrapping, and subst). But we should certainly make sure that the newtype classes here work at least as well as those defined via newts.
Though it should be mentioned that it would be really easy to extend newts and make it generate the appropriate method-providing implicit class from something like this:
@opaque class ArrayWrapper[A](val unwrap: Array[A]) {
/* method defs */
def size = unwrap.length
}
…and then extend it some more as the needs arise in the future, because it’s a library.
|
https://contributors.scala-lang.org/t/pre-sip-unboxed-wrapper-types/987
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Opened 6 years ago
Closed 6 years ago
#17540 closed Uncategorized (invalid)
Errors in 1.3 Writing your first Django app part 1 and 2 Ubuntu 11.10
Description
I recently tried to work through your tutorial for Django 1.3 on Ubuntu 11.10. The first error I found was in part 1 where the new app was added to installed apps and there is a missing comma ',':
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'polls' )
and should read:
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'polls', )
The second error was in part 2 in the section "Make the poll app modifiable in the admin". It has a misplaced 'models' in the first import and reads:
from polls.models import Poll from django.contrib import admin admin.site.register(Poll)
and should read:
from models import Poll from django.contrib import admin admin.site.register(Poll)
I believe the second issue could be also fixed by describing the expected project structure in the tutorial.
These errors were discovered when setting up a Django, mod_wsgi, apache configuration on Ubuntu 11.10
In the first case, the comma at the end is not required.
In the second case, doing "from polls.models import Poll" will work fine, and is definitely preferred over "from models import Poll" (which is using implicit relative imports, which are going away). It is likely your Python path has been incorrectly set up. The setup for 1.3 and earlier is a bit confusing due to Python path hacking that was done in those older versions of Django, but has now been corrected.
Tutorial 1 does indeed document what the project structure will look like.
|
https://code.djangoproject.com/ticket/17540
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Hi guys,
basically the idea here is at each step, I'm in a node and I branch to the left node ie i+1 and right node ie i+2.
Note: i stands for i'th step.
When i reaches n, then the branch returns 1. if i+1 is bigger than n then that branch is discarded.
Just like fib(n), this recursive call repeats a lot of these expensive calls so cache results of expensive computation for future lookup.
public class Solution { Map<String, Integer> stairs = new HashMap<String, Integer>(); public int climbStairs(int n) { stairs.put(n+","+n, 1); //This can be memoized without computation stairs.put((n+1)+","+n, 0); //This can be memoized without computation return recursiveClimb(0, n); } public int recursiveClimb(int start, int end){ if(stairs.get(start+","+end) != null) return stairs.get(start+","+end); int steps = recursiveClimb(start+1, end) + recursiveClimb(start+2, end); stairs.put(start+","+end, steps); //Dont forget to store the result of your computation return steps; } }
Happy hack!
|
https://discuss.leetcode.com/topic/5497/most-straight-forward-solution-using-memoization
|
CC-MAIN-2017-43
|
en
|
refinedweb
|
Search Discussions
- Some surprisingly wrong results (php 5.2.0): date and time seem not coherent: <?php // Date: Default timezone Europe/Berlin (which is CET) // date.timezone no value $basedate = strtotime("31 Dec 2007 ...
- Simple function that converts more than one <br ,<br/ ,<br / ... to a <p </p . Maybe it's useful for someone =) function br2p($string) { return preg_replace('#<p [\n\r\s]*?</p #m', '', '<p ...
- <?php function array_unique_FULL($array){ foreach($array as $k = $v){ if(is_array($v)){ $ret=F::array_unique_FULL(array_merge($ret,$v)); }else{ $ret[$k]=$v; } }//for return array_unique($ret); } ? ...
- Sometimes it is helpful to check for the existance of a file which might be found by using the include_path like in include("file_from_include_path.php"); A simple function iterates the include_path ...
- Updating internal's PHP timezone database (5.1.x and 5.2.x) ---- Server IP: 69.147.83.197 Probable Submitter: 200.234.208.27 ---- Manual Page -- ...
- This function could be useful to somebody if you want to insert an XML into another when building an XML from many different files. Note that you must specify a name for the node in which the child ...
- This is the fonction for PHP4 : function array_combine($arr1,$arr2) { $out = array(); foreach($arr1 as $key1 = $value1) { $out[$value1] = $arr2[$key1]; } return $out } ---- Server IP: 194.246.101.61 ...
- Check for duplicates in an array (as opposed to removing them): if (array_unique($array) != $array) { echo "Duplicate located in array."; } ---- Server IP: 69.147.83.197 Probable Submitter: ...
- Regarding cyberchrist at futura dot net's function. It makes an unnecessary array_merge(); the elements of $b that are merged with those of $a are immediately removed again by the array_diff(). The ...
- I've been working on a project for a while now, and for example in my DB handler I wanted to load var's to the objects late; However, without doing it manually on the object itself but through a ...
- A simple funtion to format american dollars. <? function formatMoney($money) { if($money<1) { $money='¢'.$money*100; } else { $dollars=intval($money); $cents=$money-$dollars; $cents=$cents*100; ...
- If you intend to pass a copy of an object to a function, then you should use 'clone' to create a copy explicity. In PHP5, objects appear to always be passed by reference (unlike PHP4), but this is ...
- I was wondering what was quicker: - return a boolean as soon I know it's value ('direct') or - save the boolean in a variable and return it at the function's end. <?php $times = 50000; function ...
- Don't forget that using callbacks in a class requires that you reference the object name in the callback like so: <?php $newArray = array_filter($array, array($this,"callback_function")); ? Where ...
- <?php $tmp_array = "123,232,141"; if (strval(intval($tmp_array)) == $tmp_array) { echo "'".intval($tmp_array)."' equals '$tmp_array'\n"; } else { echo "'".intval($tmp_array)."' does not equal ...
- the function posted is false, hier the correction: function rstrpos ($haystack, $needle, $offset) { $size = strlen ($haystack); $pos = strpos (strrev($haystack), strrev($needle), $size - $offset); if ...
- It should be noted that version_compare() considers 1 < 1.0 < 1.0.0 etc. I'm guessing this is due to the left-to-right nature of the algorithm. ---- Server IP: 212.63.193.10 Probable Submitter: ...
- You should probably try to avoid changing any of the items in the args array. Consider this example: ---------- function a(&$value) { echo "start a: $value\n"; b(); echo "end a: $value\n"; } function ...
- filesize() acts differently between platforms and distributions. I tried manually compiling PHP on a 32bit platform. Filesize() would fail on files 2G. Then I compiled again, adding CFLAGS=`getconf ...
- $test = true and false; --- $test === true $test = (true and false); --- $test === false $test = true && false; --- $test === false ---- Server IP: 195.46.80.5 Probable Submitter: 158.195.96.161 ---- ...
- Other languages (in my case Java) allow access to multiple values for the same GET/POST parameter without the use of the brace ([]) notation. I wanted to use this function because it was faster than ...
- Below is the function for making an English-style list from an array, seems to be simpler than some of the other examples I've seen. <?php function ImplodeProper($arr, $lastConnector = 'and') { if( ...
- This code implodes same as the PHP built in except it allows you to do multi dimension arrays ( similar to a function below but works dynamic :p. <?php function implode_md($glue, $array, ...
- To go further with Fabian's comment: The XML specification (production 66) says that (decimal) numeric character references start with '&#', followed by one or more digits [0-9], and end with a ';' - ...
- Fabian's observation that chr(039) returns "a heart character" is explained by the fact that numeric literals that start with '0' are interpreted in base 8, which doesn't have a digit '9'. So 039==3 ...
- Bafflingly, html_entity_decode() only converts the 100 most common named entities, whereas the HTML 4.01 Recommendation lists over 250. This wrapper function converts all known named entities to ...
- Whilst implementing my RSS_FEED reader, I stumbled upon a slight issue, typically on RSS feeds such as the NY Times ones : quotes and apostrophes were replaced by question tags. For example : "the ...
- If you have a class which defines a constant which may be overridden in child definitions, here are two methods how the parent can access that constant: class Weather { const danger = 'parent'; ...
- A further implementation of the great rstrpos function posted in this page. Missing some parameters controls, but the core seems correct. <?php // Parameters: // // haystack : target string // needle ...
- @egingell at sisna dot com - Use of __call makes "overloading" possible also, although somewhat clunky... i.e. <?php class overloadExample { function __call($fName, $fArgs) { if ($fName == 'sum') { ...
- @ zachary dot craig at goebelmediagroup dot com I do something like that, too. My way might be even more clunky. <?php function sum() { $args = func_get_args(); if (!count($args)) { echo 'You have to ...
- Re: Renumbering arrays: This (from rcarvalhoREMOVECAPS at clix dot pt): $a = array_merge($a, null); does not renumber the array in PHP5. However this: $a = array_merge($a, array()); does renumber the ...
- Re: public at kreinacke dot com It has long been a point of frustration to me that md5() functions don't produce the same results as the *nix md5sum program. Reading your comments about the ...
- Using the Unix 'file' program with the -i switch will not work reliably. Consider the following plain-text CSV file (we'll call it 'error.csv'), which has the contents: ...
- There are a couple of things you can do for cleaner code if you want the keys returned from the array. I am not sure how they each impact performance, but the visual readability is more beneficial ...
- How about something like this: function goodFloor($x) { return floor(round($x, strlen((string)($x)))); } It's not elegant but at least short... Regards, Wojciech ---- Server IP: 195.136.184.34 ...
- Smaller version for PHP5 <?php # array array_unique_save (array array [, bool preserve_keys] ) function array_unique_save ($a, $pk = true) { $a = array_diff_key($a, array_unique($a)); return ($pk ? ...
- To svenxy AT nospam gmx net AND rob at digital-crocus dot com <?php $zones = array('192.168.11', '192.169.12', '192.168.13', '192.167.14', '192.168.15', '122.168.16', '192.168.17' ); natsort($zones); ...
- After much messing around to get php to store session in a database and reading all these notes, I come up with this revised code based on 'stalker at ruun dot de' class. I wanted to use PEAR::MDB2. ...
- In the below example posted by "shaun at shaunfreeman dot co dot uk". You shouldn't call gc() within the close() method. This would undermine PHP's ability to call gc() based on ...
- The following works for connecting via POP3 to a gmail server: imap_open("{pop.gmail.com:995/pop3/ssl/novalidate-cert}INBOX", $username, $pasword); ---- Server IP: 209.41.74.194 Probable Submitter: ...
- Here the workaround to the bug of strtotime() found in my previous comment on finding the exact date and time of "3 months ago of last second of this year", using mktime() properties on dates instead ...
- Here are my functions to do a 128 bit aes encryption which is transmitted to the dachser parcel tracking system via url. They expect a true aes 128 bit encryption an process the reqest by a java ...
- ...
- In case of an empty identifier the function returns a warning, not the boolean 'false'. "Warning: timezone_open() [function.timezone-open]: Unknown or bad timezone () " ---- Server IP: 217.160.72.57 ...
- JOECOLE, isn't this the same thing? $str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8"); ---- Server IP: 69.147.83.197 Probable Submitter: 216.145.54.7 ---- Manual Page -- ...
- is also quite good. Np lib install is required -Shelon Padmore ---- Server IP: 69.147.83.197 Probable Submitter: 190.6.231.26 ---- Manual Page -- ...
- Interop Between PHP and Java URLs has changed to: (Part 4) it is linked to Part 1, 2 and 3. ---- Server IP: 69.147.83.197 Probable Submitter: 202.156.12.10 (proxied: ...
- I enhance xml2array (can't remember who author) to work with duplicate key index by change "tagData" function with this - <? function tagData($parser, $tagData) { // set the latest open tag equal to ...
- To add to Stephen's note about logging, I found that if I defined the error_log path to be the Apache error log folder (ie: /var/log/httpd/php_error_log), it would still log to Apache's log, not the ...)
|
https://grokbase.com/g/php/php-notes/2007/10
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
The QTextDecoder class provides a state-based decoder. More...
#include <QTextDecoder>
Note: All functions in this class are reentrant..
Constructs a text decoder for the given codec.
Destroys the decoder. is an overloaded function.
The converted string is returned in target.
This is an overloaded function.
Converts the bytes in the byte array specified by ba to Unicode and returns the result.
|
https://doc.qt.io/archives/4.6/qtextdecoder.html
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Blender distutils addon
Project description
This Python module adds a new command to distutils to build Blender addons: bdist_blender_addon. It also provides a simple mechanism to package extra modules not included with Blender’s Python distribution within the addon.
Example
See the info_example_distutils addon to see how this distutils module is used.
Installation
Installing the blender.distutils module
The module is available on PiPy and installable with pip.
$ pip install blender.distutils
It is suggested to add a requirements.txt file to the Blender addon plugin that lists the module dependencies.
# This is requirements.txt # This module adds the setup.py bdist_blender_addon command blender.distutils # This module is required by the addon, but not distributed with blender # bdist_blender_addon will ship it if with the addon # Dependencies to be included are listed in setup.cfg dateutils
Add a simple setup.py to the blender addon
The bdist_blender_addon is a distutils command. As such, a setup.py file is required. Addon name and version are defined by this file. I suggest using bumpversion to keep setup.py, bl_info and your git tags in sync.
The setup.py for a blender addon is actually quite straightforward. The install_requires argument should only list the first-level dependencies needed by the addon: those may require their own dependencies. The actual modules to be shipped with the addon are cherry picked in setup.cfg.
from setuptools import setup, find_packages setup( name='info_example_distutils', version='1.0.0', description='Blender example distutils', long_description=open('README.md').read(), url='', author='Charles Flèche', author_email='charles.fleche@free.fr', license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: End Users/Desktop', 'Topic :: Multimedia :: Graphics :: 3D Modeling', 'Topic :: Multimedia :: Graphics :: 3D Rendering', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3 :: Only' ], packages=find_packages(), keywords='blender', # Here are listed first level dependencies needed by the module. Themselves # may require dependencies. The actual modules to be shipped with the addon # are cherry picked in setup.cfg install_requires=['dateutils'] )
Including third-party modules not shipped with blender
The bdist_blender_addon command allows to include additional python modules that are not shipped with Blender. These modules will be included in the root folder of the addon. Currently an explicit list of modules, including their dependencies, needs to be configured.
Cherry pick the modules to be shipped with the blender addon
The modules to be included to the blender addon are listed as an option of the [bdist_blender_addon] section in setup.cfg. This list includes all the modules and their dependencies.
# This is in setup.cfg [bdist_blender_addon] # Here are listed the modules (and their dependencies) to be shipped # with the blender module. In this example the addon requires `dateutils`, # which in turns requires `dateutil`, `pytz` and `six`. addon_require = dateutil,dateutils,pytz,six
Include the additional modules folder in the addon code
The addon needs to explicitly register the path to third party modules. During development, those modules will be in a virtual environment. When the addon is installed in production, those modules will be at the root of the addon folder.
import pathlib import os import site import sys def third_party_modules_sitedir(): # If we are in a VIRTUAL_ENV, while developing for example, we want the # addon to hit the modules installed in the virtual environment if 'VIRTUAL_ENV' in os.environ: env = pathlib.Path(os.environ['VIRTUAL_ENV']) v = sys.version_info path = env / 'lib/python{}.{}/site-packages'.format(v.major, v.minor) # However outside of a virtual environment, the additionnal modules not # shipped with Blender are expected to be found in the root folder of # the addon else: path = pathlib.Path(__file__).parent return str(path.resolve()) # The additionnal modules location (virtual env or addon folder) is # appended here site.addsitedir(third_party_modules_sitedir()) # This module is not part of the standard blender distribution # It is shipped alongside the plugin when `python setup.py bdist_blender_addon` import dateutils
Build the module
The bdist_blender_addon command will copy the addon code, copy the additional modules over, clean unneeded files (like the *.pyc bytecode files) and package them all in a versioned zip archive under the dist folder.
$ python setup.py bdist_blender_addon running bdist_blender_addon running build running build_py creating build/lib/info_example_distutils copying info_example_distutils/__init__.py -> build/lib/info_example_distutils creating build/lib/info_example_distutils/dateutil [long list of files being copied or added to the addon zip archive] $ ls dist/ info_example_distutils-v1.0.0.zip
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/blender.distutils/1.0.5/
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
Developing a Per-Monitor DPI-Aware WPF Application
Important APIs
Note
This page covers legacy WPF development for Windows 8.1. If you are developing WPF applications for Windows 10, please see the latest documentation on GitHub.
Windows 8.1 gives developers new functionality to create desktop applications that are per-monitor DPI-aware. In order to take advantage of this functionality, a per monitor DPI-aware application must do the following:
- Change window dimensions to maintain a physical size that appears consistent on any display
- Re-layout and re-render graphics for the new window size
- Select fonts that are scaled appropriately for the DPI level
- Select and load bitmap assets that are tailored for the DPI level
To facilitate making a per-monitor DPI-aware application, Windows 8.1 provides the following Microsoft Win32APIs:
- SetProcessDpiAwareness (or DPI manifest entry) sets the process to a specified DPI awareness level, which then determines how Windows scales the UI. This supersedes SetProcessDPIAware.
- GetProcessDpiAwareness returns the DPI awareness level. This supersedes IsProcessDPIAware.
- GetDpiForMonitor returns the DPI for a monitor.
-. To create an application that resizes and re-renders itself when a user moves it to a different display, use this notification.
For more details on various DPI awareness levels supported for desktop applications in Windows 8.1 see the topic Writing DPI-Aware Desktop and Win32 Applications.
DPI Scaling and WPF
Windows Presentation Foundation (WPF) applications are by default system DPI-aware. For definitions of the different DPI awareness levels see the topic Writing DPI-Aware Desktop and Win32 Applications. The WPF graphics system uses device-independent units to enable resolution and device independence. WPF scales each device independent pixel automatically based on current system DPI. This allows WPF applications to scale automatically when the DPI of the monitor the window is on is same system DPI. However, since WPF applications are system dpi-aware, the application will be scaled by the OS when the application is moved to a monitor with a different DPI or when the slider in the control panel is used to change the DPI. Scaling in the OS may result in WPF applications to appear blurry especially when the scaling is non-integral. In order to avoid scaling WPF applications, they need to be updated to be per-monitor DPI-aware.
Per Monitor Aware WPF Sample Walkthrough
The Per Monitor Aware WPF sample is a sample WPF application updated to be per-monitor DPI-aware. The sample consists of two projects:
- NativeHelpers.vcxproj: This is a native helper project that implements the core functionality to make a WPF application as per-monitor DPI-aware utilizing the Win32APIs above. The project contains two classes:
- PerMonDPIHelpers: A class that provides helper functions for DPI related operations like retrieving the current DPI of the active monitor, setting a process to be per-monitor DPI-aware, etc.
- PerMonitorDPIWindow: A base class derived from System.Windows.Window that implements functionality to make a WPF application window to be per-monitor dpi-aware. Adjusts window size, graphics rendering size and font size based on the DPI of the monitor rather than the system DPI.
- WPFApplication.csproj: Sample WPF application that consumes the PerMonitorDPIWindow (PerMonitorDPIWindow), and showcases how the application window and rendering resizes when the window is moved to a monitor with a different DPI or when the slider in the Display control panel is used to change the DPI.
To run the sample follow the steps below:
- Download and unzip the Per Monitor Aware WPF sample
- Start Microsoft Visual Studio and select File > Open > Project/Solution
- Browse to the directory that contains the unzipped sample. Go to the directory named for the sample, and double-click the Visual Studio Solution (.sln) file
- Press F7 or use Build > Build Solution to build the sample
- Press Ctrl+F5 or use Debug > Start Without Debugging to run the sample
To see the impact of changing DPI on a WPF application that is updated to be per-monitor DPI-aware using the base class in the sample, move the application window to and from displays that have different DPIs. As the window is moved between monitors, the window size and the UI scale is updated based on the DPI of the display by using WPF’s scalable graphics system, rather than being scaled by the OS. The application’s UI is rendered natively and does not appear blurry. If you don’t have two displays with different DPI, change the DPI by changing the slider in the Display control panel. Changing the slider and clicking Apply will resize the application’s window and update the UI scale automatically.
Updating an existing WPF Application to be per-monitor dpi-aware using helper project in the WPF Sample
If you have an existing WPF application and wish to leverage the DPI helper project from the sample to make it DPI aware, follow these steps.
Download and unzip the Per Monitor Aware WPF sample
Start Visual Studio and select File > Open > Project/Solution
Browse to the directory which contains an existing WPF application and double-click the Visual Studio Solution (.sln) file
Right click on Solution > Add > Existing Project
In the file selection dialogue browse to the directory that contains the unzipped sample. Open to the directory named for the sample, browse to the folder "NativeHelpers", select the Visual C++ project file "NativeHelpers.vcxproj” and click OK
Right click on the project NativeHelpers and select Build. This will generate NativeHelpers.dll that will be added as a reference to the WPF Application in the next step
Add a reference to NativeHelpers.dll from your WPF Application. Expand your WPF application project, right click on References and click on Add Reference...
In the resulting dialogue, expand the Solution section. Under Projects, select NativeHelpers, and click OK
Expand your WPF application project, expand Properties, and open AssemblyInfo.cs. Make the following additions to AssemblyInfo.cs
- Add reference to System.Windows.Media in the reference section (using System.Windows.Media;)
- Add the DisableDpiAwareness attribute (
[assembly: DisableDpiAwareness])
Inherit the main WPF window class from PerMonitorDPIWindow base class
Update the .cs file of the main WPF window to inherit from the PerMonitorDPIWindow base class
- Add a reference to NativeHelpers in the reference section by adding the line
using NativeHelpers;
- Inherit the main window class from PerMonitorDPIWindow class
Update the .xaml file of the main WPF window to inherit from PerMonitorDPIWindow base class
- Add a reference to NativeHelpers in the reference section by adding the line
xmlns:src="clr-namespace:NativeHelpers;assembly=NativeHelpers"
- Inherit the main window class from PerMonitorDPIWindow class
Press F7 or use Build > Build Solution to build the sample
Press Ctrl+F5 or use Debug > Start Without Debugging to run the sample
The Per Monitor Aware WPF sample application illustrates how a WPF application can be updated to be per-monitor DPI-aware by responding to the WM_DPICHANGED window notification. In response to the window notification, the sample updates the scale transform used by WPF based on the current DPI of the monitor the window is on. The wParam of the window notification contains the new DPI in the wParam. The lParam contains a rectangle that has the size and position of the new suggested window, scaled for the new DPI.
Note:
Note
Since this sample overwrites the window size and the scale transform of the root node of the WPF window, further work may be required by application developer if:
- The size of the window impacts other portions of the application like this WPF Window being hosted inside another application.
- The WPF application that is extending this class is setting some other transform on the root visual; the sample may overwrite some other transform that is being applied by the WPF application itself.
Overview of the helper project in the WPF sample
In order to make an existing WPF application per-monitor DPI-aware the NativeHelpers library provides following functionality:
Marks the WPF application as per-ponitor DPI-aware: The WPF application is marked as per-monitor DPI-aware by calling SetProcessDpiAwareness for the current process. Marking the application as per-monitor DPI-aware will ensure that
- The OS does not scale the application when the system DPI does not match the current DPI of the monitor the application window is on
- The WM_DPICHANGED message is sent whenever the DPI of the window changes
Adjusts the window dimension, re-layout and re-render graphics content and select fonts based on initial DPI of the monitor the window is on: Once the application is marked as per-monitor DPI-aware, WPF will still scale the window size, graphics and font size based on the system DPI. Since, at app launch, the system DPI is not guaranteed to be the same as the DPI of the monitor the window is launched on, the library adjust these values once the window is loaded. The base class PerMonitorDPIWindow updates these in the OnLoaded() handler.
The Window size is updated by changing the Width and Height properties of the Window. The layout and size are updated by applying an appropriate scale transform to the root node of the WPF window.
void PerMonitorDPIWindow::OnLoaded(Object^ , RoutedEventArgs^ ) { if (m_perMonitorEnabled) { m_source = (HwndSource^) PresentationSource::FromVisual((Visual^) this); HwndSourceHook^ hook = gcnew HwndSourceHook(this, &PerMonitorDPIWindow::HandleMessages); m_source->AddHook(hook); //Calculate the DPI used by WPF. m_wpfDPI = 96.0 * m_source->CompositionTarget->TransformToDevice.M11; //Get the Current DPI of the monitor of the window. m_currentDPI = NativeHelpers::PerMonitorDPIHelper::GetDpiForWindow(m_source->Handle); //Calculate the scale factor used to modify window size, graphics and text m_scaleFactor = m_currentDPI / m_wpfDPI; //Update Width and Height based on the on the current DPI of the monitor Width = Width * m_scaleFactor; Height = Height * m_scaleFactor; //Update graphics and text based on the current DPI of the monitor UpdateLayoutTransform(m_scaleFactor); } }); } } }
Responds to WM_DPICHANGED window notification: Update the window size, graphics and font size based on the DPI passed in the window notification. The base class PerMonitorDPIWindow handles the window notification in the HandleMessages() method.
The Window size is updated by calling SetWindowPos using the information passed in the lparam of the window message. The layout and graphics size are updated by applying an appropriate scale transform to the root node of the WPF window. The scale factor is calculated by using the DPI passed in the wparam of the window message.
IntPtr PerMonitorDPIWindow::HandleMessages(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, bool% ) { double oldDpi; switch (msg) { case WM_DPICHANGED: LPRECT lprNewRect = (LPRECT)lParam.ToPointer(); SetWindowPos(static_cast<HWND>(hwnd.ToPointer()), 0, lprNewRect->left, lprNewRect- >top, lprNewRect->right - lprNewRect->left, lprNewRect->bottom - lprNewRect->top, SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE); oldDpi = m_currentDPI; m_currentDPI = static_cast<int>(LOWORD(wParam.ToPointer())); if (oldDpi != m_currentDPI) { OnDPIChanged(); } break; } return IntPtr::Zero; } void PerMonitorDPIWindow::OnDPIChanged() { m_scaleFactor = m_currentDPI / m_wpfDPI; UpdateLayoutTransform(m_scaleFactor); DPIChanged(this, EventArgs::Empty); }); } } }
Handling DPI change for assets like images
In order to update graphics content, the sample WPF application applies a scale transform to the root node of the WPF application. While this works well for content that is rendered natively by WPF (rectangle, text etc.), this implies that bitmap assets like images are scaled by WPF.
In order to avoid blurred bitmaps caused by scaling, the WPF application developer can write a custom DPI image control that selects a different asset based on the current DPI of the monitor the window is on. The image control can rely on the DPIChanged() event fired for the WPF window that consumes from the PerMonitorDPIWindow, when the DPI changes.
Note
The image control should also select the right control during app launch in the Loaded() WPF window event handler.
|
https://docs.microsoft.com/en-us/windows/desktop/hidpi/declaring-managed-apps-dpi-aware
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
by Kevin Fauth
Table of contents
Created
4 May 2009
Adobe Flex makes building an incredibly rich and attractive kiosk application relatively simple. Chances are you have never had the opportunity to work on a kiosk or build one, in which case a kiosk can seem like a mystery. Flex technology, however, is behind an increasing number of kiosks and will most likely continue to grow in acceptance for this type of application.
In this article I'm going to cover some basic kiosk concepts, such as working with both user-driven and timed events. I will also describe the general architecture of a kiosk application, and build a simple kiosk application to help explain the concepts.
Before diving into the nitty-gritty details of building a kiosk, there are some concepts to learn that will help change your mindset from traditional application development to working with kiosks. The following list is by no means comprehensive, but should help you wrap your head around how a kiosk is put together.
The machine itself
Chances are, one of the reasons you became a Flex developer was because it saved you time moving the application from one platform to another. Almost gone are the days of using JavaScript to detect what version of Opera, Firefox, or Internet Explorer the user is on, and if that version supports CSS 2.x or 1.x, and so forth. Flex gives you the ability to standardize the user environment, so you no longer worry about those exceptions and instead can focus on the rich interface.
This is my favorite part of kiosk development – your company usually owns the hardware, the machine itself. You get to control the processor, RAM, video card, touchscreen, printer, swiper, or anything else you can imagine. This is by far the greatest advantage of kiosk development. Of course the tighter you integrate with a Windows machine, the harder it will be to switch to a Linux or Mac machine, so I encourage you to use as many cross-platform technologies as possible, for example Java, basic JavaScript, and printer/swiper/other hardware that will work across the platforms with little change, instead of browser and platform specific ActiveX.
Interacting with hardware
So here's the big question: How does Flex interact with hardware? Do you need to interact with hardware at all? Some kiosk applications require a printer, a card swiper, and maybe another piece of hardware (for example a scanner on an ATM, a barcode reader on a DVD Kiosk, and so on). Interacting with the hardware isn't as complicated as it might seem though; after all you usually own it. There are a few methods for interacting with hardware, but as of right now, the only way is to tunnel your communication from Flex to another application on the kiosk's hard drive to do the dirty work for you.
You can, for example, create and ActiveX or Java application that has native support for hardware interaction. The application might have to be signed (and trusted) in order to run with heightened permissioning to talk to the hardware; but as long as you have a valid Certificate Authority (CA) and signing certificate, it should be no problem. To bridge the ActiveX or Java application to Flex, I use ExternalInterface and create a hardware class in my Flex app that will take care of everything for me.
Touchscreens
Touchscreen development shouldn't be difficult, but if you have never worked with a touchscreen it can be a bit overwhelming. Touchscreens are just another Human Interface Device (HID) that your computer can use to determine what your users are trying to do—it's basically an expensive mouse. At the time of this writing, you can pick one up for development purposes, or even production, off of eBay for between $100 and $4000.
When you set up your touchscreen device, the software drivers that come with it will include various options to configure it for your application. These may include the ability to disable right-click from a touchscreen (yes, right-click is possible), decide when a user's click action is actually performed (for example on lift or on press), and even at which processor priority level the touchscreen application should run. In my experience, I would recommend disabling right-click, configuring the click to occur on press (mouseDown), and setting the processor priority level to High to simplify the development with kiosks and touchscreens..
Parallax
Parallax refers to an apparent shift in position of an object when the viewer's position changes. You have likely experienced this on older ATMs; there are physical buttons on either side of the screen, but the labels just don't seem to line up with the buttons. If you bend over or stand on tiptoes then you can line up the labels with the buttons–that's parallax in action.
If you don't want your users to have to bend over to make sure they're selecting what they really want, a full understanding of this phenomenon is important when you build your kiosk. Make sure designers are aware of this as well; placing vertical buttons too close together can cause users to accidentally select the wrong button.
The first thing to consider when building the application itself is also one of the easiest to overlook: allowing Flex to keep track of the application's state. The typical case for Flex development is to allow the user almost complete control of the entire process and flow of the application. While kiosk development is similar, user's sessions must be kept separate from one user to the next. And, unlike a game or other web application, kiosks are always running. It's very important to add some sort of timer to every page that is displayed in the application to make sure your kiosk's display is dynamic and rich. The timing can vary depending with the business needs of the application, or with your professional judgment as a developer.
The sample application in this article uses two timers, one to wait for user input, another to kick unresponsive users out of their session on an input screen.
It seems that everybody has their own way of tracking application state; here I'll use a basic singleton class. For a real-world application, you will want to embed this into your MVC architecture and other related classes.
Create ApplicationState.as
To get the project started, create a new Flex project and name it "My First Kiosk". Next, within the main package create a class called ApplicationState that extends EventDispatcher. The contents will look like this:
package { import flash.events.Event; import flash.events.EventDispatcher; public class ApplicationState extends EventDispatcher { // events in the state public static var EVENT_STATE_CHANGE:String = "stateChange"; // "states" in the application public static var SCREEN_SAVER:Number = 0; public static var WELCOME_SCREEN:Number = 1; public static var USER_INPUT:Number = 2; public static var COUNTDOWN:Number = 99; // stores the current state of the application private var _currentState:Number; public function set currentState(val:Number):void { previousState = _currentState; _currentState = val; dispatchEvent(new Event(EVENT_STATE_CHANGE)); } [Bindable(EVENT_STATE_CHANGE)] public function get currentState():Number { return _currentState; } public var previousState:Number; // singleton work private static var _instance:ApplicationState; public static function getInstance():ApplicationState { if ( !_instance ) { _instance = new ApplicationState() } return _instance; } } }
At the top of the class you will see the three states I have defined,
SCREEN_SAVER,
WELCOME_SCREEN, and
USER_SELECT.I have them defined as
Numberfor right now, but any data type will work.
The variable
currentStatewill store the current state of the application; no surprises there. You can get or set this value in any module of your program. Here it is set on a UI element's
showevent. This class uses a setter method to set the value so it can dispatch an event whenever the user changes the state. I made the event string bindable in case any view is binding to that value and wants to update the UI. You will also notice that I'm storing the
previousStateat the top of the setter. This is used mostly for the
ApplicationTimerclass that I'll discuss near the end of this article.
Finally you will see the details for the singleton class for the ApplicationState class. There are a few tricks to enforce a singleton class in Flex, but you will most likely be putting this into a manager class somewhere else in your MVC architecture, so I will not go into the details.
Now that you have created the class that will keep track of your application's state, you need to start adding views and visual elements to the display.
There are a couple different types of screens you can show at the beginning of your kiosk while it loads the modules or other pieces of the application, and it all really depends on what your business needs are. You may want to start the kiosk and let the user have immediate access to it while you download the extra modules they might not need for a few minutes. Or, you might prefer to load all of your modules before allowing the user to get started. In this case, you might also want to default your initial view to a "loading kiosk" state. In this example application, I'm going to allow the user to jump right in and start moving around.
Create Welcome.mxml
The first visual item I need to create is the Welcome.mxml (See Figure 1). This view will be the screen displayed while waiting for the user to click a button. I create a new Component, name it "Welcome", select
VBoxas the Based On component, and set the
heightand
widthto
100%.
Next, I set the component's
horizontalAlignand
verticalAlignto
centerand
middle, respectively. I add a label, a button, and some code to dispatch an event whenever the user clicks on the button.
<?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event(name="startClicked")] </mx:Metadata> <mx:Script> <![CDATA[>
Figure 1. The Welcome.mxml.
Note: Using
Metadatatags in the components allows you to add the events in MXML mode.
In the
clickhandler for my button, you can see I created a new method,
onButtonClick()that will dispatch a custom event type called
startClicked. While this is sufficient to dispatch an event, I added the event to the
Metadatatag to ensure the event is visible when adding this component via MXML.
Keep track of the application state
Now that the first visual component is done, I need to let the rest of the application know that the currently visible state is now the Welcome screen. To accomplish this, I need to notify the ApplicationState class about what state change just happened. Since I'm not using any MVC for this example, I'm going to plug it into the
showproperty of the component itself. It should be a relatively safe place to put it, since if it's showing, then it's in that state.
In the script block, I'll get the instance of the ApplicationState singleton class, and set its
currentStateequal to
WELCOME_SCREEN,the static variable I defined in the ApplicationState class for the Welcome screen, whenever the
showevent is fired for the component. The updated Welcome.mxml code now looks like this:
<?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event(name="startClicked")] </mx:Metadata> <mx:Script> <![CDATA[ private var _applicationState:ApplicationState = ApplicationState.getInstance(); private function onShow():void { _applicationState.currentState = ApplicationState.WELCOME_SCREEN; }>
Note: The button on this component is quite large; this is doneto account for parallax and user experience considerations.
I have now created the ApplicationState class to keep track of the application's state and Welcome.mxml to add a visual component to the application. Now I am going to create one more visual component to prompt for a user's selection and then tie those three items together, so a very basic application can appear on the screen and function.
The new component basically does everything that Welcome.mxml does, but instead of just one button, it has four. Again, you will want to integrate this into your MVC architecture and the framework you use to manage the content and your UI views.
Create UserInputSelection.mxml
Following the same steps for creating the Welcome.mxml file, I add the four buttons (See Figure 2). I also pass the
MouseEventwith the click events in order to capture just what was selected and display a simple Alert message with the label's text in it. Since this form has multiple buttons that won't change the state of the application, I'm going to dispatch a new event called
extendTimeoutin the
onButtonClick()method. The main.mxml will listen for this event, which I will explain in the Time for timers section. The UserInputSelection.mxml file now looks like:
<?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event(name="itemSelected")] </mx:Metadata> <mx:Script> <![CDATA[ import mx.controls.Alert;>
Figure 2. Create UserInputSelection.mxml
Note: Using
Metadatatags in the components allows you to add the events in MXML mode.
Just as I did in the Welcome.mxml file, I add
clickhandlers to the button and dispatch a custom event,
itemSelected. More than likely, you will want to build these buttons dynamically based off a dataset of some sort.
Keep track of application state
Now that the functionality of the UserInputSelection screen is created, I need to tell the ApplicationState class that the state of the application is now in the UserInputSelection screen. I use the same mechanism as in the Welcome.mxml file, except I change
WELCOME_SCREENto
USER_INPUT. The UserInputSelection.mxml file now looks like:
<?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event(name="itemSelected")] </mx:Metadata> <mx:Script> <![CDATA[ import mx.controls.Alert; private var _applicationState:ApplicationState = ApplicationState.getInstance(); private function onShow():void { _applicationState.currentState = ApplicationState.USER_INPUT; }>
I now have the ApplicationState and created two visual components, I want to tie them all together so I can see what shape my application is in as of right now. I need to integrate those components into the main.mxml application file, and a
viewstackprovides the easiest way to integrate the new components into this view.
Modify main.mxml
Open up main.mxml, create the new
ViewStackand add the children. Set the
heightand
widthof the
ViewStackto
100%for now. I like to be able to reference the children by id, so I add an id to each new child. The main.mxml code now looks like this:
<?xml version="1.0" encoding="utf-8"?> <mx:Application <mx:ViewStack <local:Welcome <local:UserInput </mx:ViewStack> </mx:Application>
Running the application in its current form will only display the Welcome.mxml component. I still need to manage what gets displayed and when.
Changing what is visible in the ViewStack
When I first created the Welcome.mxml and UserInputSelection.mxml screens, I added event dispatching into the mix. That is now going to help me control the application as the user moves around in it. I just need to add in the listeners and code to handle that change. The component declarations will now look like:
<local:Welcome <local:UserInput
And the script looks like:
private function onStartClicked():void { myViewStack.selectedChild = userInputScreen; } private function onItemSelected():void { // do nothing yet }
The entire main.mxml file should now look like:
<?xml version="1.0" encoding="utf-8"?> <mx:Application <mx:Script> <![CDATA[ private function onStartClicked():void { myViewStack.selectedChild = userInputScreen; } private function onItemSelected():void { // do nothing yet } ]]> </mx:Script> <mx:ViewStack <local:Welcome <local:UserInput </mx:ViewStack> </mx:Application>
By adding the events in the
Metadatatags in the custom component, I now get my custom events to appear in the
mxmltags of my components,
startClickedand
itemSelected; these new events now invoke the
onStartClicked()and
onItemSelected()event handlers. When
startClickedis fired from the component,
onStartClicked()will run and will update the
ViewStack's selected child to display the UserInput component. The
onItemSelected()method does nothing for now.
Running this code should now give you the Welcome screen, and clicking the button labeled "Click me to start" will now change the
ViewStackto the UserInput component and display the four item buttons. There is no way to move to the previous screen in the application. When you build a kiosk for production, you will most likely want to include this capability and others, such as pop-up help. I will leave that to you to add at your discretion.
I have now created the framework for a kiosk application. However, I don't want my users to get stuck at the user input screen. Moreover, if they walk away, I don't want the next user to start on that screen. So the next piece to work on is the ScreenSaver component, which will help reset application state and allow for application clean-up.
While I call this next component a screen saver, it is really a multipurpose component that you can display at the end of the entire user entry process, when a user times out on a state, or if the user walks away, to give your application time to reset itself. You can display an advertisement, logo, or graphic. It provides time for the application to reset, letting animations complete, clearing data, maybe sending a few calls to the server to pass data about user interactions, or anything that's part of the clean-up or resetting phase in your application.
Create ScreenSaver.mxml
I'm going to make a very simple screen saver, with some minor effects to achieve the traditional screen saver effect (See Figure 3). In order to manipulate text with effects (grow, fade, and so on) I need to embed the font. I have included and embedded a royalty-free font in the downloadable sample code.
To get started, I create a new component called ScreenSaver and base the component on an
HBoxobject, settting both the
heightand
widthproperties to
100%. Next, I modify the component's
horizontalAlignand
verticalAlignto
centerand
middle, respectively. I add a
labeland a few effects to run on
Show. The resulting code looks like:
<?xml version="1.0" encoding="utf-8"?> <mx:HBox <mx:Script> <![CDATA[ private var _applicationState:ApplicationState = ApplicationState.getInstance(); private function onShow():void { _applicationState.currentState = ApplicationState.SCREEN_SAVER; } ]]> </mx:Script> <mx:Sequence <mx:SetPropertyAction <mx:SetPropertyAction <mx:Fade <mx:Parallel <mx:Rotate <mx:Fade </mx:Parallel> </mx:Sequence> <mx:Sequence <mx:Parallel <mx:Rotate <mx:Fade </mx:Parallel> <mx:SetPropertyAction <mx:Fade </mx:Sequence> <mx:Label </mx:HBox>
Figure 3. A very simple screen saver
I added an event handler for the
HBox showevent, which calls
onShow()to set the current application state. I am also binding the
showEffectand
hideEffectto the
fadeInand
fadeOutsequence effects. In order for the effects to look right, I'm setting the text to animate its
alphato zero, then its
visibleproperty to
true. Since this is in a
sequenceeffect, it will ensure the
alphais set to
0before showing the label, so that it doesn't flash on the screen before fading in. The rest of the code is straightforward.
Modify Main.mxml to include ScreenSaver.mxml
Now that I've created the screen saver, I'm going to add it at the very bottom of main.mxml. I'm doing this because Flex lays out UI components from the top down. By adding this new component to the bottom of the main.mxml file and setting its
visibleproperty to
true, I make it appear on top of everything else, allowing me to move UI components around and reset the application's UI under the cover of the ScreenSaver component.
So, under the ViewStack, I'm going to add:
<local:ScreenSaver
When you run the application now, it should appear the same as before. I'll integrate the screen saver in the next section.
With the visual components mostly complete, the last visual component I need is a countdown that will appear on the user input screen when the user waits too long to make a selection.
The countdown screen will be shown whenever a user input screen is displayed and a user doesn't select an item within a specified timeframe (see Figure 4). You will be able to configure the times in the Time for timers section.
Create Countdown.mxml
Just like the screen saver, I am going to make a very basic countdown screen. The countdown numbers are going to come from the
ApplicationTimerclass, which I'll be creating in the next section. For this visual component, I want the user to click on the screen (touch the screen) in order to return to the input screen.
To get started, I create a new component called Countdown and base it on a
VBoxobject. I set both the
heightand
widthproperties to
100%. Next, I modify the component's
horizontalAlignand
verticalAlignto
centerand
middle, respectively. I add two
Labeltags and a custom event. The resulting code looks like:
<?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event( <mx:Label </mx:VBox>
Figure 4. The countdown screen
On this screen I detect a
clickevent on the
VBoxand that will fire the
formClick()method. This method dispatches two events,
userClickedScreenand
extendTimeout. The
userClickedScreenevent notifies any listeners that the user is trying to keep their session alive. The
extendTimeoutevent is a piece of the final component of this example and I will go into that in more detail in the next section. The last task that this method performs is to set the current application state to the previous application state. Since the countdown is simply an overlay for the UI and I did not want to try to integrate all the pieces together, I decided to allow this component to know the previous application state and handle what it is already familiar with.
Modify Main.mxml to include Countdown.mxml
Now that Countdown.mxml is finished, I need to integrate it into main.mxml. I do this in the same way I added ScreenSaver.mxml, by adding it near the bottom. I'm going to place it under the
ViewStack, but above the ScreenSaver component. This will allow the Countdown to appear on top of the ViewStack, while still allowing the ScreenSaver to appear on top of everything. The code to add the Countdown component looks like:
<local:Countdown
I don't have a value for the
countdownValueproperty yet, but I will get that once I create the ApplicationTimer class.
With all the UI components mostly complete, I want to control how long each user should be allowed to view a screen before making a selection and when to display the screen saver. I'll need to integrate a new ApplicationTimer class to tell the application when to show the countdown and screen saver, and when to reset the views and "session" data.
In order to manage that, I'm going to create a new class, but base it off a
UIComponentso I can plug it onto my main.mxml as a component. You don't have to use a
UIComponentfor this, but I like to so I can look just at the MXML and get a good idea of what it is doing without having to scroll up to read the
<script>tags and find the
addListenermethods. Both are acceptable practices.
Create ApplicationTimer.as
My new class is going to be listening to the ApplicationState singleton for the state change event
EVENT_STATE_CHANGE. It will then decide what screen is showing and how long it should be visible before throwing an event to show/hide the screen saver or show/hide
the countdown display. In this example, I have hardcoded the values, but these values will most likely be dynamic depending on your application and MVC design.
The ApplicationTimer.as class looks like:
package { import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; import mx.core.UIComponent; [Event(name="showScreenSaver")] [Event(name="hideScreenSaver")] [Event(name="showCountdown")] [Event(name="hideCountdown")] public class ApplicationTimer extends UIComponent { // events this class dispatches public static var EVENT_SHOW_SCREEN_SAVER:String = "showScreenSaver"; public static var EVENT_HIDE_SCREEN_SAVER:String = "hideScreenSaver"; public static var EVENT_SHOW_COUNTDOWN:String = "showCountdown"; public static var EVENT_HIDE_COUNTDOWN:String = "hideCountdown"; [Bindable("currentTimerCount")] public function get countdownNumber():Number { return _countdownNumber } public function set countdownNumber(val:Number):void { _countdownNumber = val; dispatchEvent(new Event("currentTimerCount")); } // internal values private var _applicationState:ApplicationState = ApplicationState.getInstance(); private var _stateTimer:Timer = new Timer(5000); // default the timer to 5 seconds private var _countdownTimer:Timer = new Timer(1000); // set to 1sec to update UI private var _countdownNumber:Number; public function userInteractionReceived():void { if ( _stateTimer ) { _stateTimer.stop(); _stateTimer.reset(); _stateTimer.start(); } } public function onStateChange(e:Event):void { _stateTimer.stop(); _stateTimer.reset(); switch ( _applicationState.currentState ){ case ApplicationState.WELCOME_SCREEN: _stateTimer.delay = 5000; // 5 second delay break; case ApplicationState.USER_INPUT: _stateTimer.delay = 5000; // 5 second delay break; case ApplicationState.SCREEN_SAVER: _stateTimer.delay = 2500; // 2.5 second delay break; } // don't restart the state timer if the current state is the countdown if ( _applicationState.currentState != ApplicationState.COUNTDOWN ){ _countdownTimer.stop(); _stateTimer.start(); } } private function onTimer(e:TimerEvent):void { _stateTimer.stop(); switch ( _applicationState.currentState ){ case ApplicationState.WELCOME_SCREEN: dispatchEvent(new Event(EVENT_SHOW_SCREEN_SAVER)); break; case ApplicationState.USER_INPUT: startCountdown(6); break; case ApplicationState.SCREEN_SAVER: dispatchEvent(new Event(EVENT_HIDE_SCREEN_SAVER)); break; } } private function startCountdown(val:Number):void { countdownNumber = val; dispatchEvent(new Event(EVENT_SHOW_COUNTDOWN)); _countdownTimer.reset(); _countdownTimer.repeatCount = countdownNumber; _countdownTimer.start(); } private function onCountdownTimer(e:TimerEvent):void { // if user "times out", hide the countdown, show screen saver if ( _countdownTimer.currentCount == _countdownTimer.repeatCount ){ _countdownTimer.stop(); dispatchEvent(new Event(EVENT_HIDE_COUNTDOWN)); dispatchEvent(new Event(EVENT_SHOW_SCREEN_SAVER)); } else // otherwise update the countdownNumber { countdownNumber = _countdownTimer.repeatCount - _countdownTimer.currentCount; } } // constructor public function ApplicationTimer(){ super(); _applicationState.addEventListener(ApplicationState.EVENT_STATE_CHANGE, onStateChange); _stateTimer.addEventListener(TimerEvent.TIMER, onTimer); _countdownTimer.addEventListener(TimerEvent.TIMER, onCountdownTimer); } } }
Near the top of the class you will see four events:
showScreenSaver,
hideScreenSaver,
showCountdown,
hideCountdown. The various timer return calls dispatch these events, which can then control the UI. Static variables are used for the event names to make referencing them easier throughout the class.
The variable
countdownNumberhas a public getter and setter and dispatches a
currentTimerCountevent whenever that value changes. The Countdown.mxml component uses this value to display how many seconds the user has left to touch the screen.
Moving down a few lines, you will see I declare two timers,
_stateTimerand
_countdownTimer. The
_stateTimervalue defaults to 5 seconds, but could default to any number. The
_countdownTimervalue needs to stay at 1 second, since it will need to update the
countdownNumberevery second for display purposes. Under the timer declarations, notice the public function
userInteractionReceived(). I‘ll cover this in the Detecting user presence section.
When the ApplicationTimer class initializes, it sets an event listener for the
stateChangeevent from
ApplicationStateclass and calls
onStateChange().Once the method fires, it stops the
_stateTimer, resets it and determines what the new
currentStateis. Depending on the new state, it will update the
_stateTimer.delayto how long that screen should be visible, and then if the
currentStateis not the
COUNTDOWNstate, it will ensure the
_countdownTimeris stopped and then restart the
_stateTimer.
Once
_stateTimerhits the limit,
onTimer()is called and it determines what the current state is and if it should show the screen saver, hide the screen saver, or start a countdown process of some sort. In this example, if the
currentStateis
WELCOME_SCREEN, show the screen saver. If the
currentStateis USER_INPUT, display a 6-second countdown, and if the
currenStateis
SCREEN_SAVER, hide the screen saver.
Whenever the
_countdownTimerthrows a
TimerEvent,
onCountdownTimer()is called. This method will compare what the
currentCountof the timers is and see if it is equal to the
repeatCountproperty. If they are equal, then it has reached the end of the countdown period; it stops the timer, dispatches an event to hide the countdown, and dispatches another event to show the screen saver, which will in turn, fire a
stateChangeevent and start the timer for how long the screen saver should be displayed. If, however, the
currentCountis less than the
repeatCount, then it takes the difference in the values and updates the
countdownNumbervariable, which, in turn, updates the displayed value on the countdown screen.
The constructor for the class is at the very bottom of the class; this is where I add event listeners to the
ApplicationStatesingleton and both the
_stateTimerand
_countdownTimerobjects.
Integrate ApplicationTimer into Main.mxml
It doesn't matter where you add ApplicationTimer in main.mxml, but I usually put it at the very bottom or very top. In this example, I'm going to place it all the way at the bottom. The events that ApplicationTimer creates to control the UI can get quite complicated, so I'm going to add two new methods to main.mxml to accommodate the new events,
handleScreenSaverand
handleCountdown. Both methods will handle both the show/hide events being thrown. The added component code will look like:
<local:ApplicationTimer
And the resulting methods will be:; } }
The
handleScreenSaver()method takes a generic Flex
Eventand if the
typeis
EVENT_HIDE_SCREEN_SAVER, the method will set the
visibleproperty of the screen saver to
false, and set
selectedChildof the
ViewStackto
welcomeScreen(the default screen). If the Flex
Event typeis
EVENT_SHOW_SCREEN_SAVER, the method will set the
visibleproperty of the screen saver to
falseand hide all the items in the ViewStack by switching to an empty canvas. This is the best place to fire off any changes or resets to the application that you need to do, including moving assets on the stage, clearing session variables, and so on. You can also set a listener for the
SCREEN_SAVERapplication state in your various classes to achieve the same effect.
The other method I add is
handleCountdown(), which also takes a generic Flex
Event. If the event type is
EVENT_SHOW_COUNTDOWN, it will set the
visibleproperty of the Countdown.mxml component to
true. If the event type is
EVENT_HIDE_COUNTDOWN, it will set the
visibleproperty of the Countdown.mxml component to
false.
Now that I added the ApplicationTimer class, I can update my Countdown component to get the value for
countdownValuefrom it. By binding
applicationTimer.countdownNumberto the
countdownValueproperty on the component, then the countdown component will know whenever the timer updates its
countdownNumbervalue.
The final piece to the application is adding functionality to determine when a user clicks a UI component or is active on a screen. In the ApplicationTimer class, I added a public method called
userInteractionReceived()which will reset the state timer for the
currentState. Whenever the application determines that a user is active on a screen, it will dispatch an event called
extendTimeoutwith its
bubbleproperty set to
true.
Here, I manually dispatch the
extendTimeoutevent from the UserInputSelection.mxml component. For larger applications, I would recommend extending the
Buttonclass (or any other
UIComponent), and have all your applications' interaction objects extend that new object. Then you can dispatch the event in your new class; just make sure the event's
bubblesproperty is set to
trueso the main.mxml application can handle the event accordingly.
To setup this functionality correctly, I need to edit main.mxml to add this change. In main.mxml I have already created a
creationCompleteevent handler, so I'm going to add a new listener to handle the
extendTimeoutevent:
this.addEventListener("extendTimeout", userInteractionReceived);
The new method,
userInteractionReceived(),is relatively simple:
private function userInteractionReceived(e:Event):void { applicationTimer.userInteractionReceived(); }
My final main.mxml now looks like:
<?xml version="1.0" encoding="utf-8"?> <mx:Application <mx:Style <mx:Script> <![CDATA[ [Bindable] private var _applicationState:ApplicationState = ApplicationState.getInstance(); private function onStartClicked():void { myViewStack.selectedChild = userInputScreen; } private function onItemSelected():void { // do nothing yet } private function onCreationComplete():void { // start off with welcome screen first myViewStack.selectedChild = welcomeScreen; this.addEventListener("extendTimeout", userInteractionReceived); } private function userInteractionReceived(e:Event):void { applicationTimer.userInteractionReceived(); }; } } ]]> </mx:Script> <!-- adding an empty canvas allows the 'show' property to fire on the children --> <mx:ViewStack <mx:Canvas <local:Welcome <local:UserInput </mx:ViewStack> <local:Countdown <local:ScreenSaver <local:ApplicationTimer </mx:Application>
There are only a couple steps remaining to complete.
Hide the mouse cursor and disable right-click
At this point, most of the UI work is done for this application. To give that final touch of a kiosk, you need to hide the mouse cursor. Just call
Mouse.hide()and there goes your mouse cursor. The application is ready for a touchscreen.
I would recommend either waiting until the very end of testing to do this, or create a custom right-click menu to hide/show cursor. Hopefully you will have disabled the right-click in the drivers for the touchscreen; this allows you to hide a lot of functionality into your right-click menu, including logs, cursor control options, and other maintenance functions.
Run the application
You can run the application in AIR or even in a browser, such as Internet Explorer or Firefox. Both browsers offer a kiosk mode of some sort. The one in Internet Explorer is better documented. Remember, it's your hardware and software, so you get to decide how it should run.
Where to go from here
The sample application in this article should help you understand what creating a kiosk application entails. It's not that different from a regular application. The tricky parts are the timing of screens and effects, but with a good architecture, that shouldn't be a problem.
I recommend using this article only as a general guide of creating a kiosk application. For a full-fledged kiosk, it doesn't make sense to jam everything together as in this example application. It will get very messy very quickly. You should find a good MVC architecture to use, such as Cairngorm, PureMVC, or Mate. You can then move the timer and state management functionality into the appropriate classes. I would also recommend the use of custom events, because you can pass more data via custom events and avoid having to use such strong references to other components.
The final thing to think about is hardware integration, which I have not covered in this article. There are some creative ways of using hardware with a Flex application that I touched upon at the beginning of this article, such as using ExternalInterface, and there is forward progress in third-party support, such as Merapi (formerly Artemis). At this time, however, there is no official Flex/Flash support for hardware (aside from graphics hardware acceleration). Sometimes, building a kiosk using Flex requires thinking outside of the box. It's definitely possible and not as hard as you might think.
|
https://www.adobe.com/devnet/flex/articles/flex_kiosk.html
|
CC-MAIN-2019-26
|
en
|
refinedweb
|
alright I made this code to try and get a grid of cells across the screen to try and make a cellular automata as I am quite new to programming but when I run this all of my cells are in one place near the bottom center on my screen (I know this because I set them to always display as white to check where they where as it wasn’t working. you may notice a logic function that generally isn’t being called but I just wanted to see if there was something I was missing that is obvious.
import java.util.ArrayList; boolean paused = false; int x = -10; int y = -10; final static ArrayList<cell> cells = new ArrayList(); class cell { boolean state; float xpos, ypos; float age; int identify; cell (float x, float y, int ident) { xpos = x; ypos = y; identify = ident; } void colour() { if (state == true) { fill(255); } else { fill(0); } } void DrawAndPress() { if (mouseX > x && mouseX < x+10 && mouseY > y && mouseY < y+10 && mousePressed) { state = !state; } rect(x, y, 10, 10); } void Logic() { } } void setup() { fullScreen(); background(0); noStroke(); for (int i = 0; i < (width*height)/10000; i = i+1) { x = x+10; if (x > width) { y = y+10; x = 0; } cells.add( new cell(x, y, i)); } } void draw() { for (cell c : cells) c.colour(); for (cell c : cells) c.DrawAndPress(); if (!paused) { for (cell c : cells) c.Logic(); } }
|
https://discourse.processing.org/t/why-does-my-for-loop-create-cells-in-one-specific-area-instead-of-in-a-grid/14197
|
CC-MAIN-2022-27
|
en
|
refinedweb
|
An entity, a standard data class. More...
#include <Entity.hpp>
An entity, a standard data class.
Entity is a class for standardization of expression method using on network I/O by XML. If Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a recommended semi-protocol of message for expressing a data class. Following the semi-protocol Entity is not imposed but encouraged.
As we could get advantages from standardization of message for network I/O with Invoke, we can get additional advantage from standardizing expression method of data class with Entity. We do not need to know a part of network communication. Thus, with the Entity, we can only concentrate on entity's own logics and relationships between another entities. Entity does not need to how network communications are being done.
I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi protocol for network I/O but not a essential protocol must be kept. The expression method of Entity, using on network I/O, is expressed by XML string.
If your own network system has a critical performance issue on communication data class, it would be better to using binary communication (with ByteArray or boost::serialization). Don't worry about the problem! Invoke also provides methods for binary data (ByteArray).
Definition at line 115 of file Entity.hpp.
Get a key that can identify the Entity uniquely.
If identifier of the Entity is not atomic value, returns a string represents the composite identifier. If identifier of the Entity is not string, converts the identifier to string and returns the string.
Reimplemented in samchon::protocol::InvokeParameter, samchon::templates::external::ExternalSystem, samchon::examples::tsp::GeometryPoint, samchon::templates::external::ExternalSystemRole, samchon::templates::distributed::DistributedProcess, and samchon::templates::slave::InvokeHistory.
Definition at line 133 of file Entity.hpp.
Referenced by samchon::protocol::EntityGroup< std::deque< System * >, System, int >::construct(), samchon::protocol::EntityGroup< std::deque< System * >, System, int >::count(), samchon::protocol::EntityGroup< std::deque< System * >, System, int >::find(), samchon::protocol::EntityGroup< std::deque< System * >, System, int >::get(), samchon::templates::external::ExternalSystemArray< Viewer >::getRole(), samchon::protocol::EntityGroup< std::deque< System * >, System, int >::has(), and samchon::templates::external::ExternalSystemArray< Viewer >::hasRole().
|
http://samchon.github.io/framework/api/cpp/d0/d3e/classsamchon_1_1protocol_1_1Entity.html
|
CC-MAIN-2022-27
|
en
|
refinedweb
|
One of the main reasons to adopt REST is the simplicity of the API, compared to the juggling of formats required to send and receive SOAP messages. We’ve had a long history of creating toolkits and libraries to ease the burden of using SOAP as a transport – so much so that when I first started looking at Python again as a language (not an accident that it was around the same time Heroku added it to their polyglot platform) … I really wanted to take a step back and see how simple I could make a script functional with Force.com. Not make something intended as fully functional application, or a web based interface, or handling multiple tasks or anything – just how simple could I make a script which logs in, performs a query, and then displays the results. Make it as small as possible with as few dependencies as possible.
Here’s the result, a command line app which opens a browser to handle OAuth, grabs the tokens, does a SOQL query in REST and displays the results:
import os import urlparse import urllib from restful_lib import Connection consumer_key = 'CONSUMERKEY' callback = '' login_url = ''+consumer_key+'&redirect_uri='+callback os.system("open '"+login_url+"'"); url_result = raw_input('If the page says "Remote Access Application Authorization", what is the URL?') result = dict(urlparse.parse_qsl(url_result.split("success#")[1])); token = urllib.unquote(result["access_token"]) instance_url = urllib.unquote(result["instance_url"]) conn = Connection(instance_url+'/services/data/v20.0') result = conn.request_get('query',args={'q':'SELECT ID FROM CONTACT'},headers={'Authorization': 'OAuth '+token}); print result
Twenty lines of code. You do need to cut and paste the post login URL from the browser back into the Python script in this flow. The only dependency is a REST library from Google. I also had to make sure my httplib was up to date (the version that comes with Snow Leopard is apparently slightly dated). The line:
os.system("open '"+login_url+"'");
Is OS X specific (opens the default web browser to the URL), but you could easily modify the script to handle a Windows based browser. Now since writing this, I’ve gone on updated it to handle queries based on user input, and some utility functions to do things like enter and remember the token (so that you don’t have like a dozen browser tabs open…) – but even with that level of functionality the script is still more like sixty lines of code. Next step will probably be to handle the login with “password” grant type of OAuth to remove the browser requirement completely (but I do like the browser usage as an example of how OAuth works with most use cases).
This script is among my gists on GitHub, and I’ll probably add the more functional script as a proper repository down the road. But you can see how integration with the Force.com platform doesn’t need to be a heavy-handed affair, thanks to REST and OAuth being in your toolbox.
|
https://developer.salesforce.com/blogs/2011/11/insanely-simple-python-rest-script
|
CC-MAIN-2022-27
|
en
|
refinedweb
|
Prerequisites for Libraries.
The following steps will help ensure your modules and components are ready for the New Architecture.
TurboModules: Define Specs in JavaScript
Under the TurboModule system, the JavaScript spec will serve as the source of truth for the methods that are provided by each native module. Without the JavaScript spec, it is up to you to ensure your public method signatures are equivalent on Android and iOS.
As the first step to adopting the new architecture, you will start by creating these specs for your native modules. You can do this, right now, prior to actually migrating your native module library to the new architecture. Your JavaScript spec will be used later on to generate native interface code for all the supported platforms, as a way to enforce uniform APIs across platforms.
Writing the JavaScript Spec
The JavaScript spec defines all APIs that are provided by the native module, along with the types of those constants and functions. Using a typed spec file allows us to be intentional and declare all the input arguments and outputs of your native module’s methods.
info
JavaScript spec files can be written in either Flow or TypeScript. The Codegen process will automatically choose the correct type parser based on your spec file's extension (
.js for Flow,
.ts or
.tsx for TypeScript). Note that TypeScript support is still in beta—if you come across any bugs or missing features, please report them.
TurboModules
JavaScript spec files must be named
Native<MODULE_NAME>.js (for TypeScript use extension
.ts or
.tsx) and they export a
TurboModuleRegistry
Spec object. The name convention is important because the Codegen process looks for modules whose spec file (either JavaScript of TypeScript) starts with the keyword
Native.
The following snippets show a basic spec template, written in Flow as well as TypeScript.
- Flow
- TypeScript
// @flow
import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport';
import {TurboModuleRegistry} from 'react-native';
export interface Spec extends TurboModule {
+getConstants: () => {||};
// your module methods go here, for example:
getString(id: string): Promise<string>;
}
export default (TurboModuleRegistry.get<Spec>('<MODULE_NAME>'): ?Spec);
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';
export interface Spec extends TurboModule {
readonly getConstants: () => {};
// your module methods go here, for example:
getString(id: string): Promise<string>;
}
export default TurboModuleRegistry.get<Spec>('<MODULE_NAME>');
Fabric Components
JavaScript spec files must be named
<FABRIC COMPONENT>NativeComponent.js (for TypeScript use extension
.ts or
.tsx) and they export a
HostComponent object. The name convention is important: the Codegen process looks for components whose spec file (either JavaScript or TypeScript) ends with the suffix
NativeComponent.
The following snippet shows a basic JavaScript spec template, written in Flow as well as TypeScript.
- Flow
- TypeScript
// @flow strict-local
import type {ViewProps} from 'react-native/Libraries/Components/View/ViewPropTypes';
import type {HostComponent} from 'react-native';
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
type NativeProps = $ReadOnly<{|
...ViewProps,
// add other props here
|}>;
export default (codegenNativeComponent<NativeProps>(
'<FABRIC COMPONENT>',
): HostComponent<NativeProps>);
import type { ViewProps } from 'ViewPropTypes';
import type { HostComponent } from 'react-native';
import codegenNativeComponent from 'react-native/Libraries/Utilities/codegenNativeComponent';
export interface NativeProps extends ViewProps {
// add other props here
}
export default codegenNativeComponent<NativeProps>(
'<FABRIC COMPONENT>'
) as HostComponent<NativeProps>;
Supported Types
When using Flow or TypeScript, you will be using type annotations to define your spec. Keeping in mind that the goal of defining a JavaScript spec is to ensure the generated native interface code is type safe, the set of supported types will be those that can be mapped one-to-one to a corresponding type on the native platform.
In general, this means you can use primitive types (strings, numbers, booleans), as well as function types, object types, and array types. Union types, on the other hand, are not supported. All types must be read-only. For Flow: either
+ or
$ReadOnly<> or
{||} objects. For TypeScript:
readonly for properties,
Readonly<> for objects, and
ReadonlyArray<> for arrays.
See Appendix I. Flow Type to Native Type Mapping. (TypeScript to Native Type Mapping will be added soon.)
Be Consistent Across Platforms and Eliminate Type Ambiguity
Before adopting the new architecture in your native module, you will need to ensure your methods are consistent across platforms. This is something you will realize as you set out to write the JavaScript spec for your native module - remember, that JavaScript spec defines what the methods will look like on all supported platforms.
If your existing native module has methods with the same name on multiple platforms, but with different numbers or types of arguments across platforms, you will need to find a way to make these consistent. If you have methods that can take two or more different types for the same argument, you will also need to find a way to resolve this type ambiguity as type unions are intentionally not supported.
Make sure autolinking is enabled
Autolinking is a feature of the React Native CLI that simplifies the installation of third-party React Native libraries. Instructions to enable autolinking are available at.
Android
On Android, this generally requires you to include
native_modules.gradle in both your
settings.gradle[.kts] and
build.gradle[.kts].
If you used the default template provided with React Native (i.e. you used
yarn react-native init <Project>), then you have autolinking already enabled.
You can anyway verify that you have it enabled with:
$ grep -r "native_modules.gradle" android
android/app/build.gradle:apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
android/settings.gradle:apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
...
iOS
On iOS, this generally requires your library to provide a Podspec (see
react-native-webview for an example).
info
To determine if your library is set up for autolinking, check the CocoaPods output after running
pod install (or
arch -x86_64 pod install in case of a Mac M1) on an iOS project. If you see "auto linking library name", you are all set to go.
Preparing your JavaScript codebase for the new React Native Renderer (Fabric)
The new renderer also known as Fabric doesn’t use the UIManager so direct calls to UIManager will need to be migrated. Historically, calls to UIManager had some pretty complicated patterns. Fortunately, we’ve created new APIs that are much cleaner. These new APIs are forwards compatible with Fabric so you can migrate your code today and they will work properly when you turn on Fabric!
Fabric will be providing new type safe JS APIs that are much more ergonomic than some of the patterns we've seen in product code today. These APIs require references to the underlying component, no longer using the result of
findNodeHandle.
findNodeHandle is used to search the tree for a native component given a class instance. This was breaking the React abstraction model.
findNodeHandle won’t be compatible with React 18 once we are ready to roll that out. Deprecation of
findNodeHandle in React Native is similar to the deprecation of
findDOMNode in React DOM.
While we know that all deprecations are a hassle, this guide is intended to help people update components as smoothly as possible. Here are the steps you need to take to get your JS codebase ready for Fabric:
- Migrating findNodeHandle / getting a HostComponent
- Migrating
.measure*()
- Migrating off
setNativeProps
- Move the call to
requireNativeComponentto a separate file
- Migrating off
dispatchViewManagerCommand
- Using
codegenNativeComponent
Migrating
findNodeHandle / getting a
HostComponent
Much of the migration work requires a HostComponent ref to access certain APIs that are only attached to host components (like View, Text, or ScrollView). HostComponents are the return value of calls to
requireNativeComponent.
findNodeHandle tunnels through multiple levels of component hierarchy to find the nearest native component.
As a concrete example, this code uses
findNodeHandle to tunnel from
ParentComponent through to the
View rendered by
ChildComponent.
class ParentComponent extends React.Component<Props> {
_ref: ?React.ElementRef<typeof ChildComponent>;
render() {
return <ChildComponent ref={this._captureRef} onSubmit={this._onSubmit} />
}
_captureRef: (ref) => {
this._ref = ref;
}
_onSubmit: () => {
const nodeHandle = findNodeHandle(this._ref);
if (nodeHandle) {
UIManager.measure(nodeHandle, () => {});
}
}
}
class ChildComponent extends React.Component<Props> {
render() {
return (
<View>
<SubmitButton onSubmit={props.onSubmit} />
</View>
);
}
}
We can’t convert this call to
this._ref.measure because
this._ref is an instance to
ChildComponent, which is not a HostComponent and thus does not have a
measure function.
ChildComponent renders a
View, which is a HostComponent, so we need to get a reference to
View instead. There are typically two approaches to get what we need. If the component we need to get the ref from is a function component using
forwardRef is probably the right choice. If it is a class component with other public methods, adding a public method for getting the ref is an option. Here are examples of those two forms:
Using
forwardRef
class ParentComponent extends React.Component<Props> {
_ref: ?React.ElementRef<typeof ChildComponent>;
render() {
return <ChildComponent ref={this._captureRef} onSubmit={this._onSubmit} />
}
_captureRef: (ref) => {
this._ref = ref;
}
_onSubmit: () => {
if (this._ref != null)
this._ref.measure(() => {});
}
}
}
const ChildComponent = React.forwardRef((props, forwardedRef) => {
return (
<View ref={forwardedRef}>
<SubmitButton onSubmit={props.onSubmit} />
</View>
);
});
Using a getter, (note the addition of
getViewRef)
class ParentComponent extends React.Component<Props> {
_ref: ?React.ElementRef<typeof ChildComponent>;
render() {
return <ChildComponent ref={this._captureRef} onSubmit={this._onSubmit} />
}
_captureRef: (ref) => {
this._ref = ref;
}
_onSubmit: () => {
if (this._ref != null)
this._ref.getViewRef().measure(() => {});
}
}
}
class ChildComponent extends React.Component<Props> {
_ref: ?React.ElementRef<typeof View>;
render() {
return (
<View ref={this._captureRef}>
<SubmitButton onSubmit={props.onSubmit} />
</View>
);
}
getViewRef(): ?React.ElementRef<typeof View> {
return this._ref;
}
_captureRef: (ref) => {
this._ref = ref;
}
}
Migrating
.measure*()
Let’s take a look at an example calling
UIManager.measure. This code might look something like this
const viewRef: React.ElementRef<typeof View> = /* ... */;
const viewHandle = ReactNative.findNodeHandle(viewRef);
UIManager.measure(viewHandle, (x, y, width, height) => {
// Use layout metrics.
});
In order to call
UIManager.measure* we need to call
findNodeHandle first and pass in those handles. With the new API, we instead call
measure directly on native refs without
findNodeHandle. The example above with the new API looks like this:
const viewRef: React.ElementRef<typeof View> = /* ... */;
viewRef.measure((x, y, width, height) => {
// Use layout metrics.
});
findNodeHandle can be called with any component as an argument, but the new
.measure* can only be called on native refs. If the ref originally passed into
findNodeHandle is not a native ref to start with, use the strategies above in getting a HostComponent to find the native ref.
Migrating off
setNativeProps
setNativeProps will not be supported in the post-Fabric world. To migrate, move all
setNativeProp values to component state.
Example
class MyComponent extends React.Component<Props> {
_viewRef: ?React.ElementRef<typeof View>;
render() {
const {somePropValue} = this.props;
return <View
onPress={this._onSubmit}
ref={this._captureRef}
someProp={somePropValue}
style={styles.view} />
}
_captureRef: (ref) => {
this._viewRef = ref;
}
_onSubmit: () => {
this._viewRef.setNativeProps({
style: styles.submittedView,
accessibility: true
});
// ...other logic for onSubmit
}
}
const styles = StyleSheet.create({
view: { backgroundColor: 'white'},
submittedView: {borderWidth: 1}
});
In this example when the View is pressed there is a
setNativeProps call to update the style and accessibility props of the component. To migrate this component it’s important to understand its current behavior using
setNativeProps.
Pre-Fabric, Component Props Persist
On first render, the component props are those declared in the render function. After the View is pressed
_onSubmit calls
setNativeProps with updated prop values.
The resulting component can be represented as such:
<View
accessibility={true}
onPress={this._onSubmit}
ref={this._captureRef}
someProp={somePropValue}
style={[styles.view, styles.submittedView]}
/>
Note that all prop values set in the render function are unchanged even though
setNativeProps didn’t pass those props. Also,
style is now the merged value of its value prior to
_onSubmit and
styles.submittedView. This is the important takeaway: in our current pre-Fabric world, component props persist. The platform view caches the prop values its passed from the JS side. If this wasn’t the case then following the setNativeProps call, React Native would have rendered a component like this:
<View accessibility={true} style={styles.submittedView} />
The fact that React Native stores some internal state of each component that isn’t explicitly declared in last render is what Fabric intends to fix.
Moving
setNativeProps to state
Taking those caveats into account, a proper migration would look like this:
class MyComponent extends React.Component<Props> {
state = {
hasSubmitted: false,
accessibility: false
};
render() {
const {somePropValue} = this.props;
const submittedStyle = this.state.hasSubmitted ? styles.submittedView: null;
return <View
accessibility={this.state.accessibility}
onPress={this._onSubmit}
someProp={somePropValue}
style={[styles.view, submittedStyle]} />
}
_onSubmit: () => {
this.setState(state => ({ ...state, hasSubmitted: true }));
// ...other logic for onSubmit
}
}
const styles = StyleSheet.create({
view: { backgroundColor: 'white'},
submittedView: {borderWidth: 1}
});
- We are using the
hasSubmittedflag to represent whether or not we want to apply
styles.submittedView. If the style was dynamic then it makes sense to store the style object in state
accessibilityis now explicitly passed to the View component as a boolean. This differs from the prior implementation where
accessibilitywasn’t passed as a prop in initial render but in this case we know the non-specification of
accessibilityis handled in the same way as
accessibilty={false}
Be wary of your assumptions as uncaught subtleties can introduce differences in behavior! It’s a good idea to have snapshot tests of your component as they will highlight any differences pre and post your migration.
Move the call to
requireNativeComponent to a separate file
This will prepare for the JS to be ready for the new codegen system for the new architecture. The new file should be named
<ComponentName>NativeComponent.js.
Old way
const RNTMyNativeView = requireNativeComponent('RNTMyNativeView');
[...]
return <RNTMyNativeView />;
New way
import RNTMyNativeViewNativeComponent from './RNTMyNativeViewNativeComponent';
[...]
return <RNTMyNativeViewNativeComponent />;
import { requireNativeComponent } from 'react-native';
const RNTMyNativeViewNativeComponent = requireNativeComponent(
'RNTMyNativeView'
);
export default RNTMyNativeViewNativeComponent;
Flow support
If
requireNativeComponent is not typed, you can temporarily use the
mixed type to fix the Flow warning, for example:
import type { HostComponent } from 'react-native/Libraries/Renderer/shims/ReactNativeTypes';
// ...
const RCTWebViewNativeComponent: HostComponent<mixed> =
requireNativeComponent < mixed > 'RNTMyNativeView';
Migrating off
dispatchViewManagerCommand
Similar to one above, in an effort to avoid calling methods on the UIManager, all view manager methods are now called through an instance of
NativeCommands.
codegenNativeCommands is a new API to code-generate
NativeCommands given an interface of your view manager’s commands.
Before
class MyComponent extends React.Component<Props> {
_moveToRegion: (region: Region, duration: number) => {
UIManager.dispatchViewManagerCommand(
ReactNative.findNodeHandle(this),
'moveToRegion',
[region, duration]
);
}
render() {
return <MyCustomMapNativeComponent onPress={this._moveToRegion} />
}
}
Creating the NativeCommands with
codegenNativeCommands
import codegenNativeCommands from 'react-native/Libraries/Utilities/codegenNativeCommands';
import type { HostComponent } from 'react-native/Libraries/Renderer/shims/ReactNativeTypes';
type MyCustomMapNativeComponentType = HostComponent<NativeProps>;
interface NativeCommands {
+moveToRegion: (
viewRef: React.ElementRef<MyCustomMapNativeComponentType>,
region: MapRegion,
duration: number,
) => void;
}
export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({
supportedCommands: ['moveToRegion'],
});
Note:
- The first argument in the
moveToRegioncommand is a HostComponent ref of the native component
- The arguments to the
moveToRegioncommand are enumerated in the signature
- The command definition is co-located with the native component. This is an encouraged pattern
- Ensure you have included your command name in
supportedCommandsarray
Using Your Command
import {Commands, ... } from './MyCustomMapNativeComponent';
class MyComponent extends React.Component<Props> {
_ref: ?React.ElementRef<typeof MyCustomMapNativeComponent>;
_captureRef: (ref) => {
this._ref = ref;
}
_moveToRegion: (region: Region, duration: number) => {
if (this._ref != null) {
Commands.moveToRegion(this._ref, region, duration);
}
}
render() {
return <MyCustomMapNativeComponent
ref={this._captureRef}
onPress={this._moveToRegion} />
}
}
Updating Native implementation
In the example the code-generated
Commands will dispatch
moveToRegion call to the native component’s view manager. In addition to writing the JS interface, you’ll need to update your native implementation signatures to match the dispatched method call. See the mapping for Android argument types andiOS argument types for reference.
iOS
RCT_EXPORT_METHOD(moveToRegion:(nonnull NSNumber *)reactTag
region:(NSDictionary *)region
duration:(double)duration
{
...
}
Android
- Java
- Kotlin
fun receiveCommand(
view: ReactMapDrawerView?, commandId: String?, args: ReadableArray?
) {
when (commandId) {
"moveToRegion" -> {
if (args != null) {
val region: ReadableMap = args.getMap(0)
val durationMs: Int = args.getInt(1)
// ... act on the view...
}
}
}
}
// receiveCommand signature has changed to receive String commandId
@Override
public void receiveCommand(
ReactMapDrawerView view, String commandId, @Nullable ReadableArray args) {
switch (commandId) {
case "moveToRegion":
if (args == null) {
break;
}
ReadableMap region = args.getMap(0);
int durationMs = args.getInt(1);
// ... act on the view...
break;
}
}
|
http://reactnative.dev/docs/new-architecture-library-intro
|
CC-MAIN-2022-27
|
en
|
refinedweb
|
In this post, you’ll learn how to use Python to remove a character from a string. You’ll learn how to do this with the Python
.replace() method as well as the Python
.translate() method. Finally, you’ll learn how to limit how many characters get removed (say, if you only wanted to remove the first x number of instances of a character).
The Quick Answer: Use string.replace()
Why Remove Characters from Strings in Python?
When you download data from different sources you’ll often receive very messy data. Much of your time will be spent cleaning that data and prepping it for analysis. Part of that data preparation will be cleaning your string and may involve removing certain characters.
Because of this being a very common challenge, this tutorial was developed to help you in your journey towards easier data analysis! Let’s get started!
Use the Replace Function to Remove Characters from a String in Python
Python comes built-in with a number of string methods. One of these methods is the
.replace() method that, well, lets you replace parts of your string. Let’s take a quick look at how the method is written:
str.replace(old, new, count)
When you append a
.replace() to a string, you identify the following parameters:
old=: the string that you want to replace,
new=: the string you want to replace with, and
count=: the number of replacements you want to make
Now that you’ve learned how the
.replace() method is written in Python, let’s take a look at an example. You’ll be given a string and will want to remove all of the
? mark characters in the string:
old_string = 'h?ello, m?y? name? is ?nik!' new_string = old_string.replace('?', '') print(new_string) # Returns: hello, my name is nik!
Let’s take a look at what we’ve done here to remove characters from a string in Python:
- We applied the .
replace()method to our string,
old_string
- We indicated we wanted to replace the
?character with an empty string
- We assigned this newly modified string to the variable
new_string
You can see here, just how easy it is to remove characters from a string in Python!
Now let’s learn how to use the Python string
.translate() method to do just this.
Use the Translate Function to Remove Characters from a String in Python
Similar to the example above, we can use the Python string
.translate() method to remove characters from a string.
This method is a bit more complicated and, generally, the
.replace() method is the preferred approach. The reason for this is that you need to define a translation table prior to actually being able to replace anything. Since this step can often be overkill and tedious for replacing only a single character. Because of this, we can use the
ord() function to get a characters unicode value to simplify this process.
Let’s see how this can be done with the same example as above:
old_string = 'h?ello, m?y? name? is ?nik!' new_string = old_string.translate({ord('?'):None}) print(new_string) # Returns: hello, my name is nik!
Let’s explore what we’ve done here:
- We use the
ord()function to return the unicode value for whatever character we want to replace
- We map this to a
Nonevalue to make sure it removes it
You can see here that this is a bit more cumbersome than the previous method you learned.
Remove Only n Number of Characters from a String in Python
There may be some times that you want to only remove a certain number of characters from a string in Python. Thankfully, the Python
.replace() method allows us to easily do this using the
count= parameter. By passing in a non-zero number into this parameter we can specify how many characters we want to remove in Python.
This can be very helpful when you receive string where you only need to remove the first iteration of a character, but others may be valid.
Let’s take a look at an example:
old_string = 'h?ello, my name is nik! how are you?' new_string = old_string.replace('?', '', 1) print(new_string) # Returns: hello, my name is nik! how are you?
We can see here that by passing in
count=1, that only the very first replacement was made. Because of this, we were able to remove only one character in our Python string.
Remove Multiple Characters from a String in Python
There may also be times that you want to replace multiple different characters from a string in Python. While you could simply chain the method, this is unnecessarily repetitive and is difficult to read.
Let’s take a look at how we can iterate over a string of different characters to remove those characters from a string in Python.
The reason we don’t need to loop over a list of strings, is that strings themselves are iterable. We could pass in a list of characters, but we don’t need to. Let’s take a look at an example where we want to replace both the
? and the
! characters from our original string:
a_string = 'h?ello, my name is nik! how are you?' for character in '!?': a_string = a_string.replace(character, '') print(a_string) # hello, my name is nik how are you
One thing you’ll notice here is that we are replacing the string with itself. If we didn’t do this (and, rather, replaced the string and assigned it to another variable), we’d end up only replacing a single character in the end.
We can also accomplish this using the regular expression library
re. We can pass in a group of characters to remove and replace them with a blank string.
Let’s take a look at how we can do this:
import re old_string = 'h?ello, my name is nik! how are you?' new_string = re.sub('[!?]', '', old_string) print(new_string) # Returns: hello, my name is nik how are you
What we’ve done here is pass in a string that contains a character class, meaning it’ll take any character contained within the square brackets
[].
The
re library makes it easy to pass in a number of different characters you want to replace and removes the need to run a for loop. This can be more efficient as the length of your string grows.
Conclusion
In this post, you learned how to remove characters from a string in Python using the string
.replace() method, the string
.translate() method, as well as using regular expression in
re.
To learn more about the regular expression
.sub() method, check out the official documentation here.
Hey, Nik!
There are two tiny mistakes in the penultimate section of code on this page:
The output of this code section (last line) should NOT contain characters of a question mark & of an exclamation point:
a_string = ‘h?ello, my name is nik! how are you?’
for character in ‘!?’:
a_string = a_string.replace(character, ”)
print(a_string)
# a_string: hello, my name is nik! how are you?
PS Btw thanks for your content: the articles are great, explanations are clear. Keep going!
Hi Dmitry,
Thanks so much for catching that! I’ve updated the article.
Thank you also for your feedback! It means a lot to me! 🙂
|
https://datagy.io/python-remove-character-from-string/
|
CC-MAIN-2022-27
|
en
|
refinedweb
|
IESDataset
from panda3d._rplight import IESDataset
- class IESDataset
Bases:__()
This constructs a new
IESDatasetwith no data set.
- __init__(param0: IESDataset)
- generateDatasetTextureInto(dest_tex: panda3d.core.Texture, z: int)
This generates the LUT into a given dataset texture. The x-axis referes to the vertical_angle, whereas the y-axis refers to the horizontal angle.
2D Texture Array.
- setCandelaValues(candela_values: panda3d.core.PTA_float)
This sets the candela values of the dataset. They should be an interleaved 2D array with the dimensions vertical_angles x horizontal_angles. They also should be normalized by dividing by the maximum entry.
- setHorizontalAngles(horizontal_angles: panda3d.core.PTA_float)
This sets the list of horizontal angles of the dataset.
- setVerticalAngles(vertical_angles: panda3d.core.PTA_float)
This sets the list of vertical angles of the dataset.
|
https://docs.panda3d.org/1.10/python/reference/panda3d._rplight.IESDataset
|
CC-MAIN-2022-27
|
en
|
refinedweb
|
A flash policy server. More...
#include <FlashPolicyServer.hpp>
A flash policy server.
FlashPolicyServer is a policy_ server replying cross-domain-policy_ to flash clients.
Definition at line 23 of file FlashPolicyServer.hpp.
Default constructor.
The cross-domain-policy_ is to accept all, any client.
Definition at line 37 of file FlashPolicyServer.hpp.
Construct from custom policy_.
Definition at line 56 of file FlashPolicyServer.hpp.
Open server.
Definition at line 64 of file FlashPolicyServer.hpp.
Get policy.
Definition at line 82 of file FlashPolicyServer.hpp.
Accept client.
Accepts flash client and replies cross-domain-policy_
Definition at line 98 of file FlashPolicyServer.hpp.
cross-domain-policy_
Definition at line 29 of file FlashPolicyServer.hpp.
|
http://samchon.github.io/framework/api/cpp/d2/d55/classsamchon_1_1protocol_1_1FlashPolicyServer.html
|
CC-MAIN-2022-27
|
en
|
refinedweb
|
I was working recently on a annotation based retry mechanism. The idea is simple: when a method invocation fails, it should retry the call based on some retry policy. Sample code:
public class ServiceBroker { private RemoteService remoteService; @Retryable(retryIdentifierBean = "retry.default") public void destroySession(final String token) throws BusinessException { //invoke a service or do other business logic stuff here remoteService.destroySession(token); } public void setRemoteService(RemoteService remoteService) { this.remoteService = remoteService; } }
I won’t dive into details about the aspect handling the retry mechanism. Notice that the destroySession method is annotated with @Retryable annotation which is provided with the spring bean id retry.default representing the retry policy.
The interesting question is how could I unit test this? How to prove that the implementation of my code indeed works as intended?
At the first glance, the only approach seems to be an integration tests. But suppose that ServiceBroker has many heavy dependencies which might be hard to configure. In the same time, all you want is to test the retry mechanism only, without worrying about anything else.
The solution is a combination of integration & unit test. Instead of loading a spring application context with all beans configured, the following trick can be applied:
public class ServiceBrokerTest { @InjectMocks private ServiceBroker victim; @Mock private RemoteService remoteService; private GenericXmlApplicationContext context; @Before public void setUp() { // Configure the bean to be added to application context and set mock dependencies, to avoid bean initialization exception. final ServiceBroker broker = new ServiceBroker(); initMocks(this); //set here other dependencies on victim if required context = new GenericXmlApplicationContext(); final AutowireCapableBeanFactory autowireFactory = context.getAutowireCapableBeanFactory(); victim = (ServiceBroker) autowireFactory.initializeBean(broker, "serviceBrokerBeanName"); } @After public void tearDown() { context.close(); } }
The above code shows how the unit test is set up. Instead of using the manually instantiated ServiceBroker, we use the one initialized by spring using AutowireCapableBeanFactory. This trick, allows to unit test the proxy of the ServiceBroker, instead the ServiceBroker itself. Thus we can test the retry mechanism itself (continuation of ServiceBrokerTest):
private static final int NUMBER_OF_RETRIES = 5; @Test public void shouldRetryExpectedNumberOfTimes() throws Exception { Mockito.doThrow(new TimeoutException()).when(remoteService).destroySession(Mockito.anyString()); victim.destroySession(""); verify(remoteService, times(NUMBER_OF_RETRIES)).destroySession( Mockito.anyString()); }
The above unit test, asserts that the remoteService was invoked expected number of times when it fails.
Conclusion
The above example shows an approach of easily unit testing aspects in a spring based application.comments powered by Disqus
|
http://alexo.github.io/blog/unit-testing-aspects-with-spring/
|
CC-MAIN-2017-39
|
en
|
refinedweb
|
You may want to search:
Hot Selling Japanese Glass Teapot Turkish Set For The Gas Stove
US $5.2-5.7 / Piece
1000 Pieces (Min. Order)
Square silicone mat set for baking heat proof silicone dish pot place mat
US $0.5-2 / Piece
1 Piece (Min. Order)
JUKI smt pick and place machine Feeder CF FF CTFR AF TAPE GUIDE SET
US $1-10 / Set
1 Set (Min. Order)
10kw to 50kw generator set powered by yamar engine
US $1000-30000 / Set
1 Set (Min. Order)
Supply all kinds of 30w speaker,fm radio speaker with usb port in india one set
US $18-25 / Piece
1 Piece (Min. Order)
High Quality 3pc Stianless steel Bathroom set
2400 Sets (Min. Order)
FUJI CP6 8X2MM feeder lever link full set AWCA2200 AWCA3906 MCA0391
US $5-10 / Piece
1 Piece (Min. Order)
2016 modern wicker dining set with tempered glass top outdoor furniture
US $230-555 / Set
6 Sets (Min. Order)
SWITEK robot alibaba come from china for a set of packaging machine
US $20-30 / Set
1 Set (Min. Order)
Supply all kinds of wireless garden speakers,professional active speaker set
US $32-36 / Piece
1 Piece (Min. Order)
Japanese Cuisine Color-Dough Set, Modeing Clay Set Toy
US $1.19-1.34 / Set
5 Cartons (Min. Order)
different shapes natural color bamboo utensils set hot sell in Japan
US $4.99-5.99 / Set
100 Cartons (Min. Order)
CBJ Joint color Mat 8 set /( #120302)
16 Sets (Min. Order)
Bathroom wall mounted brass spa room bath-Shower sets
US $20-80 / Set
50 Sets (Min. Order)
Cost-effective and Delicious soft rice cracker sets for your babies made in Japan
US $16-20 / Set
6 Sets (Min. Order)
Organic healthy puer tea gift wedding best sell product in japan
US $12-28 / Box
1 Box (Min. Order)
cas 541-02-6 pure silicon oil d5 cyclohexasiloxane korea cosmetic raw materials supplier
US $3.4-4.5 / Kilogram
500 Kilograms (Min. Order)
Folding Wood Bedside Commode Chair Seat With Antimicrobial Finishing
US $1275.0-1500.0 / Set
1 Set (Min. Order)
wire extruder machinery
US $1000-180000 / Set
1 Set (Min. Order)
Second hand small cheap komatsu d85 bulldozer
US $24000.0-26000.0 / Unit
1 Unit (Min. Order)
super water absorbency and soft material self-sufficient wholesale japanese wash cloth
US $0.1-4.09 / Piece
2000 Pieces (Min. Order)
Easy to use and Fashionable ambulance with various places
US $5-10 / Set
1 Set (Min. Order)
yamaha yv100xg track slider KV7-M2676-S2X
US $130.0-150.0 / Piece
1 Piece (Min. Order)
2017 Beautiful Girls Panty Sets Japan Sexy Images Fancy Latest Bra
US $2.2-2.3 / Pieces
10 Pieces (Min. Order)
2018 Trade Assurance New Style antique door style modern movable coffee table
US $20-300 / Set
5 Sets (Min. Order)
biryani cooking pot large stock pot for shopping
US $4.2-6.2 / Pieces
2000 Pieces (Min. Order)
japanese cast iron cookware
2000 Sets (Min. Order)
Cheap japanese patio furniture outdoor plastic wood table
US $65-70 / Set
10 Sets (Min. Order)
import solid wood ash small table japanese outdoor coffee table garden small tea table
US $1-10 / Unit
5 Units (Min. Order)
Sushi Boat for/in place of sushi boat tray leaf dish plate lunch box
US $0.01-2 / Set
20 Cartons (Min. Order)
679 wooden New design luxury dining table for wholesales
US $319-409 / Piece
5 Pieces (Min. Order)
2016 Full Auto electric stackable washer dryer discount with Warranty
US $3750-4500 / Set
1 Set (Min. Order)
6ft outdoor folding table outdoor fire pit table
US $15-25 / Piece
100 Pieces (Min. Order)
The Japanese Biscuits Confectionery
US $10000-50000 / Set
1 Set (Min. Order)
Popular Hot Sale Sushi Placing Japanese Wooden Tray
US $0.059-0.72 / Piece
50000 Pieces (Min. Order)
entertainment,tube8 japanese for public place of entertainment,a4 graph paper to print
US $0.12-0.75 / Pack
10000 Packs (Min. Order)
2015 best selling wholesale high quality japanese women sexy lingerie free pictures
US $3-9 / Piece
50 Pieces (Min. Order)
High availability japanese shoe deodorizer bag
US $0.5-0.8 / Pair
1000 Pairs (Min. Order)
japanese tea set health premium best white tea brands
US $4.5-6 / Piece
20 Pieces (Min. Order)
Precision Heavy Duty Crosscutting Machine
US $1000-200000 / Set
1 Set (Min. Order)
Excellent quality antique robot vacuum cleaner japanese factories
US $1-3000 / Set
3 Sets (Min. Order)
melamine dinner plates wholesale japanese products
US $0.1-1 / Piece
3000 Pieces (Min. Order)
with drawer for korea and japan market magic mop bucket
US $9.6-10.4 / Piece
900 Pieces (Min. Order)
PP 3D promotional dinner place mat with coaster
US $0.02-0.99 / Set
1000 Sets (Min. Order)
set-up LED Lamp and LED Bulb assembly line for making of of finished goods from CKD components
US $75000-99000 / Piece
1 Piece (Min. Order)
portable Gasoline Generator set branded Japan 3kw
US $78-150 / Set
12 Sets (Min. Order)
Supply all kinds of active speaker set,square mini portable speaker
US $18-25 / Piece
1 Piece (Min. Order)
modern design outdoor dining set with umbrella garden furniture sets
US $230-555 / Set
6 Sets (Min. Order)
Supply all kinds of speaker nfc,speaker with led light,set of 2 wireless portable speakers for computer
US $40-55 / Piece
1 Piece (Min. Order)
Buying Request Hub
Haven't found the right supplier yet ? Let matching verified suppliers find you. Get Quotation NowFREE
Do you want to show japanese place settings or other products of your own company? Display your Products FREE now!
|
http://www.alibaba.com/showroom/japanese-place-settings.html
|
CC-MAIN-2017-39
|
en
|
refinedweb
|
I in MAC.
Starting with NDK for Android – A Simple example. OR How to run a C code in android?
I have to make the change in the Android.mk file to include other files to compile.
This is the content of my Android.mk file
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_LDLIBS := -llog LOCAL_MODULE := ndksetup LOCAL_SRC_FILES := native.c test.c test_2.c include $(BUILD_SHARED_LIBRARY)
Here is my native.c code in which I am including those two files test.c and test2.c
#include <jni.h> #include <string.h> #include <android/log.h> // my test file #include "test.h" #include "test_2.h" #define DEBUG_TAG "NDKSetupActivity" void Java_com_ndksetup_NDKSetupActivity_printLog(JNIEnv * env, jobject this, jstring logString) { jboolean isCopy; const char * szLogString = (*env)->GetStringUTFChars(env, logString, &isCopy); __android_log_print(ANDROID_LOG_DEBUG, "TAGGGGG", "NDK: %s", szLogString); (*env)->ReleaseStringUTFChars(env, logString, szLogString); } int Java_com_ndksetup_NDKSetupActivity_fibonacci(int value) { int p = 8; printMe(); printMe2(); return p; }
|
http://www.coderzheaven.com/2012/04/28/include-multiple-files-compile-android-ndk/
|
CC-MAIN-2017-39
|
en
|
refinedweb
|
Till yet, we have only been using the simple types as parameters to methods. However, it is both correct and common to pass objects to methods. For instance, look at the following short Java program :
Here is an example program, demonstrates, how to use object as method parameter in Java:
/* Java Program Example - Java Use Objects as Parameters * In Java, Objects may be passed to methods */ class Test { int a, b; Test(int i, int j) { a = i; b = j; } /* return true if o is equal to invoking object */ boolean equalTo(Test o) { if(o.a == a && o.b == b) { return true; } else { return false; } } } public class JavaProgram { public static void main(String args[]) { Test obj1 = new Test(100, 22); Test obj2 = new Test(100, 22); Test obj3 = new Test(-1, -1); System.out.println("obj1 == obj2 : " + obj1.equalTo(obj2)); System.out.println("obj1 == obj3 : " + obj1.equalTo(obj3)); } }
When the above Java program is compile and executed, it will produce the following output:
As you can see, the equalTo() method within Test compares two objects for equality and returns the result i.e., it compares the invoking objects with the one that it is passed. If they holds the same values, then the method returns true, otherwise false.
Notice that the parameter o in method named equalTo(), specifies Test as its type. Although Test is a class type created by the program, it is used in simply the same way as Java's built-in types.
One of the most common uses of the object parameters involves constructors. Often, you will want to construct a new object so that it is initially the same as some existing object. To perform this, you must define a constructor that takes an object of its class as a parameter. For example, here this version of the Box allows one object to initialize another :
/* Java Program Example - Java Use Objects as Parameters * In this program, Box allows one object to * initialize another */ class Box { double width; double height; double depth; /* notice this constructor, it takes an object of the type Box */ Box(Box ob) // pass object to the constructor { width = ob.width; height = ob.height; depth = ob.depth; } /* constructor used when all the dimensions specified */ Box(double wid, double hei, double dep) { width = wid; height = hei; depth = dep; } /* constructor used when no dimensions specified */ Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } /* constructor used when cube is created */ Box(double len) { width = height = depth = len; } /* compute and return the volume */ double volume() { return width * height * depth; } } class Overload { public static void main(String args[]) { /* create boxes using the various constructors */ Box mybox1 = new Box(100, 200, 150); Box mybox2 = new Box(); Box mycube = new Box(7); Box myclone = new Box(mybox1); // create a copy of mybox1 double vol; /* get the volume of the first box */ vol = mybox1.volume(); /* print the volume of the first box */ System.out.println("Volume of mybox1 is " + vol); /* get the volume of the second box */ vol = mybox2.volume(); /* print the volume of the second box */ System.out.println("Volume of mybox2 is " + vol); /* get the volume of the cube */ vol = mycube.volume(); /* print the volume of the cube */ System.out.println("Volume of cube is " + vol); /* get the volume of the clone */ vol = myclone.volume(); /* print the volume of the clone */ System.out.println("Volume of clone is " + vol); } }
When the above Java program is compile and executed, it will produce the following output:
As you will see, when you begin to create your own classes, giving many forms of the constructors is usually required to allow to be constructed in a convenient and efficient manner.
Java Programming Online Test
Tools
Calculator
Quick Links
|
https://codescracker.com/java/java-objects-as-parameters.htm
|
CC-MAIN-2017-39
|
en
|
refinedweb
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.